Open History to see the last commit
1import { useSyncExternalStore } from "react";
2
3/**
4 * Guide state that lives outside React, so the app and the guide can both
5 * reach it:
6 *
7 * - the "active" (highlighted) section, set from app state (see
8 * `use-section-highlighting.ts`), or by hand from the dev menu.
9 * - which sections the reader has done (did the section's hands-on step).
10 * `guide/section-progress.ts` marks a section done when the app reports
11 * the section's action (its `doneWhen` in `guide/content.tsx`).
12 */
13interface GuideState {
14 activeSectionId: string | null;
15 doneSectionIds: ReadonlySet<string>;
16}
17
18let state: GuideState = { activeSectionId: null, doneSectionIds: new Set() };
19const listeners = new Set<() => void>();
20
21function update(next: GuideState) {
22 state = next;
23 for (const listener of listeners) listener();
24}
25
26function subscribe(listener: () => void) {
27 listeners.add(listener);
28 return () => listeners.delete(listener);
29}
30
31export function setActiveSection(id: string | null) {
32 if (id === state.activeSectionId) return;
33 update({ ...state, activeSectionId: id });
34}
35
36export function getActiveSection(): string | null {
37 return state.activeSectionId;
38}
39
40export function useActiveSection(): string | null {
41 return useSyncExternalStore(subscribe, getActiveSection, () => null);
42}
43
44export function markSectionDone(id: string) {
45 if (state.doneSectionIds.has(id)) return;
46 update({ ...state, doneSectionIds: new Set(state.doneSectionIds).add(id) });
47}
48
49export function markSectionNotDone(id: string) {
50 if (!state.doneSectionIds.has(id)) return;
51 const doneSectionIds = new Set(state.doneSectionIds);
52 doneSectionIds.delete(id);
53 update({ ...state, doneSectionIds });
54}
55
56export function isSectionDone(id: string): boolean {
57 return state.doneSectionIds.has(id);
58}
59
60/** The done section ids. A new set only when something changed, so it's safe as a snapshot. */
61export function getDoneSections(): ReadonlySet<string> {
62 return state.doneSectionIds;
63}
64
65const noDoneSections: ReadonlySet<string> = new Set();
66
67export function useDoneSections(): ReadonlySet<string> {
68 return useSyncExternalStore(subscribe, getDoneSections, () => noDoneSections);
69}
70
71export function useIsSectionDone(id: string): boolean {
72 return useSyncExternalStore(
73 subscribe,
74 () => isSectionDone(id),
75 () => false,
76 );
77}