Skip to content
Source
Sign inSign up
fuko/trytanstackdb-v2
Open History to see the last commit

guide-store.ts

77 lines2.3 KB

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. Phase 4 sets it from app state; for
8 * now it can be set from the dev menu in the guide header.
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>;
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();
25​
26function subscribe(listener: () => void) {
27 listeners.add(listener);
28 return () => listeners.delete(listener);
30​
31export function setActiveSection(id: string | null) {
32 if (id === state.activeSectionId) return;
33 update({ ...state, activeSectionId: id });
35​
36export function getActiveSection(): string | null {
37 return state.activeSectionId;
39​
40export function useActiveSection(): string | null {
41 return useSyncExternalStore(subscribe, getActiveSection, () => null);
43​
44export function markSectionDone(id: string) {
45 if (state.doneSectionIds.has(id)) return;
46 update({ ...state, doneSectionIds: new Set(state.doneSectionIds).add(id) });
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 });
55​
56export function isSectionDone(id: string): boolean {
57 return state.doneSectionIds.has(id);
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;
64​
65const noDoneSections: ReadonlySet<string> = new Set();
66​
67export function useDoneSections(): ReadonlySet<string> {
68 return useSyncExternalStore(subscribe, getDoneSections, () => noDoneSections);
70​
71export function useIsSectionDone(id: string): boolean {
72 return useSyncExternalStore(
73 subscribe,
74 () => isSectionDone(id),
75 () => false,
76 );