Repository navigation
Expand file tree
/
Copy pathtodos.ts
More file actions
82 lines (72 loc) · 2.07 KB
/
Copy pathtodos.ts
File metadata and controls
82 lines (72 loc) · 2.07 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
import { readCache, writeCache, type EvenStorage } from "./live-cache";
import {
DEFAULT_TODOS as LIVE_DEFAULT_TODOS,
type TodoItem,
} from "./live-state";
const TODO_LIMIT = 6;
const TODO_TITLE_MAX_CODE_POINTS = 40;
const TODO_ID_MAX_CODE_POINTS = 64;
const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f]/;
export const DEFAULT_TODOS = LIVE_DEFAULT_TODOS;
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
function isNormalizedText(
value: unknown,
maxCodePoints: number,
): value is string {
return typeof value === "string"
&& value.length > 0
&& value === value.trim()
&& [...value].length <= maxCodePoints
&& !CONTROL_CHARACTERS.test(value);
}
function isTodoList(value: unknown): value is readonly TodoItem[] {
if (
!Array.isArray(value)
|| value.length === 0
|| value.length > TODO_LIMIT
) {
return false;
}
const ids = new Set<string>();
for (const item of value) {
if (
!isRecord(item)
|| !isNormalizedText(item.id, TODO_ID_MAX_CODE_POINTS)
|| !isNormalizedText(item.title, TODO_TITLE_MAX_CODE_POINTS)
|| typeof item.completed !== "boolean"
|| ids.has(item.id)
) {
return false;
}
ids.add(item.id);
}
return true;
}
function cloneTodos(items: readonly TodoItem[]): readonly TodoItem[] {
return items.map((item) => ({ ...item }));
}
export async function resolveTodos(
storage: EvenStorage,
): Promise<readonly TodoItem[]> {
const cached = await readCache(storage, "todos", isTodoList);
return cloneTodos(cached ?? DEFAULT_TODOS);
}
export function toggleTodo(
items: readonly TodoItem[],
index: number,
): readonly TodoItem[] {
if (!Number.isInteger(index) || index < 0 || index >= items.length) {
return items;
}
return items.map((item, itemIndex) => itemIndex === index
? { ...item, completed: !item.completed }
: item);
}
export function writeTodos(
storage: EvenStorage,
items: readonly TodoItem[],
): Promise<boolean> {
return writeCache(storage, "todos", cloneTodos(items));
}