w

API 参考

数据结构

Task 对象

interface Task {
  id: string; // 唯一标识符
  text: string; // 任务描述
  completed: boolean; // 完成状态
  dueDate?: string; // 可选截止日期(ISO 格式)
  priority: "low" | "medium" | "high"; // 优先级
  createdAt: Date; // 创建时间戳
  completedAt?: Date; // 完成时间戳(如已完成)
}

HistoryRecord 对象

interface HistoryRecord {
  id: string; // 唯一标识符
  action: "created" | "completed" | "deleted" | "updated";
  description: string; // 人类可读描述
  timestamp: Date; // 操作时间戳
}

本地存储 API

存储键

  • todo-tasks:Task 对象数组
  • todo-history:HistoryRecord 对象数组

数据持久化

// 保存任务到本地存储
localStorage.setItem("todo-tasks", JSON.stringify(tasks));

// 从本地存储加载任务
const tasks = JSON.parse(localStorage.getItem("todo-tasks") || "[]");

// 保存历史到本地存储
localStorage.setItem("todo-history", JSON.stringify(history));

// 从本地存储加载历史
const history = JSON.parse(localStorage.getItem("todo-history") || "[]");

导出/导入 API

导出格式

{
  "tasks": [
    {
      "id": "abc123",
      "text": "Complete project",
      "completed": false,
      "dueDate": "2024-02-15",
      "priority": "high",
      "createdAt": "2024-02-01T10:00:00.000Z",
      "completedAt": null
    }
  ],
  "exportDate": "2024-02-01T10:00:00.000Z"
}

导入验证

function validateImportData(data) {
  if (!data.tasks || !Array.isArray(data.tasks)) {
    throw new Error("Invalid data format: tasks array required");
  }

  data.tasks.forEach((task) => {
    if (!task.id || !task.text || typeof task.completed !== "boolean") {
      throw new Error("Invalid task format");
    }
  });

  return true;
}

事件系统

任务事件

// 任务创建
window.dispatchEvent(
  new CustomEvent("taskCreated", {
    detail: { task: newTask },
  }),
);

// 任务完成
window.dispatchEvent(
  new CustomEvent("taskCompleted", {
    detail: { task: completedTask },
  }),
);

// 任务更新
window.dispatchEvent(
  new CustomEvent("taskUpdated", {
    detail: { task: updatedTask },
  }),
);

// 任务删除
window.dispatchEvent(
  new CustomEvent("taskDeleted", {
    detail: { taskId: deletedTaskId },
  }),
);

历史事件

// 添加历史记录
window.dispatchEvent(
  new CustomEvent("historyAdded", {
    detail: { record: newRecord },
  }),
);

工具函数

ID 生成

function generateId() {
  return Math.random().toString(36).substr(2, 9);
}

日期工具

function getTomorrow() {
  const tomorrow = new Date();
  tomorrow.setDate(tomorrow.getDate() + 1);
  return tomorrow.toISOString().split("T")[0];
}

function isOverdue(dueDate) {
  return new Date(dueDate) < new Date();
}

function formatDate(date) {
  return new Intl.DateTimeFormat("en-US", {
    year: "numeric",
    month: "short",
    day: "numeric",
  }).format(new Date(date));
}

function formatTimeAgo(date) {
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  const minutes = Math.floor(diff / 60000);
  const hours = Math.floor(diff / 3600000);
  const days = Math.floor(diff / 86400000);

  if (days > 0) return `${days} days ago`;
  if (hours > 0) return `${hours} hours ago`;
  if (minutes > 0) return `${minutes} minutes ago`;
  return "Just now";
}

任务排序

function sortTasks(tasks) {
  return tasks.sort((a, b) => {
    // 优先级排序
    const priorityOrder = { high: 3, medium: 2, low: 1 };
    const priorityDiff = priorityOrder[b.priority] - priorityOrder[a.priority];
    if (priorityDiff !== 0) return priorityDiff;

    // 截止日期排序
    if (a.dueDate && b.dueDate) {
      return new Date(a.dueDate).getTime() - new Date(b.dueDate).getTime();
    }
    if (a.dueDate) return -1;
    if (b.dueDate) return 1;

    // 创建时间排序
    return b.createdAt.getTime() - a.createdAt.getTime();
  });
}

浏览器兼容性

所需 API

  • localStorage — 数据持久化
  • JSON.parse/stringify — 数据序列化
  • CustomEvent — 事件系统
  • Intl.DateTimeFormat — 日期格式化

支持的浏览器

  • Chrome 51+
  • Firefox 50+
  • Safari 10+
  • Edge 12+

错误处理

常见错误

try {
  const tasks = JSON.parse(localStorage.getItem("todo-tasks"));
} catch (error) {
  console.error("Failed to load tasks:", error);
  // 回退到空数组
  tasks = [];
}

数据验证

function validateTask(task) {
  const errors = [];

  if (!task.text || task.text.trim().length === 0) {
    errors.push("Task text is required");
  }

  if (!["low", "medium", "high"].includes(task.priority)) {
    errors.push("Invalid priority level");
  }

  if (task.dueDate && isNaN(Date.parse(task.dueDate))) {
    errors.push("Invalid due date format");
  }

  return errors;
}

性能考虑

大型任务列表

// 大列表分页
function getTasksPage(tasks, page = 1, pageSize = 50) {
  const start = (page - 1) * pageSize;
  const end = start + pageSize;
  return tasks.slice(start, end);
}

// 虚拟滚动支持
function getVisibleTasks(tasks, scrollTop, viewportHeight, itemHeight) {
  const startIndex = Math.floor(scrollTop / itemHeight);
  const visibleCount = Math.ceil(viewportHeight / itemHeight);
  return tasks.slice(startIndex, startIndex + visibleCount);
}

内存管理

// 限制历史记录数量
function addHistoryRecord(history, record, maxRecords = 100) {
  history.unshift(record);
  if (history.length > maxRecords) {
    history = history.slice(0, maxRecords);
  }
  return history;
}

// 清理旧已完成任务
function cleanupOldTasks(tasks, daysToKeep = 30) {
  const cutoff = new Date();
  cutoff.setDate(cutoff.getDate() - daysToKeep);

  return tasks.filter((task) => !task.completed || task.completedAt > cutoff);
}

集成示例

外部工具集成

// 导出到外部日历
function exportToCalendar(tasks) {
  const calendarEvents = tasks
    .filter((task) => task.dueDate && !task.completed)
    .map((task) => ({
      title: task.text,
      start: task.dueDate,
      priority: task.priority,
    }));

  // 生成日历文件或发送到 API
  return calendarEvents;
}

// 从外部源导入
async function importFromExternal(source) {
  try {
    const response = await fetch(source);
    const data = await response.json();

    if (validateImportData(data)) {
      return data.tasks;
    }
  } catch (error) {
    console.error("Import failed:", error);
    throw error;
  }
}

Webhook 集成

// 任务完成时发送 Webhook
async function sendWebhook(task, webhookUrl) {
  try {
    await fetch(webhookUrl, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        event: "taskCompleted",
        task: task,
        timestamp: new Date().toISOString(),
      }),
    });
  } catch (error) {
    console.error("Webhook failed:", error);
  }
}

下一步

查看使用示例了解实际应用场景,或浏览相关工具探索互补工具。

这个页面对您有帮助吗?