feat(工具箱): 添加新工具
- 待办事项 - Base64 字符串编码 / 解码 - URL 编码 / 解码 - 文本结构转换 - 转换 HTML 实体 - CSV 编辑 - frp 配置文件生成 - Minecraft UUID 转换 - Minecraft 区块位置计算 - 生成 Dynmap renderdata
This commit is contained in:
@@ -0,0 +1,797 @@
|
||||
// 待办事项数据模型
|
||||
//
|
||||
// 数据文件(todo-data.json)结构(版本 2):
|
||||
// {
|
||||
// "type": "frost-navigation/todo-list",
|
||||
// "schemaVersion": 2,
|
||||
// "updatedAt": "2026-11-17T08:00:00.000Z",
|
||||
// "categories": [
|
||||
// {
|
||||
// "id": "…",
|
||||
// "name": "默认",
|
||||
// "color": "#0894FA",
|
||||
// "createdAt": "…"
|
||||
// }
|
||||
// ],
|
||||
// "tasks": [
|
||||
// {
|
||||
// "id": "…",
|
||||
// "title": "…",
|
||||
// "note": "…",
|
||||
// "done": false,
|
||||
// "priority": "normal",
|
||||
// "tags": ["…"],
|
||||
// "dueDate": "2026-11-18",
|
||||
// "categoryId": "…",
|
||||
// "createdAt": "…",
|
||||
// "updatedAt": "…",
|
||||
// "completedAt": null
|
||||
// }
|
||||
// ]
|
||||
// }
|
||||
//
|
||||
// 版本升级约定:
|
||||
// 1. 数据结构发生变化时,将 CURRENT_DATA_VERSION 加 1;
|
||||
// 2. 在 MIGRATIONS 中新增“从旧版本升级到下一版本”的函数(键为旧版本号);
|
||||
// 3. 迁移函数只负责结构转换,不依赖组件和浏览器 API,便于单独测试;
|
||||
// 4. 打开旧版本数据时,由调用方在写入升级后的数据前原样备份原文件(见 todo-storage.js)。
|
||||
//
|
||||
// 版本 0 为历史格式:没有 schemaVersion 字段,内容可能是任务数组或 { tasks: [] },
|
||||
// 且任务字段命名不统一(text / content、completed / isDone、deadline 等)。
|
||||
// 版本 1 为引入待办分类前的格式:只有 tasks,没有 categories,任务也没有 categoryId。
|
||||
// 版本 2 新增 categories(待办分类),任务通过 categoryId 关联分类。
|
||||
|
||||
import { v4 as uuidV4 } from 'uuid';
|
||||
|
||||
/** 数据类型标识 */
|
||||
export const DATA_TYPE = 'frost-navigation/todo-list';
|
||||
|
||||
/** 数据文件名 */
|
||||
export const DATA_FILE_NAME = 'todo-data.json';
|
||||
|
||||
/** 当前数据版本 */
|
||||
export const CURRENT_DATA_VERSION = 2;
|
||||
|
||||
/** 默认分类 ID(旧版本数据升级时使用的分类) */
|
||||
export const DEFAULT_CATEGORY_ID = 'default';
|
||||
|
||||
/** 默认分类名称 */
|
||||
export const DEFAULT_CATEGORY_NAME = '默认';
|
||||
|
||||
/** 分类可选颜色 */
|
||||
export const CATEGORY_COLORS = [
|
||||
'#0894FA',
|
||||
'#00A870',
|
||||
'#ED7B2F',
|
||||
'#E34D59',
|
||||
'#14B8A6',
|
||||
'#F59E0B',
|
||||
'#2F54EB',
|
||||
'#8C8C8C',
|
||||
];
|
||||
|
||||
/** 分类名称最大长度 */
|
||||
const MAX_CATEGORY_NAME_LENGTH = 20;
|
||||
|
||||
/** 优先级 */
|
||||
export const PRIORITY_VALUES = ['high', 'normal', 'low'];
|
||||
|
||||
/** 优先级选项(用于界面下拉框) */
|
||||
export const PRIORITY_OPTIONS = [
|
||||
{ label: '高', value: 'high' },
|
||||
{ label: '普通', value: 'normal' },
|
||||
{ label: '低', value: 'low' },
|
||||
];
|
||||
|
||||
/** 优先级名称 */
|
||||
const PRIORITY_LABELS = {
|
||||
high: '高',
|
||||
normal: '普通',
|
||||
low: '低',
|
||||
};
|
||||
|
||||
/** 旧数据中可能出现的优先级写法 */
|
||||
const PRIORITY_ALIASES = {
|
||||
'高': 'high',
|
||||
'中': 'normal',
|
||||
'普通': 'normal',
|
||||
'低': 'low',
|
||||
};
|
||||
|
||||
/** 单条待办最多保存的标签数量 */
|
||||
const MAX_TAGS = 10;
|
||||
|
||||
/** 标签最大长度 */
|
||||
const MAX_TAG_LENGTH = 24;
|
||||
|
||||
/** 标题最大长度 */
|
||||
const MAX_TITLE_LENGTH = 200;
|
||||
|
||||
/** 备注最大长度 */
|
||||
const MAX_NOTE_LENGTH = 2000;
|
||||
|
||||
/** 是否为普通对象 */
|
||||
function isPlainObject(value) {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
|
||||
/** 从对象中按优先级取出第一个有值的字段 */
|
||||
function pickDefined(source, keys) {
|
||||
if (!isPlainObject(source)) return undefined;
|
||||
for (let i = 0; i < keys.length; i += 1) {
|
||||
const value = source[keys[i]];
|
||||
if (value !== undefined && value !== null) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** 将时间值转换为 ISO 字符串 */
|
||||
function toIsoTime(value) {
|
||||
|
||||
if (value === undefined || value === null || value === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (typeof value === 'number' && Number.isFinite(value)) {
|
||||
// 兼容以秒为单位的时间戳(10 位数)
|
||||
const timestamp = value > 1e11 ? value : value * 1000;
|
||||
const date = new Date(timestamp);
|
||||
return Number.isNaN(date.getTime()) ? null : date.toISOString();
|
||||
}
|
||||
|
||||
if (typeof value === 'string') {
|
||||
const text = value.trim();
|
||||
if (!text) {
|
||||
return null;
|
||||
}
|
||||
if (/^\d+$/.test(text)) {
|
||||
return toIsoTime(Number(text));
|
||||
}
|
||||
const date = new Date(text);
|
||||
return Number.isNaN(date.getTime()) ? null : date.toISOString();
|
||||
}
|
||||
|
||||
return null;
|
||||
|
||||
}
|
||||
|
||||
/** 将日期对象格式化为 YYYY-MM-DD */
|
||||
function formatDate(date) {
|
||||
const year = date.getFullYear();
|
||||
const month = String(date.getMonth() + 1).padStart(2, '0');
|
||||
const day = String(date.getDate()).padStart(2, '0');
|
||||
return `${year}-${month}-${day}`;
|
||||
}
|
||||
|
||||
/** 将日期值规范化为 YYYY-MM-DD(无效值返回空字符串) */
|
||||
function normalizeDateString(value) {
|
||||
|
||||
if (value === undefined || value === null || value === '') {
|
||||
return '';
|
||||
}
|
||||
|
||||
if (value instanceof Date) {
|
||||
return Number.isNaN(value.getTime()) ? '' : formatDate(value);
|
||||
}
|
||||
|
||||
if (typeof value === 'number' && Number.isFinite(value)) {
|
||||
const timestamp = value > 1e11 ? value : value * 1000;
|
||||
const date = new Date(timestamp);
|
||||
return Number.isNaN(date.getTime()) ? '' : formatDate(date);
|
||||
}
|
||||
|
||||
const text = String(value).trim();
|
||||
if (!text) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const match = text.match(/^(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})$/);
|
||||
if (!match) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const year = Number(match[1]);
|
||||
const month = Number(match[2]);
|
||||
const day = Number(match[3]);
|
||||
|
||||
if (month < 1 || month > 12 || day < 1 || day > 31) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const date = new Date(year, month - 1, day);
|
||||
|
||||
// 排除 2 月 30 日之类的非法日期
|
||||
if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return `${match[1]}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
|
||||
|
||||
}
|
||||
|
||||
/** 规范化标题 */
|
||||
function normalizeTitle(value) {
|
||||
if (value === undefined || value === null) {
|
||||
return '';
|
||||
}
|
||||
return String(value).replace(/\s+/g, ' ').trim().slice(0, MAX_TITLE_LENGTH);
|
||||
}
|
||||
|
||||
/** 规范化备注 */
|
||||
function normalizeNote(value) {
|
||||
if (value === undefined || value === null) {
|
||||
return '';
|
||||
}
|
||||
return String(value).replace(/\r\n/g, '\n').trim().slice(0, MAX_NOTE_LENGTH);
|
||||
}
|
||||
|
||||
/** 规范化优先级 */
|
||||
function normalizePriority(value) {
|
||||
|
||||
if (typeof value === 'number' && Number.isFinite(value)) {
|
||||
if (value >= 3) return 'high';
|
||||
if (value <= 1) return 'low';
|
||||
return 'normal';
|
||||
}
|
||||
|
||||
if (typeof value === 'string') {
|
||||
const text = value.trim().toLowerCase();
|
||||
if (PRIORITY_VALUES.includes(text)) {
|
||||
return text;
|
||||
}
|
||||
if (PRIORITY_ALIASES[text]) {
|
||||
return PRIORITY_ALIASES[text];
|
||||
}
|
||||
}
|
||||
|
||||
return 'normal';
|
||||
|
||||
}
|
||||
|
||||
/** 规范化标签 */
|
||||
function normalizeTags(value) {
|
||||
|
||||
let list = [];
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
list = value;
|
||||
} else if (typeof value === 'string') {
|
||||
list = value.split(/[,,、;;]+/);
|
||||
}
|
||||
|
||||
const result = [];
|
||||
|
||||
for (let i = 0; i < list.length; i += 1) {
|
||||
|
||||
const item = list[i];
|
||||
|
||||
if (typeof item !== 'string' && typeof item !== 'number') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const tag = String(item).trim().slice(0, MAX_TAG_LENGTH);
|
||||
|
||||
if (!tag || result.includes(tag)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
result.push(tag);
|
||||
|
||||
if (result.length >= MAX_TAGS) {
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
return result;
|
||||
|
||||
}
|
||||
|
||||
/** 规范化分类名称 */
|
||||
function normalizeCategoryName(value) {
|
||||
if (value === undefined || value === null) {
|
||||
return '';
|
||||
}
|
||||
return String(value).replace(/\s+/g, ' ').trim().slice(0, MAX_CATEGORY_NAME_LENGTH);
|
||||
}
|
||||
|
||||
/** 规范化分类颜色(仅支持十六进制颜色,无法识别时使用第一个预设颜色) */
|
||||
function normalizeCategoryColor(value) {
|
||||
|
||||
if (typeof value !== 'string') {
|
||||
return CATEGORY_COLORS[0];
|
||||
}
|
||||
|
||||
const text = value.trim();
|
||||
|
||||
if (/^#[0-9A-Fa-f]{6}$/.test(text)) {
|
||||
return text.toUpperCase();
|
||||
}
|
||||
|
||||
if (/^#[0-9A-Fa-f]{3}$/.test(text)) {
|
||||
const hex = text.slice(1).split('').map((char) => char + char).join('');
|
||||
return `#${hex.toUpperCase()}`;
|
||||
}
|
||||
|
||||
return CATEGORY_COLORS[0];
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 创建一条新的分类数据
|
||||
* @param {object} input 初始字段
|
||||
* @returns {{ id: string, name: string, color: string, createdAt: string }}
|
||||
*/
|
||||
export function createCategory(input = {}) {
|
||||
|
||||
const name = normalizeCategoryName(input.name);
|
||||
|
||||
return {
|
||||
id: typeof input.id === 'string' && input.id.trim() ? input.id.trim().slice(0, 64) : uuidV4(),
|
||||
name: name || DEFAULT_CATEGORY_NAME,
|
||||
color: normalizeCategoryColor(input.color),
|
||||
createdAt: toIsoTime(input.createdAt) ?? new Date().toISOString(),
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 规范化单条分类数据
|
||||
* @param {any} raw 原始数据
|
||||
* @param {number} index 在列表中的位置(用于生成兜底名称)
|
||||
* @returns {object | null} 规范化后的分类
|
||||
*/
|
||||
function normalizeCategory(raw, index = 0) {
|
||||
|
||||
if (typeof raw === 'string') {
|
||||
const name = normalizeCategoryName(raw);
|
||||
return name ? createCategory({ name }) : null;
|
||||
}
|
||||
|
||||
if (!isPlainObject(raw)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const name = normalizeCategoryName(pickDefined(raw, ['name', 'title', 'label']))
|
||||
|| `分类 ${index + 1}`;
|
||||
|
||||
return createCategory({
|
||||
id: pickDefined(raw, ['id', 'uuid', 'key']),
|
||||
name,
|
||||
color: pickDefined(raw, ['color', 'colour']),
|
||||
createdAt: pickDefined(raw, ['createdAt', 'createTime', 'createdTime']),
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
/** 规范化分类列表,并保证至少存在一个分类 */
|
||||
function normalizeCategories(list) {
|
||||
|
||||
if (!Array.isArray(list)) {
|
||||
return [createCategory({ id: DEFAULT_CATEGORY_ID, name: DEFAULT_CATEGORY_NAME })];
|
||||
}
|
||||
|
||||
const result = [];
|
||||
const usedIds = new Set();
|
||||
|
||||
for (let i = 0; i < list.length; i += 1) {
|
||||
|
||||
const category = normalizeCategory(list[i], i);
|
||||
|
||||
if (!category) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (usedIds.has(category.id)) {
|
||||
category.id = uuidV4();
|
||||
}
|
||||
|
||||
usedIds.add(category.id);
|
||||
result.push(category);
|
||||
|
||||
}
|
||||
|
||||
if (result.length === 0) {
|
||||
result.push(createCategory({ id: DEFAULT_CATEGORY_ID, name: DEFAULT_CATEGORY_NAME }));
|
||||
}
|
||||
|
||||
return result;
|
||||
|
||||
}
|
||||
|
||||
/** 获取优先级名称 */
|
||||
export function getPriorityLabel(priority) {
|
||||
return PRIORITY_LABELS[priority] ?? '普通';
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 规范化单条待办数据(兼容旧字段命名)
|
||||
* @param {any} raw 原始数据
|
||||
* @param {string[]} validCategoryIds 有效分类 ID 列表
|
||||
* @returns {object | null} 规范化后的待办,无法识别时返回 null
|
||||
*/
|
||||
export function normalizeTask(raw, validCategoryIds = []) {
|
||||
|
||||
if (typeof raw === 'string') {
|
||||
raw = { title: raw };
|
||||
}
|
||||
|
||||
if (!isPlainObject(raw)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const title = normalizeTitle(pickDefined(raw, ['title', 'text', 'content', 'name']));
|
||||
|
||||
if (!title) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const doneValue = pickDefined(raw, ['done', 'completed', 'isDone', 'checked', 'finished']);
|
||||
|
||||
const done = doneValue === true
|
||||
|| doneValue === 'true'
|
||||
|| doneValue === 1
|
||||
|| raw.status === 'done'
|
||||
|| raw.status === 'completed';
|
||||
|
||||
const now = new Date().toISOString();
|
||||
|
||||
const createdAt = toIsoTime(pickDefined(raw, ['createdAt', 'createTime', 'createdTime', 'created'])) ?? now;
|
||||
const updatedAt = toIsoTime(pickDefined(raw, ['updatedAt', 'updateTime', 'updatedTime', 'modifiedAt'])) ?? createdAt;
|
||||
const completedAt = done
|
||||
? (toIsoTime(pickDefined(raw, ['completedAt', 'doneAt', 'finishedAt'])) ?? updatedAt)
|
||||
: null;
|
||||
|
||||
const providedId = pickDefined(raw, ['id', 'uuid', 'key']);
|
||||
const id = typeof providedId === 'string' && providedId.trim()
|
||||
? providedId.trim().slice(0, 64)
|
||||
: uuidV4();
|
||||
|
||||
const providedCategoryId = pickDefined(raw, ['categoryId', 'category', 'listId']);
|
||||
const categoryId = typeof providedCategoryId === 'string' && validCategoryIds.includes(providedCategoryId)
|
||||
? providedCategoryId
|
||||
: (validCategoryIds[0] ?? '');
|
||||
|
||||
return {
|
||||
id,
|
||||
title,
|
||||
note: normalizeNote(pickDefined(raw, ['note', 'notes', 'desc', 'description', 'remark'])),
|
||||
done,
|
||||
priority: normalizePriority(pickDefined(raw, ['priority', 'level'])),
|
||||
tags: normalizeTags(pickDefined(raw, ['tags', 'labels', 'tag'])),
|
||||
dueDate: normalizeDateString(pickDefined(raw, ['dueDate', 'deadline', 'due', 'dueTime', 'endDate'])),
|
||||
categoryId,
|
||||
createdAt,
|
||||
updatedAt,
|
||||
completedAt,
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
/** 规范化待办列表,并处理重复 ID */
|
||||
function normalizeTasks(list, validCategoryIds = []) {
|
||||
|
||||
if (!Array.isArray(list)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const result = [];
|
||||
const usedIds = new Set();
|
||||
|
||||
for (let i = 0; i < list.length; i += 1) {
|
||||
|
||||
const task = normalizeTask(list[i], validCategoryIds);
|
||||
|
||||
if (!task) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (usedIds.has(task.id)) {
|
||||
task.id = uuidV4();
|
||||
}
|
||||
|
||||
usedIds.add(task.id);
|
||||
result.push(task);
|
||||
|
||||
}
|
||||
|
||||
return result;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 创建一条新的待办数据
|
||||
* @param {object} input 初始字段
|
||||
* @param {string[]} validCategoryIds 有效分类 ID 列表
|
||||
*/
|
||||
export function createTask(input = {}, validCategoryIds = []) {
|
||||
|
||||
const now = new Date().toISOString();
|
||||
|
||||
const categoryId = typeof input.categoryId === 'string' && validCategoryIds.includes(input.categoryId)
|
||||
? input.categoryId
|
||||
: (validCategoryIds[0] ?? '');
|
||||
|
||||
return {
|
||||
id: typeof input.id === 'string' && input.id.trim() ? input.id.trim() : uuidV4(),
|
||||
title: normalizeTitle(input.title),
|
||||
note: normalizeNote(input.note),
|
||||
done: false,
|
||||
priority: normalizePriority(input.priority),
|
||||
tags: normalizeTags(input.tags),
|
||||
dueDate: normalizeDateString(input.dueDate),
|
||||
categoryId,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
completedAt: null,
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 根据当前待办列表构建待写入文件的数据对象
|
||||
* @param {object[]} tasks 待办列表
|
||||
* @param {object[]} categories 分类列表
|
||||
*/
|
||||
export function buildTodoData(tasks = [], categories = []) {
|
||||
|
||||
const normalizedCategories = normalizeCategories(categories);
|
||||
const categoryIds = normalizedCategories.map((category) => category.id);
|
||||
|
||||
return {
|
||||
type: DATA_TYPE,
|
||||
schemaVersion: CURRENT_DATA_VERSION,
|
||||
updatedAt: new Date().toISOString(),
|
||||
categories: normalizedCategories,
|
||||
tasks: normalizeTasks(tasks, categoryIds),
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 序列化为数据文件内容(2 空格缩进,末尾保留换行)
|
||||
* @param {object} data 数据对象
|
||||
*/
|
||||
export function stringifyTodoData(data) {
|
||||
return `${JSON.stringify(data, null, 2)}\n`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 版本 0 升级到版本 1
|
||||
* 旧格式可能是任务数组,也可能是包含 tasks 字段的对象,任务字段由 normalizeTask 统一处理。
|
||||
*/
|
||||
function migrateVersion0ToVersion1(source) {
|
||||
|
||||
if (Array.isArray(source)) {
|
||||
return { tasks: source };
|
||||
}
|
||||
|
||||
if (isPlainObject(source) && Array.isArray(source.tasks)) {
|
||||
return { tasks: source.tasks };
|
||||
}
|
||||
|
||||
return { tasks: [] };
|
||||
|
||||
}
|
||||
|
||||
/** 版本迁移函数表:键为起始版本,值为升级到下一版本的函数 */
|
||||
const MIGRATIONS = {
|
||||
0: migrateVersion0ToVersion1,
|
||||
1: migrateVersion1ToVersion2,
|
||||
};
|
||||
|
||||
/**
|
||||
* 版本 1 升级到版本 2:新增待办分类
|
||||
* 旧数据中没有分类,统一归入“默认”分类,避免升级后待办无所属分类。
|
||||
*/
|
||||
function migrateVersion1ToVersion2(source) {
|
||||
|
||||
const sourceObject = isPlainObject(source) ? source : {};
|
||||
const tasks = Array.isArray(sourceObject.tasks) ? sourceObject.tasks : [];
|
||||
const categories = Array.isArray(sourceObject.categories) ? sourceObject.categories : [];
|
||||
|
||||
// 数据中已带有分类时直接保留(兼容手工调整过的数据)
|
||||
if (categories.length > 0) {
|
||||
return { ...sourceObject, tasks, categories };
|
||||
}
|
||||
|
||||
return {
|
||||
tasks: tasks.map((task) => (
|
||||
isPlainObject(task)
|
||||
? { ...task, categoryId: task.categoryId ?? DEFAULT_CATEGORY_ID }
|
||||
: task
|
||||
)),
|
||||
categories: [
|
||||
{
|
||||
id: DEFAULT_CATEGORY_ID,
|
||||
name: DEFAULT_CATEGORY_NAME,
|
||||
color: CATEGORY_COLORS[0],
|
||||
createdAt: new Date().toISOString(),
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断解析后的 JSON 是否可识别为待办事项数据。
|
||||
* 用于避免把文件夹中同名但不相关的 JSON 文件当作旧版本数据升级后覆盖。
|
||||
*/
|
||||
function isRecognizableTodoData(raw) {
|
||||
|
||||
if (Array.isArray(raw)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!isPlainObject(raw)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 声明了类型时必须是本工具的数据
|
||||
if (raw.type !== undefined) {
|
||||
return raw.type === DATA_TYPE;
|
||||
}
|
||||
|
||||
// 没有类型时,至少应具备待办数据结构(兼容旧格式)
|
||||
if (Array.isArray(raw.tasks)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return raw.schemaVersion !== undefined || raw.dataVersion !== undefined;
|
||||
|
||||
}
|
||||
|
||||
/** 读取数据中的版本号(无法识别时按版本 0 处理) */
|
||||
function getSourceVersion(raw) {
|
||||
|
||||
if (Array.isArray(raw)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (!isPlainObject(raw)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const value = pickDefined(raw, ['schemaVersion', 'dataVersion', 'version']);
|
||||
|
||||
if (value === undefined) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (typeof value === 'string' && /^\d+$/.test(value.trim())) {
|
||||
return Number(value.trim());
|
||||
}
|
||||
|
||||
if (typeof value === 'number' && Number.isInteger(value) && value >= 0) {
|
||||
return value;
|
||||
}
|
||||
|
||||
// 无法识别版本时按最旧的格式尝试升级
|
||||
return 0;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 将任意(旧)版本的数据升级到当前版本
|
||||
* @param {any} raw 已解析的 JSON 数据
|
||||
* @returns {{
|
||||
* ok: boolean,
|
||||
* error?: string,
|
||||
* data?: object,
|
||||
* fromVersion?: number,
|
||||
* toVersion?: number,
|
||||
* migrated?: boolean,
|
||||
* isFutureVersion?: boolean,
|
||||
* }} 升级结果
|
||||
*/
|
||||
export function migrateTodoData(raw) {
|
||||
|
||||
if (!isRecognizableTodoData(raw)) {
|
||||
return { ok: false, error: '无法识别的数据文件(不是待办事项数据)' };
|
||||
}
|
||||
|
||||
const fromVersion = getSourceVersion(raw);
|
||||
|
||||
if (fromVersion === null) {
|
||||
return { ok: false, error: '无法识别的数据格式,应为 JSON 对象或任务数组' };
|
||||
}
|
||||
|
||||
const now = new Date().toISOString();
|
||||
|
||||
// 数据版本高于当前版本:仅以只读方式展示,避免写入时丢失新版本中的字段
|
||||
if (fromVersion > CURRENT_DATA_VERSION) {
|
||||
|
||||
const source = Array.isArray(raw) ? { tasks: raw } : raw;
|
||||
const categories = normalizeCategories(source?.categories);
|
||||
const categoryIds = categories.map((category) => category.id);
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
data: {
|
||||
type: typeof source?.type === 'string' ? source.type : DATA_TYPE,
|
||||
schemaVersion: fromVersion,
|
||||
updatedAt: toIsoTime(source?.updatedAt) ?? now,
|
||||
categories,
|
||||
tasks: normalizeTasks(source?.tasks, categoryIds),
|
||||
},
|
||||
fromVersion,
|
||||
toVersion: fromVersion,
|
||||
migrated: false,
|
||||
isFutureVersion: true,
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
let payload = raw;
|
||||
|
||||
for (let version = fromVersion; version < CURRENT_DATA_VERSION; version += 1) {
|
||||
|
||||
const migrate = MIGRATIONS[version];
|
||||
|
||||
if (typeof migrate !== 'function') {
|
||||
return { ok: false, error: `缺少数据版本 ${version} 升级到 ${version + 1} 的迁移逻辑` };
|
||||
}
|
||||
|
||||
payload = migrate(payload);
|
||||
|
||||
}
|
||||
|
||||
const source = Array.isArray(payload)
|
||||
? { tasks: payload }
|
||||
: (isPlainObject(payload) ? payload : {});
|
||||
|
||||
if (!Array.isArray(source.tasks)) {
|
||||
return { ok: false, error: '数据文件缺少有效的任务列表(tasks 数组)' };
|
||||
}
|
||||
|
||||
if (source.categories !== undefined && !Array.isArray(source.categories)) {
|
||||
return { ok: false, error: '数据文件中的分类列表(categories)格式无效' };
|
||||
}
|
||||
|
||||
const categories = normalizeCategories(source.categories);
|
||||
const categoryIds = categories.map((category) => category.id);
|
||||
|
||||
const data = {
|
||||
type: DATA_TYPE,
|
||||
schemaVersion: CURRENT_DATA_VERSION,
|
||||
updatedAt: toIsoTime(source.updatedAt) ?? now,
|
||||
categories,
|
||||
tasks: normalizeTasks(source.tasks, categoryIds),
|
||||
};
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
data,
|
||||
fromVersion,
|
||||
toVersion: CURRENT_DATA_VERSION,
|
||||
migrated: fromVersion !== CURRENT_DATA_VERSION,
|
||||
isFutureVersion: false,
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @description 解析数据文件内容并升级到当前版本
|
||||
* @param {string} text 文件内容
|
||||
*/
|
||||
export function parseTodoDataText(text = '') {
|
||||
|
||||
const content = String(text ?? '').replace(/^\uFEFF/, '').trim();
|
||||
|
||||
if (!content) {
|
||||
return { ok: false, error: '数据内容为空' };
|
||||
}
|
||||
|
||||
let parsed = null;
|
||||
|
||||
try {
|
||||
parsed = JSON.parse(content);
|
||||
} catch (error) {
|
||||
return { ok: false, error: `数据不是有效的 JSON(${error.message})` };
|
||||
}
|
||||
|
||||
return migrateTodoData(parsed);
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user