Open History to see the last commit
1import type { FileRoutesByTo } from "@/routeTree.gen";
2
3import { matchesAppAction } from "./app-actions";
4import type { AppActionEvent, AppActionMatcher } from "./app-actions";
5
6/**
7 * The Notes app's screens, as route paths. Checked against the route tree,
8 * so a renamed route breaks the build.
9 */
10export const APP_SCREENS = [
11 "/",
12 "/folders/$folderId",
13 "/folders/$folderId/notes/$noteId",
14 "/settings",
15 "/analytics",
16] as const satisfies readonly (keyof FileRoutesByTo)[];
17
18export type AppScreen = (typeof APP_SCREENS)[number];
19
20/** Panels next to the app: the request inspector (a drawer on desktop, the sheet's Network view on phones). */
21export type AppPanel = "inspector";
22
23/**
24 * A state of the Notes app that a guide section is about: a screen, what
25 * the reader just did there, an open panel, or a mix. The guide highlights
26 * the section whose states match the app (see `sectionForAppState`).
27 */
28export interface AppState {
29 /** The screen. Omitted: any screen. */
30 screen?: AppScreen;
31 /** Narrows the screen to some route params, e.g. `{ folderId: "all" }`. */
32 params?: { folderId?: string; noteId?: string };
33 /**
34 * The reader's last action (see `app-actions.ts`). Omitted: any, or none.
35 * A matcher without a `status` only matches changes that weren't rolled
36 * back: a rejected change is the Rollbacks section's business.
37 */
38 lastAction?: AppActionMatcher;
39 /** An open panel. Omitted: any, or none. */
40 panel?: AppPanel;
41}
42
43/**
44 * What the app is doing right now, as the guide sees it. `changedAt` says
45 * when each part last changed (a counter, not a clock), so the newest thing
46 * the reader did wins over a panel that has just been left open.
47 */
48export interface AppSnapshot {
49 screen: AppScreen | null;
50 params: { folderId?: string; noteId?: string };
51 lastAction: AppActionEvent | null;
52 panel: AppPanel | null;
53 changedAt: { screen: number; lastAction: number; panel: number };
54 /** Counter for `changedAt`. */
55 clock: number;
56}
57
58export const INITIAL_APP_SNAPSHOT: AppSnapshot = {
59 screen: null,
60 params: {},
61 lastAction: null,
62 panel: null,
63 changedAt: { screen: 0, lastAction: 0, panel: 0 },
64 clock: 0,
65};
66
67export type AppStateInput =
68 | { kind: "navigated"; screen: AppScreen | null; params: AppSnapshot["params"] }
69 | { kind: "action"; event: AppActionEvent }
70 | { kind: "panel"; panel: AppPanel | null };
71
72/**
73 * Folds one thing that happened into the snapshot.
74 *
75 * - Navigating forgets the last action, unless the action was the reader
76 * opening the folder or note they've just landed on (those are reported on
77 * click, just before the route changes).
78 * - A `confirmed` event only counts while its action is still the last one:
79 * a save that lands after the reader has moved on isn't news.
80 * - A `rolled-back` event always counts: the change just disappeared.
81 */
82export function nextAppSnapshot(snapshot: AppSnapshot, input: AppStateInput): AppSnapshot {
83 const clock = snapshot.clock + 1;
84 switch (input.kind) {
85 case "navigated": {
86 if (input.screen === snapshot.screen && sameParams(input.params, snapshot.params)) {
87 return snapshot;
88 }
89 const keepAction = snapshot.lastAction !== null && ledTo(snapshot.lastAction, input.params);
90 return {
91 ...snapshot,
92 screen: input.screen,
93 params: input.params,
94 lastAction: keepAction ? snapshot.lastAction : null,
95 changedAt: { ...snapshot.changedAt, screen: clock },
96 clock,
97 };
98 }
99 case "action": {
100 const { event } = input;
101 if (
102 event.status === "confirmed" &&
103 (snapshot.lastAction === null || actionKey(snapshot.lastAction) !== actionKey(event))
104 ) {
105 return snapshot;
106 }
107 return {
108 ...snapshot,
109 lastAction: event,
110 changedAt: { ...snapshot.changedAt, lastAction: clock },
111 clock,
112 };
113 }
114 case "panel": {
115 if (input.panel === snapshot.panel) return snapshot;
116 return {
117 ...snapshot,
118 panel: input.panel,
119 changedAt: { ...snapshot.changedAt, panel: clock },
120 clock,
121 };
122 }
123 }
124}
125
126/**
127 * Whether something that happened is news the guide should follow. A panel
128 * closing isn't: the reader is done looking at it, not doing something new,
129 * so the highlight stays where it was.
130 */
131export function isNews(input: AppStateInput): boolean {
132 return !(input.kind === "panel" && input.panel === null);
133}
134
135/** Whether the app is in `state` right now. */
136export function matchesAppState(state: AppState, snapshot: AppSnapshot): boolean {
137 if (state.screen !== undefined && state.screen !== snapshot.screen) return false;
138 for (const [key, value] of Object.entries(state.params ?? {})) {
139 if (snapshot.params[key as keyof AppSnapshot["params"]] !== value) return false;
140 }
141 if (state.panel !== undefined && state.panel !== snapshot.panel) return false;
142 if (state.lastAction !== undefined) {
143 const event = snapshot.lastAction;
144 if (event === null || !matchesAppAction(state.lastAction, event)) return false;
145 if (event.status === "rolled-back" && state.lastAction.status === undefined) return false;
146 }
147 return true;
148}
149
150/**
151 * The guide section that matches the app best, or `null` if none does.
152 *
153 * Among the sections with a matching state, the one about the newest change
154 * wins (an action you just did beats a panel you opened a while ago), then
155 * the more specific state (a screen and an action beat an action alone),
156 * then the section that comes first in the guide.
157 */
158export function sectionForAppState(
159 snapshot: AppSnapshot,
160 sections: readonly { id: string; appStates: readonly AppState[] }[],
161): string | null {
162 let best: { id: string; recency: number; specificity: number } | null = null;
163 for (const section of sections) {
164 for (const state of section.appStates) {
165 if (!matchesAppState(state, snapshot)) continue;
166 const recency = stateRecency(state, snapshot);
167 const specificity = stateSpecificity(state);
168 if (
169 best === null ||
170 recency > best.recency ||
171 (recency === best.recency && specificity > best.specificity)
172 ) {
173 best = { id: section.id, recency, specificity };
174 }
175 }
176 }
177 return best?.id ?? null;
178}
179
180/** When the newest part of the app this state looks at changed. */
181function stateRecency(state: AppState, snapshot: AppSnapshot): number {
182 return Math.max(
183 state.screen !== undefined || state.params !== undefined ? snapshot.changedAt.screen : 0,
184 state.lastAction !== undefined ? snapshot.changedAt.lastAction : 0,
185 state.panel !== undefined ? snapshot.changedAt.panel : 0,
186 );
187}
188
189/** How many things a state pins down. */
190function stateSpecificity(state: AppState): number {
191 return (
192 (state.screen !== undefined ? 1 : 0) +
193 Object.keys(state.params ?? {}).length +
194 Object.keys(state.lastAction ?? {}).length +
195 (state.panel !== undefined ? 1 : 0)
196 );
197}
198
199function sameParams(a: AppSnapshot["params"], b: AppSnapshot["params"]): boolean {
200 return a.folderId === b.folderId && a.noteId === b.noteId;
201}
202
203/** The action was opening the folder or note these route params point at. */
204function ledTo(event: AppActionEvent, params: AppSnapshot["params"]): boolean {
205 if (event.type === "folder.opened") return params.folderId === event.folderId;
206 if (event.type === "note.opened") return params.noteId === event.noteId;
207 return false;
208}
209
210/** The action without its outcome, so `applied` and `confirmed` of one change compare equal. */
211function actionKey(event: AppActionEvent): string {
212 const { status: _status, error: _error, ...action } = event;
213 return JSON.stringify(action);
214}
215
216/** The app screen a route id stands for, e.g. `/_workspace/folders/$folderId/` → `/folders/$folderId`. */
217export function screenFromRouteId(routeId: string): AppScreen | null {
218 const path = routeId.replace(/^\/_workspace/, "").replace(/(.)\/$/, "$1") || "/";
219 return (APP_SCREENS as readonly string[]).includes(path) ? (path as AppScreen) : null;
220}