-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstore.ts
More file actions
73 lines (65 loc) · 1.73 KB
/
store.ts
File metadata and controls
73 lines (65 loc) · 1.73 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
/**
* External store for screen output entries and spinner state.
*
* Compatible with React's `useSyncExternalStore` for reactive rendering.
*
* @module
*/
import type {
OutputEntry,
OutputEntryInput,
OutputSnapshot,
OutputStore,
OutputSubscriber,
SpinnerState,
} from './types.js'
// ---------------------------------------------------------------------------
// Exports
// ---------------------------------------------------------------------------
/**
* Create an external output store for accumulating log, report,
* and spinner state in screen components.
*
* @returns A frozen {@link OutputStore} instance.
*/
export function createOutputStore(): OutputStore {
const entries: OutputEntry[] = []
const subscribers = new Set<OutputSubscriber>()
let nextId = 0
const idle: SpinnerState = Object.freeze({ status: 'idle' as const })
let spinnerState: SpinnerState = idle
let snapshot: OutputSnapshot = Object.freeze({ entries: Object.freeze([]), spinner: idle })
/**
* Rebuild the snapshot and notify all subscribers.
*
* @private
*/
const notify = (): void => {
snapshot = Object.freeze({
entries: Object.freeze([...entries]),
spinner: spinnerState,
})
;[...subscribers].map((cb) => cb())
}
return Object.freeze({
getSnapshot(): OutputSnapshot {
return snapshot
},
subscribe(callback: OutputSubscriber): () => void {
subscribers.add(callback)
return () => {
subscribers.delete(callback)
}
},
push(entry: OutputEntryInput): void {
const id = nextId
nextId += 1
entries.push({ ...entry, id })
notify()
},
setSpinner(state: SpinnerState): void {
spinnerState = state
notify()
},
})
}