dsh-matrix-todo 1.1.0 → 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/LICENSE +1 -1
- package/README.md +102 -165
- package/client.js +2 -2
- package/cordis.patch.yml +4 -4
- package/icon.svg +7 -7
- package/index.js +123 -123
- package/lib/store.js +511 -511
- package/locale/en.json +5 -5
- package/locale/zh.json +5 -5
- package/package.json +5 -5
package/lib/store.js
CHANGED
|
@@ -1,511 +1,511 @@
|
|
|
1
|
-
/** File-backed store for the four-quadrant todo plugin: one JSON document, serialized atomic writes. */
|
|
2
|
-
|
|
3
|
-
import { readFile, writeFile, rename, mkdir, copyFile } from 'node:fs/promises'
|
|
4
|
-
import { dirname, join } from 'node:path'
|
|
5
|
-
|
|
6
|
-
const VERSION = 1
|
|
7
|
-
const MAX_TODOS = 500
|
|
8
|
-
const TITLE_MAX = 200
|
|
9
|
-
const RADIUS_MIN = 0
|
|
10
|
-
const RADIUS_MAX = 24
|
|
11
|
-
const FONT_MIN = 11
|
|
12
|
-
const FONT_MAX = 17
|
|
13
|
-
const CORRUPT_UNBACKUPED = '数据文件损坏且无法备份,已停止写入以保护原文件'
|
|
14
|
-
|
|
15
|
-
/**
|
|
16
|
-
* Panel layout preferences, persisted next to the todos.
|
|
17
|
-
* `frame`: cards = four rounded cards, grid = outer border with a cross (田字格),
|
|
18
|
-
* cross = a true cross with no outer border. `tint`: soft pastel cell backgrounds.
|
|
19
|
-
*/
|
|
20
|
-
export const DEFAULT_SETTINGS = Object.freeze({
|
|
21
|
-
urgentSide: 'right',
|
|
22
|
-
frame: 'cross',
|
|
23
|
-
radius: 10,
|
|
24
|
-
tint: 'plain',
|
|
25
|
-
fontSize: 14,
|
|
26
|
-
dueFormat: 'countdown',
|
|
27
|
-
titleStyle: 'wrap',
|
|
28
|
-
colRatio: 0.5,
|
|
29
|
-
rowRatio: 0.5,
|
|
30
|
-
navLabel: '',
|
|
31
|
-
})
|
|
32
|
-
|
|
33
|
-
const NAV_LABEL_MAX = 24
|
|
34
|
-
|
|
35
|
-
const URGENT_SIDES = ['left', 'right']
|
|
36
|
-
const FRAMES = ['cards', 'grid', 'cross']
|
|
37
|
-
const TINTS = ['plain', 'soft']
|
|
38
|
-
const DUE_FORMATS = ['date', 'countdown']
|
|
39
|
-
const TITLE_STYLES = ['wrap', 'truncate']
|
|
40
|
-
const RATIO_MIN = 0.2
|
|
41
|
-
const RATIO_MAX = 0.8
|
|
42
|
-
|
|
43
|
-
/** Valid split ratio, or the default when the value is unusable. */
|
|
44
|
-
function sanitizeRatio(value) {
|
|
45
|
-
return typeof value === 'number' && Number.isFinite(value) && value >= RATIO_MIN && value <= RATIO_MAX
|
|
46
|
-
? value
|
|
47
|
-
: 0.5
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
/** Error with a stable code, so the HTTP layer can map it to a status. */
|
|
51
|
-
export class StoreError extends Error {
|
|
52
|
-
constructor(code, message) {
|
|
53
|
-
super(message)
|
|
54
|
-
this.name = 'StoreError'
|
|
55
|
-
this.code = code
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
function emptyDoc() {
|
|
60
|
-
return { version: VERSION, todos: [], settings: { ...DEFAULT_SETTINGS }, reordered: false, seeded: false }
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
const DAY_RE = /^\d{4}-\d{2}-\d{2}$/
|
|
64
|
-
|
|
65
|
-
/** `YYYY-MM-DD` that names a real calendar day, or null when absent/blank. */
|
|
66
|
-
function normalizeDueDate(raw) {
|
|
67
|
-
if (raw === undefined || raw === null || raw === '') return null
|
|
68
|
-
if (typeof raw !== 'string' || !DAY_RE.test(raw)) {
|
|
69
|
-
throw new StoreError('invalid-input', '截止日期格式应为 YYYY-MM-DD')
|
|
70
|
-
}
|
|
71
|
-
const [year, month, day] = raw.split('-').map(Number)
|
|
72
|
-
const date = new Date(year, month - 1, day)
|
|
73
|
-
if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) {
|
|
74
|
-
throw new StoreError('invalid-input', '截止日期不是真实存在的日期')
|
|
75
|
-
}
|
|
76
|
-
return raw
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
/** Lenient variant for rows read off disk: an unusable due date becomes null. */
|
|
80
|
-
function sanitizeDueDate(raw) {
|
|
81
|
-
try {
|
|
82
|
-
return normalizeDueDate(raw)
|
|
83
|
-
} catch {
|
|
84
|
-
return null
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
/** Unknown or malformed preference fields fall back to the default, never throw. */
|
|
89
|
-
function sanitizeSettings(value) {
|
|
90
|
-
const source = value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {}
|
|
91
|
-
return {
|
|
92
|
-
urgentSide: URGENT_SIDES.includes(source.urgentSide) ? source.urgentSide : DEFAULT_SETTINGS.urgentSide,
|
|
93
|
-
frame: FRAMES.includes(source.frame) ? source.frame : DEFAULT_SETTINGS.frame,
|
|
94
|
-
radius:
|
|
95
|
-
Number.isInteger(source.radius) && source.radius >= RADIUS_MIN && source.radius <= RADIUS_MAX
|
|
96
|
-
? source.radius
|
|
97
|
-
: DEFAULT_SETTINGS.radius,
|
|
98
|
-
tint: TINTS.includes(source.tint) ? source.tint : DEFAULT_SETTINGS.tint,
|
|
99
|
-
fontSize:
|
|
100
|
-
Number.isInteger(source.fontSize) && source.fontSize >= FONT_MIN && source.fontSize <= FONT_MAX
|
|
101
|
-
? source.fontSize
|
|
102
|
-
: DEFAULT_SETTINGS.fontSize,
|
|
103
|
-
dueFormat: DUE_FORMATS.includes(source.dueFormat) ? source.dueFormat : DEFAULT_SETTINGS.dueFormat,
|
|
104
|
-
titleStyle: TITLE_STYLES.includes(source.titleStyle) ? source.titleStyle : DEFAULT_SETTINGS.titleStyle,
|
|
105
|
-
colRatio: sanitizeRatio(source.colRatio),
|
|
106
|
-
rowRatio: sanitizeRatio(source.rowRatio),
|
|
107
|
-
navLabel:
|
|
108
|
-
typeof source.navLabel === 'string' ? source.navLabel.trim().slice(0, NAV_LABEL_MAX) : DEFAULT_SETTINGS.navLabel,
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
/** Contract id format: e_<base36 timestamp>_<4 random base36 chars>. */
|
|
113
|
-
function newId() {
|
|
114
|
-
const rand = Math.random().toString(36).slice(2, 6).padEnd(4, '0')
|
|
115
|
-
return `e_${Date.now().toString(36)}_${rand}`
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
function asRecord(value) {
|
|
119
|
-
if (value === undefined) return {}
|
|
120
|
-
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
121
|
-
throw new StoreError('invalid-input', '参数必须是对象')
|
|
122
|
-
}
|
|
123
|
-
return value
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
/** Title: trim the textual form, then require 1..200 characters. */
|
|
127
|
-
function normalizeTitle(raw) {
|
|
128
|
-
const title = raw === undefined || raw === null ? '' : String(raw).trim()
|
|
129
|
-
if (title.length === 0) throw new StoreError('invalid-input', '标题不能为空')
|
|
130
|
-
if (title.length > TITLE_MAX) throw new StoreError('invalid-input', `标题最长 ${TITLE_MAX} 字`)
|
|
131
|
-
return title
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
/** Quadrant flags default to false when absent; anything non-boolean is rejected. */
|
|
135
|
-
function normalizeFlag(raw, field) {
|
|
136
|
-
if (raw === undefined) return false
|
|
137
|
-
if (typeof raw !== 'boolean') throw new StoreError('invalid-input', `${field} 必须是布尔值`)
|
|
138
|
-
return raw
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
function requireId(raw) {
|
|
142
|
-
if (typeof raw !== 'string' || raw === '') throw new StoreError('invalid-input', 'id 必填')
|
|
143
|
-
return raw
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
/** Keep manually edited files tolerable: drop rows that cannot be rendered, keep every usable field. */
|
|
147
|
-
function sanitizeTodos(value) {
|
|
148
|
-
if (!Array.isArray(value)) return []
|
|
149
|
-
const out = []
|
|
150
|
-
for (const raw of value) {
|
|
151
|
-
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) continue
|
|
152
|
-
if (typeof raw.id !== 'string' || raw.id === '') continue
|
|
153
|
-
const title = typeof raw.title === 'string' ? raw.title.trim() : ''
|
|
154
|
-
if (title === '' || title.length > TITLE_MAX) continue
|
|
155
|
-
const done = raw.done === true
|
|
156
|
-
const createdAt = typeof raw.createdAt === 'string' ? raw.createdAt : new Date().toISOString()
|
|
157
|
-
out.push({
|
|
158
|
-
id: raw.id,
|
|
159
|
-
title,
|
|
160
|
-
important: raw.important === true,
|
|
161
|
-
urgent: raw.urgent === true,
|
|
162
|
-
done,
|
|
163
|
-
dueDate: sanitizeDueDate(raw.dueDate),
|
|
164
|
-
createdAt,
|
|
165
|
-
updatedAt: typeof raw.updatedAt === 'string' ? raw.updatedAt : createdAt,
|
|
166
|
-
completedAt: done && typeof raw.completedAt === 'string' ? raw.completedAt : null,
|
|
167
|
-
})
|
|
168
|
-
}
|
|
169
|
-
return out
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
/** Read the document; unreadable shape or unparseable JSON is reported as corrupt, not fatal. */
|
|
173
|
-
async function readDoc(file) {
|
|
174
|
-
let raw
|
|
175
|
-
try {
|
|
176
|
-
raw = await readFile(file, 'utf8')
|
|
177
|
-
} catch (err) {
|
|
178
|
-
if (err.code === 'ENOENT') return { doc: emptyDoc(), corrupt: false }
|
|
179
|
-
throw new StoreError('io-error', `无法读取待办数据:${err.message}`)
|
|
180
|
-
}
|
|
181
|
-
try {
|
|
182
|
-
const doc = JSON.parse(raw)
|
|
183
|
-
if (!doc || typeof doc !== 'object' || Array.isArray(doc) || !Array.isArray(doc.todos)) {
|
|
184
|
-
throw new Error('shape')
|
|
185
|
-
}
|
|
186
|
-
return { doc, corrupt: false }
|
|
187
|
-
} catch {
|
|
188
|
-
return { doc: emptyDoc(), corrupt: true }
|
|
189
|
-
}
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
/** Backup name next to the data file: todos.json -> todos.corrupt-<timestamp>.json */
|
|
193
|
-
function corruptBackupPath(file) {
|
|
194
|
-
return `${file.replace(/\.json$/i, '')}.corrupt-${Date.now()}.json`
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
export function createStore({ file } = {}) {
|
|
198
|
-
if (typeof file !== 'string' || file === '') throw new StoreError('invalid-input', '数据文件路径必填')
|
|
199
|
-
const dataFile = file
|
|
200
|
-
const state = { todos: [], settings: { ...DEFAULT_SETTINGS }, reordered: false, seeded: false, corrupt: false, sealed: false }
|
|
201
|
-
let queue = Promise.resolve()
|
|
202
|
-
let closed = false
|
|
203
|
-
|
|
204
|
-
/** Latest in-memory todos, copied so callers cannot mutate the source of truth. */
|
|
205
|
-
function snapshot() {
|
|
206
|
-
return state.todos.map((todo) => ({ ...todo }))
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
async function persist() {
|
|
210
|
-
if (state.sealed) throw new StoreError('io-error', CORRUPT_UNBACKUPED)
|
|
211
|
-
const snapshotText = JSON.stringify(
|
|
212
|
-
{ version: VERSION, todos: state.todos, settings: state.settings, reordered: state.reordered, seeded: state.seeded },
|
|
213
|
-
null,
|
|
214
|
-
2,
|
|
215
|
-
)
|
|
216
|
-
const write = queue.then(async () => {
|
|
217
|
-
await mkdir(dirname(dataFile), { recursive: true })
|
|
218
|
-
const tmp = `${dataFile}.tmp`
|
|
219
|
-
await writeFile(tmp, snapshotText, 'utf8')
|
|
220
|
-
await rename(tmp, dataFile)
|
|
221
|
-
})
|
|
222
|
-
queue = write.catch(() => {})
|
|
223
|
-
try {
|
|
224
|
-
await write
|
|
225
|
-
} catch (err) {
|
|
226
|
-
if (err instanceof StoreError) throw err
|
|
227
|
-
throw new StoreError('io-error', `待办数据写入失败:${err.message}`)
|
|
228
|
-
}
|
|
229
|
-
}
|
|
230
|
-
|
|
231
|
-
async function guard(fn) {
|
|
232
|
-
try {
|
|
233
|
-
return await fn()
|
|
234
|
-
} catch (err) {
|
|
235
|
-
if (err instanceof StoreError) throw err
|
|
236
|
-
throw new StoreError('io-error', `待办数据写入失败:${err.message}`)
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
return {
|
|
241
|
-
async load() {
|
|
242
|
-
const { doc, corrupt } = await readDoc(dataFile)
|
|
243
|
-
state.todos = sanitizeTodos(doc.todos)
|
|
244
|
-
state.settings = sanitizeSettings(doc.settings)
|
|
245
|
-
state.reordered = doc.reordered === true
|
|
246
|
-
// A store that already holds rows, or one that was seeded before, never
|
|
247
|
-
// gets onboarding rows again — deleting the guide must stick.
|
|
248
|
-
state.seeded = corrupt || doc.seeded === true || state.todos.length > 0
|
|
249
|
-
// Until someone drags a row, the list order is derived: newest first. Once
|
|
250
|
-
// a drag is saved, the stored array order is the user's own order.
|
|
251
|
-
if (!state.reordered) state.todos.sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)))
|
|
252
|
-
state.corrupt = corrupt
|
|
253
|
-
state.sealed = false
|
|
254
|
-
if (!corrupt) return { corrupt: false }
|
|
255
|
-
const backup = corruptBackupPath(dataFile)
|
|
256
|
-
try {
|
|
257
|
-
await copyFile(dataFile, backup)
|
|
258
|
-
} catch {
|
|
259
|
-
state.sealed = true
|
|
260
|
-
throw new StoreError('io-error', CORRUPT_UNBACKUPED)
|
|
261
|
-
}
|
|
262
|
-
await guard(persist)
|
|
263
|
-
return { corrupt: true, backup }
|
|
264
|
-
},
|
|
265
|
-
|
|
266
|
-
close() {
|
|
267
|
-
if (closed) return queue
|
|
268
|
-
closed = true
|
|
269
|
-
return queue
|
|
270
|
-
},
|
|
271
|
-
|
|
272
|
-
list() {
|
|
273
|
-
return snapshot()
|
|
274
|
-
},
|
|
275
|
-
|
|
276
|
-
/** True once onboarding rows were written, or when the store was never empty. */
|
|
277
|
-
seeded() {
|
|
278
|
-
return state.seeded
|
|
279
|
-
},
|
|
280
|
-
|
|
281
|
-
/**
|
|
282
|
-
* One-time onboarding rows for a brand-new store. The client sends localized
|
|
283
|
-
* titles; the flag makes the call idempotent and stops the guide from coming
|
|
284
|
-
* back after the user deletes it.
|
|
285
|
-
*/
|
|
286
|
-
async seed(input = {}) {
|
|
287
|
-
if (state.seeded) return { added: 0 }
|
|
288
|
-
const source = asRecord(input)
|
|
289
|
-
const rows = Array.isArray(source.items) ? source.items.slice(0, 32) : []
|
|
290
|
-
const now = Date.now()
|
|
291
|
-
const added = []
|
|
292
|
-
rows.forEach((raw, index) => {
|
|
293
|
-
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return
|
|
294
|
-
const title = typeof raw.title === 'string' ? raw.title.trim() : ''
|
|
295
|
-
if (title === '' || title.length > TITLE_MAX) return
|
|
296
|
-
const createdAt = new Date(now - index * 1000).toISOString()
|
|
297
|
-
added.push({
|
|
298
|
-
id: newId(),
|
|
299
|
-
title,
|
|
300
|
-
important: raw.important === true,
|
|
301
|
-
urgent: raw.urgent === true,
|
|
302
|
-
done: false,
|
|
303
|
-
dueDate: sanitizeDueDate(raw.dueDate),
|
|
304
|
-
createdAt,
|
|
305
|
-
updatedAt: createdAt,
|
|
306
|
-
completedAt: null,
|
|
307
|
-
})
|
|
308
|
-
})
|
|
309
|
-
state.seeded = true
|
|
310
|
-
if (added.length > 0) state.todos = [...added, ...state.todos]
|
|
311
|
-
await guard(persist)
|
|
312
|
-
return { added: added.length }
|
|
313
|
-
},
|
|
314
|
-
|
|
315
|
-
/** Current layout preferences (a copy; callers cannot mutate the source of truth). */
|
|
316
|
-
settings() {
|
|
317
|
-
return { ...state.settings }
|
|
318
|
-
},
|
|
319
|
-
|
|
320
|
-
/** Merge validated preference fields and persist them with the todos. */
|
|
321
|
-
async saveSettings(input = {}) {
|
|
322
|
-
const source = asRecord(input)
|
|
323
|
-
const next = { ...state.settings }
|
|
324
|
-
if (source.urgentSide !== undefined) {
|
|
325
|
-
if (!URGENT_SIDES.includes(source.urgentSide)) {
|
|
326
|
-
throw new StoreError('invalid-input', 'urgentSide 只能是 left 或 right')
|
|
327
|
-
}
|
|
328
|
-
next.urgentSide = source.urgentSide
|
|
329
|
-
}
|
|
330
|
-
if (source.frame !== undefined) {
|
|
331
|
-
if (!FRAMES.includes(source.frame)) {
|
|
332
|
-
throw new StoreError('invalid-input', 'frame 只能是 cards、grid 或 cross')
|
|
333
|
-
}
|
|
334
|
-
next.frame = source.frame
|
|
335
|
-
}
|
|
336
|
-
if (source.tint !== undefined) {
|
|
337
|
-
if (!TINTS.includes(source.tint)) {
|
|
338
|
-
throw new StoreError('invalid-input', 'tint 只能是 plain 或 soft')
|
|
339
|
-
}
|
|
340
|
-
next.tint = source.tint
|
|
341
|
-
}
|
|
342
|
-
if (source.dueFormat !== undefined) {
|
|
343
|
-
if (!DUE_FORMATS.includes(source.dueFormat)) {
|
|
344
|
-
throw new StoreError('invalid-input', 'dueFormat 只能是 date 或 countdown')
|
|
345
|
-
}
|
|
346
|
-
next.dueFormat = source.dueFormat
|
|
347
|
-
}
|
|
348
|
-
if (source.titleStyle !== undefined) {
|
|
349
|
-
if (!TITLE_STYLES.includes(source.titleStyle)) {
|
|
350
|
-
throw new StoreError('invalid-input', 'titleStyle 只能是 wrap 或 truncate')
|
|
351
|
-
}
|
|
352
|
-
next.titleStyle = source.titleStyle
|
|
353
|
-
}
|
|
354
|
-
for (const field of ['colRatio', 'rowRatio']) {
|
|
355
|
-
if (source[field] === undefined) continue
|
|
356
|
-
if (
|
|
357
|
-
typeof source[field] !== 'number' ||
|
|
358
|
-
!Number.isFinite(source[field]) ||
|
|
359
|
-
source[field] < RATIO_MIN ||
|
|
360
|
-
source[field] > RATIO_MAX
|
|
361
|
-
) {
|
|
362
|
-
throw new StoreError('invalid-input', `${field} 必须是 ${RATIO_MIN}–${RATIO_MAX} 之间的数字`)
|
|
363
|
-
}
|
|
364
|
-
next[field] = source[field]
|
|
365
|
-
}
|
|
366
|
-
if (source.navLabel !== undefined) {
|
|
367
|
-
if (typeof source.navLabel !== 'string') {
|
|
368
|
-
throw new StoreError('invalid-input', 'navLabel 必须是字符串')
|
|
369
|
-
}
|
|
370
|
-
const label = source.navLabel.trim()
|
|
371
|
-
if (label.length > NAV_LABEL_MAX) {
|
|
372
|
-
throw new StoreError('invalid-input', `侧边栏名称最长 ${NAV_LABEL_MAX} 字`)
|
|
373
|
-
}
|
|
374
|
-
next.navLabel = label
|
|
375
|
-
}
|
|
376
|
-
if (source.fontSize !== undefined) {
|
|
377
|
-
if (!Number.isInteger(source.fontSize) || source.fontSize < FONT_MIN || source.fontSize > FONT_MAX) {
|
|
378
|
-
throw new StoreError('invalid-input', `fontSize 必须是 ${FONT_MIN}-${FONT_MAX} 的整数`)
|
|
379
|
-
}
|
|
380
|
-
next.fontSize = source.fontSize
|
|
381
|
-
}
|
|
382
|
-
if (source.radius !== undefined) {
|
|
383
|
-
if (!Number.isInteger(source.radius) || source.radius < RADIUS_MIN || source.radius > RADIUS_MAX) {
|
|
384
|
-
throw new StoreError('invalid-input', `radius 必须是 ${RADIUS_MIN}-${RADIUS_MAX} 的整数`)
|
|
385
|
-
}
|
|
386
|
-
next.radius = source.radius
|
|
387
|
-
}
|
|
388
|
-
state.settings = next
|
|
389
|
-
await guard(persist)
|
|
390
|
-
return { ...next }
|
|
391
|
-
},
|
|
392
|
-
|
|
393
|
-
async create(input = {}) {
|
|
394
|
-
const source = asRecord(input)
|
|
395
|
-
if (state.todos.length >= MAX_TODOS) {
|
|
396
|
-
throw new StoreError('invalid-input', `待办最多 ${MAX_TODOS} 条`)
|
|
397
|
-
}
|
|
398
|
-
const title = normalizeTitle(source.title)
|
|
399
|
-
const important = normalizeFlag(source.important, 'important')
|
|
400
|
-
const urgent = normalizeFlag(source.urgent, 'urgent')
|
|
401
|
-
const dueDate = normalizeDueDate(source.dueDate)
|
|
402
|
-
const now = new Date().toISOString()
|
|
403
|
-
// Newest first inside its quadrant: the array order is the display order.
|
|
404
|
-
state.todos.unshift({
|
|
405
|
-
id: newId(),
|
|
406
|
-
title,
|
|
407
|
-
important,
|
|
408
|
-
urgent,
|
|
409
|
-
done: false,
|
|
410
|
-
dueDate,
|
|
411
|
-
createdAt: now,
|
|
412
|
-
updatedAt: now,
|
|
413
|
-
completedAt: null,
|
|
414
|
-
})
|
|
415
|
-
await guard(persist)
|
|
416
|
-
return snapshot()
|
|
417
|
-
},
|
|
418
|
-
|
|
419
|
-
async update(input = {}) {
|
|
420
|
-
const source = asRecord(input)
|
|
421
|
-
const index = state.todos.findIndex((todo) => todo.id === requireId(source.id))
|
|
422
|
-
if (index === -1) throw new StoreError('not-found', '这条待办已经不在了')
|
|
423
|
-
const current = state.todos[index]
|
|
424
|
-
const next = { ...current }
|
|
425
|
-
if (source.title !== undefined) next.title = normalizeTitle(source.title)
|
|
426
|
-
if (source.important !== undefined) next.important = normalizeFlag(source.important, 'important')
|
|
427
|
-
if (source.urgent !== undefined) next.urgent = normalizeFlag(source.urgent, 'urgent')
|
|
428
|
-
if (source.dueDate !== undefined) next.dueDate = normalizeDueDate(source.dueDate)
|
|
429
|
-
next.updatedAt = new Date().toISOString()
|
|
430
|
-
state.todos[index] = next
|
|
431
|
-
await guard(persist)
|
|
432
|
-
return snapshot()
|
|
433
|
-
},
|
|
434
|
-
|
|
435
|
-
async toggle(input = {}) {
|
|
436
|
-
const source = asRecord(input)
|
|
437
|
-
const index = state.todos.findIndex((todo) => todo.id === requireId(source.id))
|
|
438
|
-
if (index === -1) throw new StoreError('not-found', '这条待办已经不在了')
|
|
439
|
-
const current = state.todos[index]
|
|
440
|
-
const now = new Date().toISOString()
|
|
441
|
-
const done = !current.done
|
|
442
|
-
state.todos[index] = {
|
|
443
|
-
...current,
|
|
444
|
-
done,
|
|
445
|
-
completedAt: done ? now : null,
|
|
446
|
-
updatedAt: now,
|
|
447
|
-
}
|
|
448
|
-
await guard(persist)
|
|
449
|
-
return snapshot()
|
|
450
|
-
},
|
|
451
|
-
|
|
452
|
-
/**
|
|
453
|
-
* Drag-and-drop result: move one row to another quadrant and/or another
|
|
454
|
-
* position. `beforeId` names the row it should sit above (null = last).
|
|
455
|
-
*/
|
|
456
|
-
async reorder(input = {}) {
|
|
457
|
-
const source = asRecord(input)
|
|
458
|
-
const id = requireId(source.id)
|
|
459
|
-
const index = state.todos.findIndex((todo) => todo.id === id)
|
|
460
|
-
if (index === -1) throw new StoreError('not-found', '这条待办已经不在了')
|
|
461
|
-
const current = state.todos[index]
|
|
462
|
-
const next = { ...current }
|
|
463
|
-
if (source.important !== undefined) next.important = normalizeFlag(source.important, 'important')
|
|
464
|
-
if (source.urgent !== undefined) next.urgent = normalizeFlag(source.urgent, 'urgent')
|
|
465
|
-
if (source.beforeId !== undefined && source.beforeId !== null && typeof source.beforeId !== 'string') {
|
|
466
|
-
throw new StoreError('invalid-input', 'beforeId 必须是字符串或 null')
|
|
467
|
-
}
|
|
468
|
-
const anchorId = typeof source.beforeId === 'string' && source.beforeId !== '' ? source.beforeId : null
|
|
469
|
-
// Validate the anchor before touching the array: a late throw would
|
|
470
|
-
// otherwise leave the detached row missing from memory and lose it on the
|
|
471
|
-
// next write. `beforeId === id` means "keep this position".
|
|
472
|
-
if (anchorId !== null && anchorId !== id && !state.todos.some((todo) => todo.id === anchorId)) {
|
|
473
|
-
throw new StoreError('not-found', '拖放的目标位置已经不在了')
|
|
474
|
-
}
|
|
475
|
-
state.todos.splice(index, 1)
|
|
476
|
-
let insertAt = state.todos.length
|
|
477
|
-
if (anchorId === id) insertAt = index
|
|
478
|
-
else if (anchorId !== null) insertAt = state.todos.findIndex((todo) => todo.id === anchorId)
|
|
479
|
-
next.updatedAt = new Date().toISOString()
|
|
480
|
-
state.todos.splice(insertAt, 0, next)
|
|
481
|
-
state.reordered = true
|
|
482
|
-
await guard(persist)
|
|
483
|
-
return snapshot()
|
|
484
|
-
},
|
|
485
|
-
|
|
486
|
-
async remove(input = {}) {
|
|
487
|
-
const source = asRecord(input)
|
|
488
|
-
const id = requireId(source.id)
|
|
489
|
-
const index = state.todos.findIndex((todo) => todo.id === id)
|
|
490
|
-
if (index === -1) throw new StoreError('not-found', '这条待办已经不在了')
|
|
491
|
-
state.todos.splice(index, 1)
|
|
492
|
-
await guard(persist)
|
|
493
|
-
return snapshot()
|
|
494
|
-
},
|
|
495
|
-
|
|
496
|
-
async clearCompleted(input = {}) {
|
|
497
|
-
asRecord(input)
|
|
498
|
-
const before = state.todos.length
|
|
499
|
-
state.todos = state.todos.filter((todo) => !todo.done)
|
|
500
|
-
if (state.todos.length !== before) await guard(persist)
|
|
501
|
-
return snapshot()
|
|
502
|
-
},
|
|
503
|
-
}
|
|
504
|
-
}
|
|
505
|
-
|
|
506
|
-
/** Default data file, resolved from the running profile. */
|
|
507
|
-
export function resolveDataFile(override) {
|
|
508
|
-
if (typeof override === 'string' && override.trim() !== '') return override
|
|
509
|
-
const base = process.env.DSH_PROFILE_DIR || process.cwd()
|
|
510
|
-
return join(base, 'data', 'dsh-matrix-todo', 'todos.json')
|
|
511
|
-
}
|
|
1
|
+
/** File-backed store for the four-quadrant todo plugin: one JSON document, serialized atomic writes. */
|
|
2
|
+
|
|
3
|
+
import { readFile, writeFile, rename, mkdir, copyFile } from 'node:fs/promises'
|
|
4
|
+
import { dirname, join } from 'node:path'
|
|
5
|
+
|
|
6
|
+
const VERSION = 1
|
|
7
|
+
const MAX_TODOS = 500
|
|
8
|
+
const TITLE_MAX = 200
|
|
9
|
+
const RADIUS_MIN = 0
|
|
10
|
+
const RADIUS_MAX = 24
|
|
11
|
+
const FONT_MIN = 11
|
|
12
|
+
const FONT_MAX = 17
|
|
13
|
+
const CORRUPT_UNBACKUPED = '数据文件损坏且无法备份,已停止写入以保护原文件'
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Panel layout preferences, persisted next to the todos.
|
|
17
|
+
* `frame`: cards = four rounded cards, grid = outer border with a cross (田字格),
|
|
18
|
+
* cross = a true cross with no outer border. `tint`: soft pastel cell backgrounds.
|
|
19
|
+
*/
|
|
20
|
+
export const DEFAULT_SETTINGS = Object.freeze({
|
|
21
|
+
urgentSide: 'right',
|
|
22
|
+
frame: 'cross',
|
|
23
|
+
radius: 10,
|
|
24
|
+
tint: 'plain',
|
|
25
|
+
fontSize: 14,
|
|
26
|
+
dueFormat: 'countdown',
|
|
27
|
+
titleStyle: 'wrap',
|
|
28
|
+
colRatio: 0.5,
|
|
29
|
+
rowRatio: 0.5,
|
|
30
|
+
navLabel: '',
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
const NAV_LABEL_MAX = 24
|
|
34
|
+
|
|
35
|
+
const URGENT_SIDES = ['left', 'right']
|
|
36
|
+
const FRAMES = ['cards', 'grid', 'cross']
|
|
37
|
+
const TINTS = ['plain', 'soft']
|
|
38
|
+
const DUE_FORMATS = ['date', 'countdown']
|
|
39
|
+
const TITLE_STYLES = ['wrap', 'truncate']
|
|
40
|
+
const RATIO_MIN = 0.2
|
|
41
|
+
const RATIO_MAX = 0.8
|
|
42
|
+
|
|
43
|
+
/** Valid split ratio, or the default when the value is unusable. */
|
|
44
|
+
function sanitizeRatio(value) {
|
|
45
|
+
return typeof value === 'number' && Number.isFinite(value) && value >= RATIO_MIN && value <= RATIO_MAX
|
|
46
|
+
? value
|
|
47
|
+
: 0.5
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Error with a stable code, so the HTTP layer can map it to a status. */
|
|
51
|
+
export class StoreError extends Error {
|
|
52
|
+
constructor(code, message) {
|
|
53
|
+
super(message)
|
|
54
|
+
this.name = 'StoreError'
|
|
55
|
+
this.code = code
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function emptyDoc() {
|
|
60
|
+
return { version: VERSION, todos: [], settings: { ...DEFAULT_SETTINGS }, reordered: false, seeded: false }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const DAY_RE = /^\d{4}-\d{2}-\d{2}$/
|
|
64
|
+
|
|
65
|
+
/** `YYYY-MM-DD` that names a real calendar day, or null when absent/blank. */
|
|
66
|
+
function normalizeDueDate(raw) {
|
|
67
|
+
if (raw === undefined || raw === null || raw === '') return null
|
|
68
|
+
if (typeof raw !== 'string' || !DAY_RE.test(raw)) {
|
|
69
|
+
throw new StoreError('invalid-input', '截止日期格式应为 YYYY-MM-DD')
|
|
70
|
+
}
|
|
71
|
+
const [year, month, day] = raw.split('-').map(Number)
|
|
72
|
+
const date = new Date(year, month - 1, day)
|
|
73
|
+
if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) {
|
|
74
|
+
throw new StoreError('invalid-input', '截止日期不是真实存在的日期')
|
|
75
|
+
}
|
|
76
|
+
return raw
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Lenient variant for rows read off disk: an unusable due date becomes null. */
|
|
80
|
+
function sanitizeDueDate(raw) {
|
|
81
|
+
try {
|
|
82
|
+
return normalizeDueDate(raw)
|
|
83
|
+
} catch {
|
|
84
|
+
return null
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Unknown or malformed preference fields fall back to the default, never throw. */
|
|
89
|
+
function sanitizeSettings(value) {
|
|
90
|
+
const source = value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {}
|
|
91
|
+
return {
|
|
92
|
+
urgentSide: URGENT_SIDES.includes(source.urgentSide) ? source.urgentSide : DEFAULT_SETTINGS.urgentSide,
|
|
93
|
+
frame: FRAMES.includes(source.frame) ? source.frame : DEFAULT_SETTINGS.frame,
|
|
94
|
+
radius:
|
|
95
|
+
Number.isInteger(source.radius) && source.radius >= RADIUS_MIN && source.radius <= RADIUS_MAX
|
|
96
|
+
? source.radius
|
|
97
|
+
: DEFAULT_SETTINGS.radius,
|
|
98
|
+
tint: TINTS.includes(source.tint) ? source.tint : DEFAULT_SETTINGS.tint,
|
|
99
|
+
fontSize:
|
|
100
|
+
Number.isInteger(source.fontSize) && source.fontSize >= FONT_MIN && source.fontSize <= FONT_MAX
|
|
101
|
+
? source.fontSize
|
|
102
|
+
: DEFAULT_SETTINGS.fontSize,
|
|
103
|
+
dueFormat: DUE_FORMATS.includes(source.dueFormat) ? source.dueFormat : DEFAULT_SETTINGS.dueFormat,
|
|
104
|
+
titleStyle: TITLE_STYLES.includes(source.titleStyle) ? source.titleStyle : DEFAULT_SETTINGS.titleStyle,
|
|
105
|
+
colRatio: sanitizeRatio(source.colRatio),
|
|
106
|
+
rowRatio: sanitizeRatio(source.rowRatio),
|
|
107
|
+
navLabel:
|
|
108
|
+
typeof source.navLabel === 'string' ? source.navLabel.trim().slice(0, NAV_LABEL_MAX) : DEFAULT_SETTINGS.navLabel,
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Contract id format: e_<base36 timestamp>_<4 random base36 chars>. */
|
|
113
|
+
function newId() {
|
|
114
|
+
const rand = Math.random().toString(36).slice(2, 6).padEnd(4, '0')
|
|
115
|
+
return `e_${Date.now().toString(36)}_${rand}`
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function asRecord(value) {
|
|
119
|
+
if (value === undefined) return {}
|
|
120
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
121
|
+
throw new StoreError('invalid-input', '参数必须是对象')
|
|
122
|
+
}
|
|
123
|
+
return value
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Title: trim the textual form, then require 1..200 characters. */
|
|
127
|
+
function normalizeTitle(raw) {
|
|
128
|
+
const title = raw === undefined || raw === null ? '' : String(raw).trim()
|
|
129
|
+
if (title.length === 0) throw new StoreError('invalid-input', '标题不能为空')
|
|
130
|
+
if (title.length > TITLE_MAX) throw new StoreError('invalid-input', `标题最长 ${TITLE_MAX} 字`)
|
|
131
|
+
return title
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Quadrant flags default to false when absent; anything non-boolean is rejected. */
|
|
135
|
+
function normalizeFlag(raw, field) {
|
|
136
|
+
if (raw === undefined) return false
|
|
137
|
+
if (typeof raw !== 'boolean') throw new StoreError('invalid-input', `${field} 必须是布尔值`)
|
|
138
|
+
return raw
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function requireId(raw) {
|
|
142
|
+
if (typeof raw !== 'string' || raw === '') throw new StoreError('invalid-input', 'id 必填')
|
|
143
|
+
return raw
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Keep manually edited files tolerable: drop rows that cannot be rendered, keep every usable field. */
|
|
147
|
+
function sanitizeTodos(value) {
|
|
148
|
+
if (!Array.isArray(value)) return []
|
|
149
|
+
const out = []
|
|
150
|
+
for (const raw of value) {
|
|
151
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) continue
|
|
152
|
+
if (typeof raw.id !== 'string' || raw.id === '') continue
|
|
153
|
+
const title = typeof raw.title === 'string' ? raw.title.trim() : ''
|
|
154
|
+
if (title === '' || title.length > TITLE_MAX) continue
|
|
155
|
+
const done = raw.done === true
|
|
156
|
+
const createdAt = typeof raw.createdAt === 'string' ? raw.createdAt : new Date().toISOString()
|
|
157
|
+
out.push({
|
|
158
|
+
id: raw.id,
|
|
159
|
+
title,
|
|
160
|
+
important: raw.important === true,
|
|
161
|
+
urgent: raw.urgent === true,
|
|
162
|
+
done,
|
|
163
|
+
dueDate: sanitizeDueDate(raw.dueDate),
|
|
164
|
+
createdAt,
|
|
165
|
+
updatedAt: typeof raw.updatedAt === 'string' ? raw.updatedAt : createdAt,
|
|
166
|
+
completedAt: done && typeof raw.completedAt === 'string' ? raw.completedAt : null,
|
|
167
|
+
})
|
|
168
|
+
}
|
|
169
|
+
return out
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Read the document; unreadable shape or unparseable JSON is reported as corrupt, not fatal. */
|
|
173
|
+
async function readDoc(file) {
|
|
174
|
+
let raw
|
|
175
|
+
try {
|
|
176
|
+
raw = await readFile(file, 'utf8')
|
|
177
|
+
} catch (err) {
|
|
178
|
+
if (err.code === 'ENOENT') return { doc: emptyDoc(), corrupt: false }
|
|
179
|
+
throw new StoreError('io-error', `无法读取待办数据:${err.message}`)
|
|
180
|
+
}
|
|
181
|
+
try {
|
|
182
|
+
const doc = JSON.parse(raw)
|
|
183
|
+
if (!doc || typeof doc !== 'object' || Array.isArray(doc) || !Array.isArray(doc.todos)) {
|
|
184
|
+
throw new Error('shape')
|
|
185
|
+
}
|
|
186
|
+
return { doc, corrupt: false }
|
|
187
|
+
} catch {
|
|
188
|
+
return { doc: emptyDoc(), corrupt: true }
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Backup name next to the data file: todos.json -> todos.corrupt-<timestamp>.json */
|
|
193
|
+
function corruptBackupPath(file) {
|
|
194
|
+
return `${file.replace(/\.json$/i, '')}.corrupt-${Date.now()}.json`
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export function createStore({ file } = {}) {
|
|
198
|
+
if (typeof file !== 'string' || file === '') throw new StoreError('invalid-input', '数据文件路径必填')
|
|
199
|
+
const dataFile = file
|
|
200
|
+
const state = { todos: [], settings: { ...DEFAULT_SETTINGS }, reordered: false, seeded: false, corrupt: false, sealed: false }
|
|
201
|
+
let queue = Promise.resolve()
|
|
202
|
+
let closed = false
|
|
203
|
+
|
|
204
|
+
/** Latest in-memory todos, copied so callers cannot mutate the source of truth. */
|
|
205
|
+
function snapshot() {
|
|
206
|
+
return state.todos.map((todo) => ({ ...todo }))
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
async function persist() {
|
|
210
|
+
if (state.sealed) throw new StoreError('io-error', CORRUPT_UNBACKUPED)
|
|
211
|
+
const snapshotText = JSON.stringify(
|
|
212
|
+
{ version: VERSION, todos: state.todos, settings: state.settings, reordered: state.reordered, seeded: state.seeded },
|
|
213
|
+
null,
|
|
214
|
+
2,
|
|
215
|
+
)
|
|
216
|
+
const write = queue.then(async () => {
|
|
217
|
+
await mkdir(dirname(dataFile), { recursive: true })
|
|
218
|
+
const tmp = `${dataFile}.tmp`
|
|
219
|
+
await writeFile(tmp, snapshotText, 'utf8')
|
|
220
|
+
await rename(tmp, dataFile)
|
|
221
|
+
})
|
|
222
|
+
queue = write.catch(() => {})
|
|
223
|
+
try {
|
|
224
|
+
await write
|
|
225
|
+
} catch (err) {
|
|
226
|
+
if (err instanceof StoreError) throw err
|
|
227
|
+
throw new StoreError('io-error', `待办数据写入失败:${err.message}`)
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
async function guard(fn) {
|
|
232
|
+
try {
|
|
233
|
+
return await fn()
|
|
234
|
+
} catch (err) {
|
|
235
|
+
if (err instanceof StoreError) throw err
|
|
236
|
+
throw new StoreError('io-error', `待办数据写入失败:${err.message}`)
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
return {
|
|
241
|
+
async load() {
|
|
242
|
+
const { doc, corrupt } = await readDoc(dataFile)
|
|
243
|
+
state.todos = sanitizeTodos(doc.todos)
|
|
244
|
+
state.settings = sanitizeSettings(doc.settings)
|
|
245
|
+
state.reordered = doc.reordered === true
|
|
246
|
+
// A store that already holds rows, or one that was seeded before, never
|
|
247
|
+
// gets onboarding rows again — deleting the guide must stick.
|
|
248
|
+
state.seeded = corrupt || doc.seeded === true || state.todos.length > 0
|
|
249
|
+
// Until someone drags a row, the list order is derived: newest first. Once
|
|
250
|
+
// a drag is saved, the stored array order is the user's own order.
|
|
251
|
+
if (!state.reordered) state.todos.sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)))
|
|
252
|
+
state.corrupt = corrupt
|
|
253
|
+
state.sealed = false
|
|
254
|
+
if (!corrupt) return { corrupt: false }
|
|
255
|
+
const backup = corruptBackupPath(dataFile)
|
|
256
|
+
try {
|
|
257
|
+
await copyFile(dataFile, backup)
|
|
258
|
+
} catch {
|
|
259
|
+
state.sealed = true
|
|
260
|
+
throw new StoreError('io-error', CORRUPT_UNBACKUPED)
|
|
261
|
+
}
|
|
262
|
+
await guard(persist)
|
|
263
|
+
return { corrupt: true, backup }
|
|
264
|
+
},
|
|
265
|
+
|
|
266
|
+
close() {
|
|
267
|
+
if (closed) return queue
|
|
268
|
+
closed = true
|
|
269
|
+
return queue
|
|
270
|
+
},
|
|
271
|
+
|
|
272
|
+
list() {
|
|
273
|
+
return snapshot()
|
|
274
|
+
},
|
|
275
|
+
|
|
276
|
+
/** True once onboarding rows were written, or when the store was never empty. */
|
|
277
|
+
seeded() {
|
|
278
|
+
return state.seeded
|
|
279
|
+
},
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* One-time onboarding rows for a brand-new store. The client sends localized
|
|
283
|
+
* titles; the flag makes the call idempotent and stops the guide from coming
|
|
284
|
+
* back after the user deletes it.
|
|
285
|
+
*/
|
|
286
|
+
async seed(input = {}) {
|
|
287
|
+
if (state.seeded) return { added: 0 }
|
|
288
|
+
const source = asRecord(input)
|
|
289
|
+
const rows = Array.isArray(source.items) ? source.items.slice(0, 32) : []
|
|
290
|
+
const now = Date.now()
|
|
291
|
+
const added = []
|
|
292
|
+
rows.forEach((raw, index) => {
|
|
293
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return
|
|
294
|
+
const title = typeof raw.title === 'string' ? raw.title.trim() : ''
|
|
295
|
+
if (title === '' || title.length > TITLE_MAX) return
|
|
296
|
+
const createdAt = new Date(now - index * 1000).toISOString()
|
|
297
|
+
added.push({
|
|
298
|
+
id: newId(),
|
|
299
|
+
title,
|
|
300
|
+
important: raw.important === true,
|
|
301
|
+
urgent: raw.urgent === true,
|
|
302
|
+
done: false,
|
|
303
|
+
dueDate: sanitizeDueDate(raw.dueDate),
|
|
304
|
+
createdAt,
|
|
305
|
+
updatedAt: createdAt,
|
|
306
|
+
completedAt: null,
|
|
307
|
+
})
|
|
308
|
+
})
|
|
309
|
+
state.seeded = true
|
|
310
|
+
if (added.length > 0) state.todos = [...added, ...state.todos]
|
|
311
|
+
await guard(persist)
|
|
312
|
+
return { added: added.length }
|
|
313
|
+
},
|
|
314
|
+
|
|
315
|
+
/** Current layout preferences (a copy; callers cannot mutate the source of truth). */
|
|
316
|
+
settings() {
|
|
317
|
+
return { ...state.settings }
|
|
318
|
+
},
|
|
319
|
+
|
|
320
|
+
/** Merge validated preference fields and persist them with the todos. */
|
|
321
|
+
async saveSettings(input = {}) {
|
|
322
|
+
const source = asRecord(input)
|
|
323
|
+
const next = { ...state.settings }
|
|
324
|
+
if (source.urgentSide !== undefined) {
|
|
325
|
+
if (!URGENT_SIDES.includes(source.urgentSide)) {
|
|
326
|
+
throw new StoreError('invalid-input', 'urgentSide 只能是 left 或 right')
|
|
327
|
+
}
|
|
328
|
+
next.urgentSide = source.urgentSide
|
|
329
|
+
}
|
|
330
|
+
if (source.frame !== undefined) {
|
|
331
|
+
if (!FRAMES.includes(source.frame)) {
|
|
332
|
+
throw new StoreError('invalid-input', 'frame 只能是 cards、grid 或 cross')
|
|
333
|
+
}
|
|
334
|
+
next.frame = source.frame
|
|
335
|
+
}
|
|
336
|
+
if (source.tint !== undefined) {
|
|
337
|
+
if (!TINTS.includes(source.tint)) {
|
|
338
|
+
throw new StoreError('invalid-input', 'tint 只能是 plain 或 soft')
|
|
339
|
+
}
|
|
340
|
+
next.tint = source.tint
|
|
341
|
+
}
|
|
342
|
+
if (source.dueFormat !== undefined) {
|
|
343
|
+
if (!DUE_FORMATS.includes(source.dueFormat)) {
|
|
344
|
+
throw new StoreError('invalid-input', 'dueFormat 只能是 date 或 countdown')
|
|
345
|
+
}
|
|
346
|
+
next.dueFormat = source.dueFormat
|
|
347
|
+
}
|
|
348
|
+
if (source.titleStyle !== undefined) {
|
|
349
|
+
if (!TITLE_STYLES.includes(source.titleStyle)) {
|
|
350
|
+
throw new StoreError('invalid-input', 'titleStyle 只能是 wrap 或 truncate')
|
|
351
|
+
}
|
|
352
|
+
next.titleStyle = source.titleStyle
|
|
353
|
+
}
|
|
354
|
+
for (const field of ['colRatio', 'rowRatio']) {
|
|
355
|
+
if (source[field] === undefined) continue
|
|
356
|
+
if (
|
|
357
|
+
typeof source[field] !== 'number' ||
|
|
358
|
+
!Number.isFinite(source[field]) ||
|
|
359
|
+
source[field] < RATIO_MIN ||
|
|
360
|
+
source[field] > RATIO_MAX
|
|
361
|
+
) {
|
|
362
|
+
throw new StoreError('invalid-input', `${field} 必须是 ${RATIO_MIN}–${RATIO_MAX} 之间的数字`)
|
|
363
|
+
}
|
|
364
|
+
next[field] = source[field]
|
|
365
|
+
}
|
|
366
|
+
if (source.navLabel !== undefined) {
|
|
367
|
+
if (typeof source.navLabel !== 'string') {
|
|
368
|
+
throw new StoreError('invalid-input', 'navLabel 必须是字符串')
|
|
369
|
+
}
|
|
370
|
+
const label = source.navLabel.trim()
|
|
371
|
+
if (label.length > NAV_LABEL_MAX) {
|
|
372
|
+
throw new StoreError('invalid-input', `侧边栏名称最长 ${NAV_LABEL_MAX} 字`)
|
|
373
|
+
}
|
|
374
|
+
next.navLabel = label
|
|
375
|
+
}
|
|
376
|
+
if (source.fontSize !== undefined) {
|
|
377
|
+
if (!Number.isInteger(source.fontSize) || source.fontSize < FONT_MIN || source.fontSize > FONT_MAX) {
|
|
378
|
+
throw new StoreError('invalid-input', `fontSize 必须是 ${FONT_MIN}-${FONT_MAX} 的整数`)
|
|
379
|
+
}
|
|
380
|
+
next.fontSize = source.fontSize
|
|
381
|
+
}
|
|
382
|
+
if (source.radius !== undefined) {
|
|
383
|
+
if (!Number.isInteger(source.radius) || source.radius < RADIUS_MIN || source.radius > RADIUS_MAX) {
|
|
384
|
+
throw new StoreError('invalid-input', `radius 必须是 ${RADIUS_MIN}-${RADIUS_MAX} 的整数`)
|
|
385
|
+
}
|
|
386
|
+
next.radius = source.radius
|
|
387
|
+
}
|
|
388
|
+
state.settings = next
|
|
389
|
+
await guard(persist)
|
|
390
|
+
return { ...next }
|
|
391
|
+
},
|
|
392
|
+
|
|
393
|
+
async create(input = {}) {
|
|
394
|
+
const source = asRecord(input)
|
|
395
|
+
if (state.todos.length >= MAX_TODOS) {
|
|
396
|
+
throw new StoreError('invalid-input', `待办最多 ${MAX_TODOS} 条`)
|
|
397
|
+
}
|
|
398
|
+
const title = normalizeTitle(source.title)
|
|
399
|
+
const important = normalizeFlag(source.important, 'important')
|
|
400
|
+
const urgent = normalizeFlag(source.urgent, 'urgent')
|
|
401
|
+
const dueDate = normalizeDueDate(source.dueDate)
|
|
402
|
+
const now = new Date().toISOString()
|
|
403
|
+
// Newest first inside its quadrant: the array order is the display order.
|
|
404
|
+
state.todos.unshift({
|
|
405
|
+
id: newId(),
|
|
406
|
+
title,
|
|
407
|
+
important,
|
|
408
|
+
urgent,
|
|
409
|
+
done: false,
|
|
410
|
+
dueDate,
|
|
411
|
+
createdAt: now,
|
|
412
|
+
updatedAt: now,
|
|
413
|
+
completedAt: null,
|
|
414
|
+
})
|
|
415
|
+
await guard(persist)
|
|
416
|
+
return snapshot()
|
|
417
|
+
},
|
|
418
|
+
|
|
419
|
+
async update(input = {}) {
|
|
420
|
+
const source = asRecord(input)
|
|
421
|
+
const index = state.todos.findIndex((todo) => todo.id === requireId(source.id))
|
|
422
|
+
if (index === -1) throw new StoreError('not-found', '这条待办已经不在了')
|
|
423
|
+
const current = state.todos[index]
|
|
424
|
+
const next = { ...current }
|
|
425
|
+
if (source.title !== undefined) next.title = normalizeTitle(source.title)
|
|
426
|
+
if (source.important !== undefined) next.important = normalizeFlag(source.important, 'important')
|
|
427
|
+
if (source.urgent !== undefined) next.urgent = normalizeFlag(source.urgent, 'urgent')
|
|
428
|
+
if (source.dueDate !== undefined) next.dueDate = normalizeDueDate(source.dueDate)
|
|
429
|
+
next.updatedAt = new Date().toISOString()
|
|
430
|
+
state.todos[index] = next
|
|
431
|
+
await guard(persist)
|
|
432
|
+
return snapshot()
|
|
433
|
+
},
|
|
434
|
+
|
|
435
|
+
async toggle(input = {}) {
|
|
436
|
+
const source = asRecord(input)
|
|
437
|
+
const index = state.todos.findIndex((todo) => todo.id === requireId(source.id))
|
|
438
|
+
if (index === -1) throw new StoreError('not-found', '这条待办已经不在了')
|
|
439
|
+
const current = state.todos[index]
|
|
440
|
+
const now = new Date().toISOString()
|
|
441
|
+
const done = !current.done
|
|
442
|
+
state.todos[index] = {
|
|
443
|
+
...current,
|
|
444
|
+
done,
|
|
445
|
+
completedAt: done ? now : null,
|
|
446
|
+
updatedAt: now,
|
|
447
|
+
}
|
|
448
|
+
await guard(persist)
|
|
449
|
+
return snapshot()
|
|
450
|
+
},
|
|
451
|
+
|
|
452
|
+
/**
|
|
453
|
+
* Drag-and-drop result: move one row to another quadrant and/or another
|
|
454
|
+
* position. `beforeId` names the row it should sit above (null = last).
|
|
455
|
+
*/
|
|
456
|
+
async reorder(input = {}) {
|
|
457
|
+
const source = asRecord(input)
|
|
458
|
+
const id = requireId(source.id)
|
|
459
|
+
const index = state.todos.findIndex((todo) => todo.id === id)
|
|
460
|
+
if (index === -1) throw new StoreError('not-found', '这条待办已经不在了')
|
|
461
|
+
const current = state.todos[index]
|
|
462
|
+
const next = { ...current }
|
|
463
|
+
if (source.important !== undefined) next.important = normalizeFlag(source.important, 'important')
|
|
464
|
+
if (source.urgent !== undefined) next.urgent = normalizeFlag(source.urgent, 'urgent')
|
|
465
|
+
if (source.beforeId !== undefined && source.beforeId !== null && typeof source.beforeId !== 'string') {
|
|
466
|
+
throw new StoreError('invalid-input', 'beforeId 必须是字符串或 null')
|
|
467
|
+
}
|
|
468
|
+
const anchorId = typeof source.beforeId === 'string' && source.beforeId !== '' ? source.beforeId : null
|
|
469
|
+
// Validate the anchor before touching the array: a late throw would
|
|
470
|
+
// otherwise leave the detached row missing from memory and lose it on the
|
|
471
|
+
// next write. `beforeId === id` means "keep this position".
|
|
472
|
+
if (anchorId !== null && anchorId !== id && !state.todos.some((todo) => todo.id === anchorId)) {
|
|
473
|
+
throw new StoreError('not-found', '拖放的目标位置已经不在了')
|
|
474
|
+
}
|
|
475
|
+
state.todos.splice(index, 1)
|
|
476
|
+
let insertAt = state.todos.length
|
|
477
|
+
if (anchorId === id) insertAt = index
|
|
478
|
+
else if (anchorId !== null) insertAt = state.todos.findIndex((todo) => todo.id === anchorId)
|
|
479
|
+
next.updatedAt = new Date().toISOString()
|
|
480
|
+
state.todos.splice(insertAt, 0, next)
|
|
481
|
+
state.reordered = true
|
|
482
|
+
await guard(persist)
|
|
483
|
+
return snapshot()
|
|
484
|
+
},
|
|
485
|
+
|
|
486
|
+
async remove(input = {}) {
|
|
487
|
+
const source = asRecord(input)
|
|
488
|
+
const id = requireId(source.id)
|
|
489
|
+
const index = state.todos.findIndex((todo) => todo.id === id)
|
|
490
|
+
if (index === -1) throw new StoreError('not-found', '这条待办已经不在了')
|
|
491
|
+
state.todos.splice(index, 1)
|
|
492
|
+
await guard(persist)
|
|
493
|
+
return snapshot()
|
|
494
|
+
},
|
|
495
|
+
|
|
496
|
+
async clearCompleted(input = {}) {
|
|
497
|
+
asRecord(input)
|
|
498
|
+
const before = state.todos.length
|
|
499
|
+
state.todos = state.todos.filter((todo) => !todo.done)
|
|
500
|
+
if (state.todos.length !== before) await guard(persist)
|
|
501
|
+
return snapshot()
|
|
502
|
+
},
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/** Default data file, resolved from the running profile. */
|
|
507
|
+
export function resolveDataFile(override) {
|
|
508
|
+
if (typeof override === 'string' && override.trim() !== '') return override
|
|
509
|
+
const base = process.env.DSH_PROFILE_DIR || process.cwd()
|
|
510
|
+
return join(base, 'data', 'dsh-matrix-todo', 'todos.json')
|
|
511
|
+
}
|