Repository navigation
Expand file tree
/
Copy pathtodo-core.js
More file actions
453 lines (409 loc) · 14 KB
/
Copy pathtodo-core.js
File metadata and controls
453 lines (409 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
(function () {
const DEFAULT_SNOOZE_MINUTES = 10;
const SNOOZE_OPTIONS = [5, 10, 15, 30];
const NAG_OPTIONS = [0, 5, 10, 15, 30];
const DEFAULT_APP_TITLE = 'Sisyphus';
const DEFAULT_QUOTE_TEXT = 'One must imagine Sisyphus happy.';
const DEFAULT_QUOTE_AUTHOR = 'Albert Camus';
function parseReminderInput(str) {
const raw = (str || '').trim();
let m = raw.match(/^(\d{2})(\d{2})$/);
if (!m) {
m = raw.match(/^(\d{1,2})\s*[::]\s*(\d{1,2})$/);
}
if (!m) return null;
const h = parseInt(m[1], 10);
const min = parseInt(m[2], 10);
if (h < 0 || h > 23 || min < 0 || min > 59) return null;
return `${String(h).padStart(2, '0')}:${String(min).padStart(2, '0')}`;
}
function normalizeDate(date) {
const copy = new Date(date);
copy.setHours(0, 0, 0, 0);
return copy;
}
function dateToInputValue(date) {
const yyyy = date.getFullYear();
const mm = String(date.getMonth() + 1).padStart(2, '0');
const dd = String(date.getDate()).padStart(2, '0');
return `${yyyy}-${mm}-${dd}`;
}
function formatDateDisplay(dateString) {
if (!dateString) return '';
const date = new Date(dateString);
if (Number.isNaN(date.getTime())) return '';
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${month}/${day}`;
}
function buildDateFromMonthDay(month, day, now = new Date()) {
const y = now.getFullYear();
const date = new Date(y, month - 1, day);
if (date.getFullYear() !== y || date.getMonth() !== month - 1 || date.getDate() !== day) {
return null;
}
return date;
}
function nextWeekdayDate(dayIndex, now = new Date()) {
const date = normalizeDate(now);
const delta = (dayIndex - date.getDay() + 7) % 7 || 7;
date.setDate(date.getDate() + delta);
return dateToInputValue(date);
}
function consumeQuickToken(token, result, now, textTokens) {
if (!token) return;
const clockToken = token.match(/^(\d{2})(\d{2})(\d{2})(\d{2})$/);
if (clockToken && (!result.dueDate || !result.reminderTime)) {
const month = parseInt(clockToken[1], 10);
const day = parseInt(clockToken[2], 10);
const hour = parseInt(clockToken[3], 10);
const minute = parseInt(clockToken[4], 10);
const date = buildDateFromMonthDay(month, day, now);
const time = parseReminderInput(`${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`);
if (date && time) {
if (!result.dueDate) result.dueDate = dateToInputValue(date);
if (!result.reminderTime) result.reminderTime = time;
result.consumedAny = true;
return;
}
}
const datePrefixes = [
['星期天', 0],
['星期日', 0],
['星期一', 1],
['星期二', 2],
['星期三', 3],
['星期四', 4],
['星期五', 5],
['星期六', 6],
['tomorrow', 'tomorrow'],
['today', 'today'],
['后天', 'dayAfterTomorrow'],
['明天', 'tomorrow'],
['今天', 'today'],
['周天', 0],
['周日', 0],
['周一', 1],
['周二', 2],
['周三', 3],
['周四', 4],
['周五', 5],
['周六', 6],
// Japanese
['明後日', 'dayAfterTomorrow'],
['明日', 'tomorrow'],
['今日', 'today'],
['日曜日', 0],
['月曜日', 1],
['火曜日', 2],
['水曜日', 3],
['木曜日', 4],
['金曜日', 5],
['土曜日', 6],
// Korean
['모레', 'dayAfterTomorrow'],
['내일', 'tomorrow'],
['오늘', 'today'],
['일요일', 0],
['월요일', 1],
['화요일', 2],
['수요일', 3],
['목요일', 4],
['금요일', 5],
['토요일', 6]
];
if (!result.dueDate) {
const lowered = token.toLowerCase();
const datePrefix = datePrefixes.find(([label]) => lowered.startsWith(label.toLowerCase()));
if (datePrefix) {
const [label, value] = datePrefix;
if (value === 'today') {
result.dueDate = dateToInputValue(normalizeDate(now));
} else if (value === 'tomorrow') {
const date = normalizeDate(now);
date.setDate(date.getDate() + 1);
result.dueDate = dateToInputValue(date);
} else if (value === 'dayAfterTomorrow') {
const date = normalizeDate(now);
date.setDate(date.getDate() + 2);
result.dueDate = dateToInputValue(date);
} else {
result.dueDate = nextWeekdayDate(value, now);
}
result.consumedAny = true;
consumeQuickToken(token.slice(label.length), result, now, textTokens);
return;
}
}
if (result.repeat === 'none') {
const repeatPrefixes = [
['monthly', 'monthly'],
['weekly', 'weekly'],
['daily', 'daily'],
['每月', 'monthly'],
['每周', 'weekly'],
['每天', 'daily'],
['毎月', 'monthly'],
['毎週', 'weekly'],
['毎日', 'daily'],
['매월', 'monthly'],
['매주', 'weekly'],
['매일', 'daily']
];
const lowered = token.toLowerCase();
const repeatPrefix = repeatPrefixes.find(([label]) => lowered.startsWith(label.toLowerCase()));
if (repeatPrefix) {
const [label, value] = repeatPrefix;
result.repeat = value;
result.consumedAny = true;
consumeQuickToken(token.slice(label.length), result, now, textTokens);
return;
}
}
if (!result.reminderTime) {
const exactTime = parseReminderInput(token);
if (exactTime) {
result.reminderTime = exactTime;
result.consumedAny = true;
return;
}
const timePrefix = token.match(/^(\d{4})(.+)$/);
if (timePrefix) {
const parsedTime = parseReminderInput(timePrefix[1]);
if (parsedTime) {
result.reminderTime = parsedTime;
result.consumedAny = true;
consumeQuickToken(timePrefix[2], result, now, textTokens);
return;
}
}
}
textTokens.push(token);
}
function parseQuickAdd(input, now = new Date()) {
const tokens = (input || '').trim().split(/\s+/).filter(Boolean);
const result = {
text: (input || '').trim(),
dueDate: null,
repeat: 'none',
reminderTime: null,
consumedAny: false
};
const textTokens = [];
tokens.forEach((token) => {
consumeQuickToken(token, result, now, textTokens);
});
if (result.consumedAny && textTokens.length > 0) {
result.text = textTokens.join(' ');
}
delete result.consumedAny;
return result;
}
function isTodoOverdue(todo, now = new Date()) {
// Repeat todos roll their dueDate forward on each completed cycle, so a not-yet-
// completed cycle still sitting on a past dueDate is just "today's turn", not
// overdue. A daily/weekly/monthly task therefore never shows the overdue hint.
if (!todo || todo.completed || isRepeatTodo(todo) || !todo.dueDate) return false;
const due = normalizeDate(new Date(todo.dueDate));
return due.getTime() < normalizeDate(now).getTime();
}
function sortTodosForDisplay(todos, now = new Date()) {
return [...todos].sort((a, b) => {
if (!!a.pinned !== !!b.pinned) return a.pinned ? -1 : 1;
const aOverdue = isTodoOverdue(a, now);
const bOverdue = isTodoOverdue(b, now);
if (aOverdue !== bOverdue) return aOverdue ? -1 : 1;
const aCreated = Date.parse(a.createdAt || '') || 0;
const bCreated = Date.parse(b.createdAt || '') || 0;
if (aCreated !== bCreated) return bCreated - aCreated;
return 0;
});
}
function isRepeatTodo(todo) {
return !!(todo && todo.repeat && todo.repeat !== 'none');
}
function shouldAutoDeleteCompletedTodo(todo) {
return !!(todo && todo.completed && !isRepeatTodo(todo));
}
function isExpiredCompletedTodo(todo, now, fadeDelay) {
const completedAt = Number(todo && todo.completedAt);
return !!(
todo &&
todo.completed &&
completedAt &&
Number.isFinite(fadeDelay) &&
now - completedAt >= fadeDelay
);
}
function startOfDayTs(ts) {
const d = new Date(ts);
return new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
}
// Add one month, clamping the day to the target month's length. Plain
// setMonth(+1) overflows short months (Jan 31 -> Mar 3, skipping February)
// and permanently loses the anchor day after one bad month.
function addOneMonthClamped(d) {
const day = d.getDate();
const target = new Date(d.getFullYear(), d.getMonth() + 1, 1);
const last = new Date(target.getFullYear(), target.getMonth() + 1, 0).getDate();
d.setFullYear(target.getFullYear(), target.getMonth(), Math.min(day, last));
}
// Advance a YYYY-MM-DD string by `times` repeat periods. 'none'/unknown is a no-op.
function advanceRepeatDate(dateString, repeat, times = 1) {
const base = new Date(dateString);
if (Number.isNaN(base.getTime())) return dateString;
const d = new Date(base.getFullYear(), base.getMonth(), base.getDate());
const steps = Math.max(0, Number(times) || 0);
for (let i = 0; i < steps; i++) {
if (repeat === 'daily') d.setDate(d.getDate() + 1);
else if (repeat === 'weekly') d.setDate(d.getDate() + 7);
else if (repeat === 'monthly') addOneMonthClamped(d);
else return dateString;
}
return dateToInputValue(d);
}
// Timestamp at which a completed repeat todo flips back to active: the start of
// the day one period after it was completed. null for non-repeat / missing data.
function nextRepeatResetTime(completedAt, repeat) {
const ts = Number(completedAt);
if (!Number.isFinite(ts) || !['daily', 'weekly', 'monthly'].includes(repeat)) return null;
const d = new Date(startOfDayTs(ts));
if (repeat === 'daily') d.setDate(d.getDate() + 1);
else if (repeat === 'weekly') d.setDate(d.getDate() + 7);
else if (repeat === 'monthly') addOneMonthClamped(d);
return d.getTime();
}
// Bump a (possibly stale) dueDate forward by whole periods until it is today or later.
function advanceDueDateToFuture(dateString, repeat, nowTs) {
const todayStart = startOfDayTs(nowTs);
let out = dateString;
for (let guard = 0; guard < 1000; guard++) {
const cur = new Date(out);
if (Number.isNaN(cur.getTime())) return dateString;
if (startOfDayTs(cur.getTime()) >= todayStart) break;
const next = advanceRepeatDate(out, repeat, 1);
if (next === out) break; // 'none'/unknown: avoid an infinite loop
out = next;
}
return out;
}
// The missing "明天重置": any completed repeat todo whose next period has arrived
// is flipped back to active (completed=false, timers cleared) and its dueDate is
// pushed to the upcoming period. Normal (non-repeat) completed todos are untouched.
function rolloverRepeatTodos(todos, now = Date.now()) {
const nowTs = now instanceof Date ? now.getTime() : (Number(now) || Date.now());
const list = Array.isArray(todos) ? todos : [];
let changed = false;
const next = list.map((todo) => {
if (!todo || !todo.completed || !isRepeatTodo(todo)) return todo;
const resetAt = nextRepeatResetTime(todo.completedAt, todo.repeat);
if (resetAt == null || nowTs < resetAt) return todo;
changed = true;
const updated = { ...todo, completed: false };
delete updated.completedAt;
delete updated.snoozedUntil;
if (updated.dueDate) {
updated.dueDate = advanceDueDateToFuture(updated.dueDate, updated.repeat, nowTs);
}
return updated;
});
return { todos: changed ? next : list, changed };
}
function filterTodosForView(todos, viewMode = 'all', options = {}) {
const list = Array.isArray(todos) ? todos : [];
if (viewMode === 'repeat') return list.filter(isRepeatTodo);
const fadeDelay = Number(options.fadeDelay);
if (!Number.isFinite(fadeDelay)) return [...list];
const now = options.now instanceof Date
? options.now.getTime()
: Number(options.now || Date.now());
return list.filter(todo => !isExpiredCompletedTodo(todo, now, fadeDelay));
}
function mergeMissingTodos(todos, candidates) {
const list = Array.isArray(todos) ? todos : [];
const existingTexts = new Set(
list
.map(todo => String((todo && todo.text) || '').trim())
.filter(Boolean)
);
const missing = (Array.isArray(candidates) ? candidates : [])
.filter(todo => {
const text = String((todo && todo.text) || '').trim();
return text && !existingTexts.has(text);
});
if (missing.length === 0) {
return { todos: [...list], changed: false };
}
return { todos: [...missing, ...list], changed: true };
}
function clampSnoozeMinutes(value) {
const n = parseInt(value, 10);
return SNOOZE_OPTIONS.includes(n) ? n : DEFAULT_SNOOZE_MINUTES;
}
function clampNagMinutes(value) {
const n = parseInt(value, 10);
return NAG_OPTIONS.includes(n) ? n : 0;
}
function normalizeQuoteSettings(settings) {
const source = settings || {};
const text = String(source.text || '').trim();
const author = String(source.author || '').trim();
return {
text: text || DEFAULT_QUOTE_TEXT,
author: author || DEFAULT_QUOTE_AUTHOR
};
}
function normalizeAppTitle(value) {
return String(value || '')
.replace(/\s+/g, ' ')
.trim() || DEFAULT_APP_TITLE;
}
function normalizeTodoViewMode(value) {
return value === 'repeat' ? 'repeat' : 'all';
}
function escapeHtmlText(text) {
return String(text || '')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function renderTextWithSystemNumbers(text) {
return escapeHtmlText(text).replace(/\d+/g, '<span class="num">$&</span>');
}
function nextReminderHistory(history, time, limit = 3) {
const list = Array.isArray(history) ? history : [];
const normalizedLimit = Math.max(0, Number(limit) || 0);
if (!time) return list.slice(0, normalizedLimit);
return [time, ...list.filter((item) => item !== time)].slice(0, normalizedLimit);
}
globalThis.TodoCore = {
DEFAULT_APP_TITLE,
DEFAULT_QUOTE_AUTHOR,
DEFAULT_QUOTE_TEXT,
DEFAULT_SNOOZE_MINUTES,
advanceRepeatDate,
clampNagMinutes,
clampSnoozeMinutes,
dateToInputValue,
filterTodosForView,
formatDateDisplay,
isTodoOverdue,
mergeMissingTodos,
nextRepeatResetTime,
rolloverRepeatTodos,
normalizeAppTitle,
normalizeQuoteSettings,
normalizeTodoViewMode,
nextReminderHistory,
parseQuickAdd,
parseReminderInput,
renderTextWithSystemNumbers,
shouldAutoDeleteCompletedTodo,
sortTodosForDisplay
};
if (typeof module !== 'undefined') {
module.exports = globalThis.TodoCore;
}
})();