forked from pingdotgg/t3code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuiStateStore.ts
More file actions
565 lines (516 loc) · 17.4 KB
/
uiStateStore.ts
File metadata and controls
565 lines (516 loc) · 17.4 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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
import { Debouncer } from "@tanstack/react-pacer";
import { create } from "zustand";
const PERSISTED_STATE_KEY = "t3code:ui-state:v1";
const LEGACY_PERSISTED_STATE_KEYS = [
"t3code:renderer-state:v8",
"t3code:renderer-state:v7",
"t3code:renderer-state:v6",
"t3code:renderer-state:v5",
"t3code:renderer-state:v4",
"t3code:renderer-state:v3",
"codething:renderer-state:v4",
"codething:renderer-state:v3",
"codething:renderer-state:v2",
"codething:renderer-state:v1",
] as const;
interface PersistedUiState {
expandedProjectCwds?: string[];
projectOrderCwds?: string[];
threadChangedFilesExpandedById?: Record<string, Record<string, boolean>>;
}
export interface UiProjectState {
projectExpandedById: Record<string, boolean>;
projectOrder: string[];
}
export interface UiThreadState {
threadLastVisitedAtById: Record<string, string>;
threadChangedFilesExpandedById: Record<string, Record<string, boolean>>;
}
export interface UiState extends UiProjectState, UiThreadState {}
export interface SyncProjectInput {
key: string;
cwd: string;
}
export interface SyncThreadInput {
key: string;
seedVisitedAt?: string | undefined;
}
const initialState: UiState = {
projectExpandedById: {},
projectOrder: [],
threadLastVisitedAtById: {},
threadChangedFilesExpandedById: {},
};
const persistedExpandedProjectCwds = new Set<string>();
const persistedProjectOrderCwds: string[] = [];
const currentProjectCwdById = new Map<string, string>();
let legacyKeysCleanedUp = false;
function readPersistedState(): UiState {
if (typeof window === "undefined") {
return initialState;
}
try {
const raw = window.localStorage.getItem(PERSISTED_STATE_KEY);
if (!raw) {
for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
const legacyRaw = window.localStorage.getItem(legacyKey);
if (!legacyRaw) {
continue;
}
hydratePersistedProjectState(JSON.parse(legacyRaw) as PersistedUiState);
return initialState;
}
return initialState;
}
const parsed = JSON.parse(raw) as PersistedUiState;
hydratePersistedProjectState(parsed);
return {
...initialState,
threadChangedFilesExpandedById: sanitizePersistedThreadChangedFilesExpanded(
parsed.threadChangedFilesExpandedById,
),
};
} catch {
return initialState;
}
}
function sanitizePersistedThreadChangedFilesExpanded(
value: PersistedUiState["threadChangedFilesExpandedById"],
): Record<string, Record<string, boolean>> {
if (!value || typeof value !== "object") {
return {};
}
const nextState: Record<string, Record<string, boolean>> = {};
for (const [threadId, turns] of Object.entries(value)) {
if (!threadId || !turns || typeof turns !== "object") {
continue;
}
const nextTurns: Record<string, boolean> = {};
for (const [turnId, expanded] of Object.entries(turns)) {
if (turnId && typeof expanded === "boolean" && expanded === false) {
nextTurns[turnId] = false;
}
}
if (Object.keys(nextTurns).length > 0) {
nextState[threadId] = nextTurns;
}
}
return nextState;
}
function hydratePersistedProjectState(parsed: PersistedUiState): void {
persistedExpandedProjectCwds.clear();
persistedProjectOrderCwds.length = 0;
for (const cwd of parsed.expandedProjectCwds ?? []) {
if (typeof cwd === "string" && cwd.length > 0) {
persistedExpandedProjectCwds.add(cwd);
}
}
for (const cwd of parsed.projectOrderCwds ?? []) {
if (typeof cwd === "string" && cwd.length > 0 && !persistedProjectOrderCwds.includes(cwd)) {
persistedProjectOrderCwds.push(cwd);
}
}
}
function persistState(state: UiState): void {
if (typeof window === "undefined") {
return;
}
try {
const expandedProjectCwds = Object.entries(state.projectExpandedById)
.filter(([, expanded]) => expanded)
.flatMap(([projectId]) => {
const cwd = currentProjectCwdById.get(projectId);
return cwd ? [cwd] : [];
});
const projectOrderCwds = state.projectOrder.flatMap((projectId) => {
const cwd = currentProjectCwdById.get(projectId);
return cwd ? [cwd] : [];
});
const threadChangedFilesExpandedById = Object.fromEntries(
Object.entries(state.threadChangedFilesExpandedById).flatMap(([threadId, turns]) => {
const nextTurns = Object.fromEntries(
Object.entries(turns).filter(([, expanded]) => expanded === false),
);
return Object.keys(nextTurns).length > 0 ? [[threadId, nextTurns]] : [];
}),
);
window.localStorage.setItem(
PERSISTED_STATE_KEY,
JSON.stringify({
expandedProjectCwds,
projectOrderCwds,
threadChangedFilesExpandedById,
} satisfies PersistedUiState),
);
if (!legacyKeysCleanedUp) {
legacyKeysCleanedUp = true;
for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
window.localStorage.removeItem(legacyKey);
}
}
} catch {
// Ignore quota/storage errors to avoid breaking chat UX.
}
}
const debouncedPersistState = new Debouncer(persistState, { wait: 500 });
function recordsEqual<T>(left: Record<string, T>, right: Record<string, T>): boolean {
const leftEntries = Object.entries(left);
const rightEntries = Object.entries(right);
if (leftEntries.length !== rightEntries.length) {
return false;
}
for (const [key, value] of leftEntries) {
if (right[key] !== value) {
return false;
}
}
return true;
}
function projectOrdersEqual(left: readonly string[], right: readonly string[]): boolean {
return (
left.length === right.length && left.every((projectId, index) => projectId === right[index])
);
}
function nestedBooleanRecordsEqual(
left: Record<string, Record<string, boolean>>,
right: Record<string, Record<string, boolean>>,
): boolean {
const leftEntries = Object.entries(left);
const rightEntries = Object.entries(right);
if (leftEntries.length !== rightEntries.length) {
return false;
}
for (const [key, value] of leftEntries) {
if (!(key in right) || !recordsEqual(value, right[key]!)) {
return false;
}
}
return true;
}
export function syncProjects(state: UiState, projects: readonly SyncProjectInput[]): UiState {
const previousProjectCwdById = new Map(currentProjectCwdById);
const previousProjectIdByCwd = new Map(
[...previousProjectCwdById.entries()].map(([projectId, cwd]) => [cwd, projectId] as const),
);
currentProjectCwdById.clear();
for (const project of projects) {
currentProjectCwdById.set(project.key, project.cwd);
}
const cwdMappingChanged =
previousProjectCwdById.size !== currentProjectCwdById.size ||
projects.some((project) => previousProjectCwdById.get(project.key) !== project.cwd);
const nextExpandedById: Record<string, boolean> = {};
const previousExpandedById = state.projectExpandedById;
const persistedOrderByCwd = new Map(
persistedProjectOrderCwds.map((cwd, index) => [cwd, index] as const),
);
const mappedProjects = projects.map((project, index) => {
const previousProjectIdForCwd = previousProjectIdByCwd.get(project.cwd);
const expanded =
previousExpandedById[project.key] ??
(previousProjectIdForCwd ? previousExpandedById[previousProjectIdForCwd] : undefined) ??
(persistedExpandedProjectCwds.size > 0
? persistedExpandedProjectCwds.has(project.cwd)
: true);
nextExpandedById[project.key] = expanded;
return {
id: project.key,
cwd: project.cwd,
incomingIndex: index,
};
});
const nextProjectOrder =
state.projectOrder.length > 0
? (() => {
const nextProjectIdByCwd = new Map(
mappedProjects.map((project) => [project.cwd, project.id] as const),
);
const usedProjectIds = new Set<string>();
const orderedProjectIds: string[] = [];
for (const projectId of state.projectOrder) {
const matchedProjectId =
(projectId in nextExpandedById ? projectId : undefined) ??
(() => {
const previousCwd = previousProjectCwdById.get(projectId);
return previousCwd ? nextProjectIdByCwd.get(previousCwd) : undefined;
})();
if (!matchedProjectId || usedProjectIds.has(matchedProjectId)) {
continue;
}
usedProjectIds.add(matchedProjectId);
orderedProjectIds.push(matchedProjectId);
}
for (const project of mappedProjects) {
if (usedProjectIds.has(project.id)) {
continue;
}
orderedProjectIds.push(project.id);
}
return orderedProjectIds;
})()
: mappedProjects
.map((project) => ({
id: project.id,
incomingIndex: project.incomingIndex,
orderIndex:
persistedOrderByCwd.get(project.cwd) ??
persistedProjectOrderCwds.length + project.incomingIndex,
}))
.toSorted((left, right) => {
const byOrder = left.orderIndex - right.orderIndex;
if (byOrder !== 0) {
return byOrder;
}
return left.incomingIndex - right.incomingIndex;
})
.map((project) => project.id);
if (
recordsEqual(state.projectExpandedById, nextExpandedById) &&
projectOrdersEqual(state.projectOrder, nextProjectOrder) &&
!cwdMappingChanged
) {
return state;
}
return {
...state,
projectExpandedById: nextExpandedById,
projectOrder: nextProjectOrder,
};
}
export function syncThreads(state: UiState, threads: readonly SyncThreadInput[]): UiState {
const retainedThreadIds = new Set(threads.map((thread) => thread.key));
const nextThreadLastVisitedAtById = Object.fromEntries(
Object.entries(state.threadLastVisitedAtById).filter(([threadId]) =>
retainedThreadIds.has(threadId),
),
);
for (const thread of threads) {
if (
nextThreadLastVisitedAtById[thread.key] === undefined &&
thread.seedVisitedAt !== undefined &&
thread.seedVisitedAt.length > 0
) {
nextThreadLastVisitedAtById[thread.key] = thread.seedVisitedAt;
}
}
const nextThreadChangedFilesExpandedById = Object.fromEntries(
Object.entries(state.threadChangedFilesExpandedById).filter(([threadId]) =>
retainedThreadIds.has(threadId),
),
);
if (
recordsEqual(state.threadLastVisitedAtById, nextThreadLastVisitedAtById) &&
nestedBooleanRecordsEqual(
state.threadChangedFilesExpandedById,
nextThreadChangedFilesExpandedById,
)
) {
return state;
}
return {
...state,
threadLastVisitedAtById: nextThreadLastVisitedAtById,
threadChangedFilesExpandedById: nextThreadChangedFilesExpandedById,
};
}
export function markThreadVisited(state: UiState, threadId: string, visitedAt?: string): UiState {
const at = visitedAt ?? new Date().toISOString();
const visitedAtMs = Date.parse(at);
const previousVisitedAt = state.threadLastVisitedAtById[threadId];
const previousVisitedAtMs = previousVisitedAt ? Date.parse(previousVisitedAt) : NaN;
if (
Number.isFinite(previousVisitedAtMs) &&
Number.isFinite(visitedAtMs) &&
previousVisitedAtMs >= visitedAtMs
) {
return state;
}
return {
...state,
threadLastVisitedAtById: {
...state.threadLastVisitedAtById,
[threadId]: at,
},
};
}
export function markThreadUnread(
state: UiState,
threadId: string,
latestTurnCompletedAt: string | null | undefined,
): UiState {
if (!latestTurnCompletedAt) {
return state;
}
const latestTurnCompletedAtMs = Date.parse(latestTurnCompletedAt);
if (Number.isNaN(latestTurnCompletedAtMs)) {
return state;
}
const unreadVisitedAt = new Date(latestTurnCompletedAtMs - 1).toISOString();
if (state.threadLastVisitedAtById[threadId] === unreadVisitedAt) {
return state;
}
return {
...state,
threadLastVisitedAtById: {
...state.threadLastVisitedAtById,
[threadId]: unreadVisitedAt,
},
};
}
export function clearThreadUi(state: UiState, threadId: string): UiState {
const hasVisitedState = threadId in state.threadLastVisitedAtById;
const hasChangedFilesState = threadId in state.threadChangedFilesExpandedById;
if (!hasVisitedState && !hasChangedFilesState) {
return state;
}
const nextThreadLastVisitedAtById = { ...state.threadLastVisitedAtById };
const nextThreadChangedFilesExpandedById = { ...state.threadChangedFilesExpandedById };
delete nextThreadLastVisitedAtById[threadId];
delete nextThreadChangedFilesExpandedById[threadId];
return {
...state,
threadLastVisitedAtById: nextThreadLastVisitedAtById,
threadChangedFilesExpandedById: nextThreadChangedFilesExpandedById,
};
}
export function setThreadChangedFilesExpanded(
state: UiState,
threadId: string,
turnId: string,
expanded: boolean,
): UiState {
const currentThreadState = state.threadChangedFilesExpandedById[threadId] ?? {};
const currentExpanded = currentThreadState[turnId] ?? true;
if (currentExpanded === expanded) {
return state;
}
if (expanded) {
if (!(turnId in currentThreadState)) {
return state;
}
const nextThreadState = { ...currentThreadState };
delete nextThreadState[turnId];
if (Object.keys(nextThreadState).length === 0) {
const nextState = { ...state.threadChangedFilesExpandedById };
delete nextState[threadId];
return {
...state,
threadChangedFilesExpandedById: nextState,
};
}
return {
...state,
threadChangedFilesExpandedById: {
...state.threadChangedFilesExpandedById,
[threadId]: nextThreadState,
},
};
}
return {
...state,
threadChangedFilesExpandedById: {
...state.threadChangedFilesExpandedById,
[threadId]: {
...currentThreadState,
[turnId]: false,
},
},
};
}
export function toggleProject(state: UiState, projectId: string): UiState {
const expanded = state.projectExpandedById[projectId] ?? true;
return {
...state,
projectExpandedById: {
...state.projectExpandedById,
[projectId]: !expanded,
},
};
}
export function setProjectExpanded(state: UiState, projectId: string, expanded: boolean): UiState {
if ((state.projectExpandedById[projectId] ?? true) === expanded) {
return state;
}
return {
...state,
projectExpandedById: {
...state.projectExpandedById,
[projectId]: expanded,
},
};
}
export function reorderProjects(
state: UiState,
draggedProjectIds: readonly string[],
targetProjectIds: readonly string[],
): UiState {
if (draggedProjectIds.length === 0) {
return state;
}
const draggedSet = new Set(draggedProjectIds);
const targetSet = new Set(targetProjectIds);
if (draggedProjectIds.every((id) => targetSet.has(id))) {
return state;
}
const originalTargetIndex = state.projectOrder.findIndex((id) => targetSet.has(id));
if (originalTargetIndex < 0) {
return state;
}
const projectOrder = [...state.projectOrder];
const removed: string[] = [];
let draggedBeforeTarget = 0;
for (let i = projectOrder.length - 1; i >= 0; i--) {
if (draggedSet.has(projectOrder[i]!)) {
removed.unshift(projectOrder.splice(i, 1)[0]!);
if (i < originalTargetIndex) {
draggedBeforeTarget++;
}
}
}
if (removed.length === 0) {
return state;
}
const insertIndex = originalTargetIndex - Math.max(0, draggedBeforeTarget - 1);
projectOrder.splice(insertIndex, 0, ...removed);
return {
...state,
projectOrder,
};
}
interface UiStateStore extends UiState {
syncProjects: (projects: readonly SyncProjectInput[]) => void;
syncThreads: (threads: readonly SyncThreadInput[]) => void;
markThreadVisited: (threadId: string, visitedAt?: string) => void;
markThreadUnread: (threadId: string, latestTurnCompletedAt: string | null | undefined) => void;
clearThreadUi: (threadId: string) => void;
setThreadChangedFilesExpanded: (threadId: string, turnId: string, expanded: boolean) => void;
toggleProject: (projectId: string) => void;
setProjectExpanded: (projectId: string, expanded: boolean) => void;
reorderProjects: (
draggedProjectIds: readonly string[],
targetProjectIds: readonly string[],
) => void;
}
export const useUiStateStore = create<UiStateStore>((set) => ({
...readPersistedState(),
syncProjects: (projects) => set((state) => syncProjects(state, projects)),
syncThreads: (threads) => set((state) => syncThreads(state, threads)),
markThreadVisited: (threadId, visitedAt) =>
set((state) => markThreadVisited(state, threadId, visitedAt)),
markThreadUnread: (threadId, latestTurnCompletedAt) =>
set((state) => markThreadUnread(state, threadId, latestTurnCompletedAt)),
clearThreadUi: (threadId) => set((state) => clearThreadUi(state, threadId)),
setThreadChangedFilesExpanded: (threadId, turnId, expanded) =>
set((state) => setThreadChangedFilesExpanded(state, threadId, turnId, expanded)),
toggleProject: (projectId) => set((state) => toggleProject(state, projectId)),
setProjectExpanded: (projectId, expanded) =>
set((state) => setProjectExpanded(state, projectId, expanded)),
reorderProjects: (draggedProjectIds, targetProjectIds) =>
set((state) => reorderProjects(state, draggedProjectIds, targetProjectIds)),
}));
useUiStateStore.subscribe((state) => debouncedPersistState.maybeExecute(state));
if (typeof window !== "undefined" && typeof window.addEventListener === "function") {
window.addEventListener("beforeunload", () => {
debouncedPersistState.flush();
});
}