@sdeck/plugin-basics 1.3.1 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/runs.ts ADDED
@@ -0,0 +1,224 @@
1
+ /**
2
+ * Every timer and stopwatch there is: whether it counts, and what it says. It is kept by button and
3
+ * not in what draws it, so they go on and end on time while another page is shown, and anything can
4
+ * read them as `basics.timers.tea.time`.
5
+ */
6
+ import type { PlacedButton, PluginContext } from "@sdeck/plugin";
7
+ import { useSyncExternalStore } from "react";
8
+ import { plugin } from "./plugin.ts";
9
+ import { formatDuration } from "./theme.ts";
10
+
11
+ /** A running or paused clock: `startedAt` while running, `banked` ms from earlier runs. */
12
+ export interface Run {
13
+ startedAt?: number;
14
+ banked: number;
15
+ }
16
+
17
+ /** How long it has run, up to `now`. */
18
+ export const elapsed = (run: Run, now: number) =>
19
+ run.banked + (run.startedAt === undefined ? 0 : now - run.startedAt);
20
+
21
+ /** Starts a paused run, or pauses a running one. */
22
+ export function toggled(run: Run, now: number): Run {
23
+ return run.startedAt === undefined ? { ...run, startedAt: now } : { banked: elapsed(run, now) };
24
+ }
25
+
26
+ export const IDLE: Run = { banked: 0 };
27
+
28
+ const runs = new Map<string, Run>();
29
+ const watchers = new Set<() => void>();
30
+ const subscribe = (watcher: () => void) => {
31
+ watchers.add(watcher);
32
+ return () => void watchers.delete(watcher);
33
+ };
34
+
35
+ export const runOf = (button: string): Run => runs.get(button) ?? IDLE;
36
+
37
+ /** The button's run, kept up to date on every deck that shows it. */
38
+ export const useRun = (button: string): Run => useSyncExternalStore(subscribe, () => runOf(button));
39
+
40
+ export function setRun(button: string, run: Run): void {
41
+ if (run === IDLE) runs.delete(button);
42
+ else runs.set(button, run);
43
+ changed();
44
+ }
45
+
46
+ function changed() {
47
+ arm();
48
+ publish();
49
+ for (const watcher of [...watchers]) watcher();
50
+ }
51
+
52
+ // -- What they say ----------------------------------------------------------------------------
53
+
54
+ interface TimerSettings {
55
+ minutes: number;
56
+ seconds: number;
57
+ label: string;
58
+ }
59
+
60
+ /** How long a timer runs, in ms. */
61
+ export const lengthOf = (s: Pick<TimerSettings, "minutes" | "seconds">) =>
62
+ Math.max(1, (s.minutes * 60 + s.seconds) * 1000);
63
+
64
+ export function timerValues(run: Run, total: number, now: number) {
65
+ // Started since `now` was read: none of it has passed.
66
+ const passed = elapsed(run, Math.max(now, run.startedAt ?? 0));
67
+ const remaining = Math.min(total, Math.max(0, total - passed));
68
+ const done = remaining <= 0;
69
+ const counting = run.startedAt !== undefined && !done;
70
+ return {
71
+ time: formatDuration(remaining),
72
+ remaining: Math.ceil(remaining / 1000),
73
+ total: total / 1000,
74
+ progress: Math.round((1 - remaining / total) * 1000) / 10,
75
+ counting,
76
+ paused: !counting && !done && remaining < total,
77
+ done,
78
+ /** The moment it ends, while it counts. */
79
+ ...(counting && { endsAt: (run.startedAt ?? 0) + total - run.banked }),
80
+ };
81
+ }
82
+
83
+ export function stopwatchValues(run: Run, now: number) {
84
+ const ms = elapsed(run, Math.max(now, run.startedAt ?? 0));
85
+ const counting = run.startedAt !== undefined;
86
+ return {
87
+ time: formatDuration(ms, false),
88
+ elapsed: Math.floor(ms / 1000),
89
+ counting,
90
+ paused: !counting && ms > 0,
91
+ };
92
+ }
93
+
94
+ // -- Variables --------------------------------------------------------------------------------
95
+
96
+ /** `Focus time` → `focus_time`: something to write after a dot. Empty when nothing is left. */
97
+ export function variableName(text: string): string {
98
+ const plain = text.normalize("NFKD").replace(/\p{M}/gu, "").toLowerCase();
99
+ const name = plain.replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
100
+ return /^\d/.test(name) ? `_${name}` : name;
101
+ }
102
+
103
+ /**
104
+ * The buttons by the name of their variable: the one the user gave, else from the label, else from
105
+ * where it is. A name that is taken gets a number.
106
+ */
107
+ export function namedButtons(buttons: readonly PlacedButton[]): Map<string, PlacedButton> {
108
+ const named = new Map<string, PlacedButton>();
109
+ const place = ({ page, slot }: PlacedButton) =>
110
+ variableName(`${page} ${slot.kind}${slot.kind === "window" ? "" : ` ${slot.index + 1}`}`);
111
+ // Chosen names come first, so that no label takes one.
112
+ const chosen = (b: PlacedButton) => variableName(String(b.settings.variable ?? ""));
113
+ for (const button of [...buttons.filter(chosen), ...buttons.filter((b) => !chosen(b))]) {
114
+ const base =
115
+ chosen(button) || variableName(String(button.settings.label ?? "")) || place(button);
116
+ let name = base;
117
+ for (let n = 2; named.has(name); n++) name = `${base}_${n}`;
118
+ named.set(name, button);
119
+ }
120
+ return named;
121
+ }
122
+
123
+ let timerButtons = new Map<string, PlacedButton>();
124
+ let stopwatchButtons = new Map<string, PlacedButton>();
125
+
126
+ const readTimers = () => {
127
+ const now = Date.now();
128
+ return Object.fromEntries(
129
+ [...timerButtons].map(([name, { id, settings }]) => {
130
+ const s = settings as unknown as TimerSettings;
131
+ return [name, { label: s.label, ...timerValues(runOf(id), lengthOf(s), now) }];
132
+ }),
133
+ );
134
+ };
135
+
136
+ const readStopwatches = () => {
137
+ const now = Date.now();
138
+ return Object.fromEntries(
139
+ [...stopwatchButtons].map(([name, { id, settings }]) => [
140
+ name,
141
+ { label: settings.label, ...stopwatchValues(runOf(id), now) },
142
+ ]),
143
+ );
144
+ };
145
+
146
+ /** Often enough that the seconds do not seem to skip. */
147
+ const EVERY_MS = 200;
148
+
149
+ export const timers = plugin.state.json<ReturnType<typeof readTimers>>("timers", "Timers", {
150
+ description: "Every timer by its variable name: basics.timers.tea.time",
151
+ poll: { everyMs: EVERY_MS, read: readTimers },
152
+ });
153
+
154
+ export const stopwatches = plugin.state.json<ReturnType<typeof readStopwatches>>(
155
+ "stopwatches",
156
+ "Stopwatches",
157
+ {
158
+ description: "Every stopwatch by its variable name: basics.stopwatches.run.time",
159
+ poll: { everyMs: EVERY_MS, read: readStopwatches },
160
+ },
161
+ );
162
+
163
+ function publish() {
164
+ timers.set(readTimers());
165
+ stopwatches.set(readStopwatches());
166
+ }
167
+
168
+ // -- Ending -----------------------------------------------------------------------------------
169
+
170
+ export interface TimerEnd {
171
+ /** The name of its variable. */
172
+ name: string;
173
+ label: string;
174
+ seconds: number;
175
+ }
176
+
177
+ /** Listeners of the "timer ends" trigger. */
178
+ export const endListeners = new Set<(event: TimerEnd) => void>();
179
+
180
+ const alarms = new Map<string, ReturnType<typeof setTimeout>>();
181
+
182
+ /** Sets an alarm for every timer that counts. */
183
+ function arm() {
184
+ for (const alarm of alarms.values()) clearTimeout(alarm);
185
+ alarms.clear();
186
+ for (const [name, { id, settings }] of timerButtons) {
187
+ const s = settings as unknown as TimerSettings;
188
+ const run = runOf(id);
189
+ if (run.startedAt === undefined) continue;
190
+ const left = lengthOf(s) - elapsed(run, Date.now());
191
+ alarms.set(
192
+ id,
193
+ setTimeout(() => end(id, name, s), Math.max(0, left)),
194
+ );
195
+ }
196
+ }
197
+
198
+ function end(id: string, name: string, settings: TimerSettings) {
199
+ // It stops counting, and whoever waits for it hears.
200
+ setRun(id, { banked: lengthOf(settings) });
201
+ const event = { name, label: settings.label, seconds: lengthOf(settings) / 1000 };
202
+ for (const listener of [...endListeners]) listener(event);
203
+ plugin.context?.emit("timer-ended", event);
204
+ }
205
+
206
+ /** Follows the user's timers and stopwatches while the plugin runs. */
207
+ export function followButtons(context: PluginContext): () => void {
208
+ const refresh = () => {
209
+ const placed = context.buttons.list();
210
+ const of = (action: string) => placed.filter((b) => b.action === action);
211
+ timerButtons = namedButtons(of("timer"));
212
+ stopwatchButtons = namedButtons(of("stopwatch"));
213
+ const kept = new Set([...of("timer"), ...of("stopwatch")].map((b) => b.id));
214
+ for (const id of [...runs.keys()]) if (!kept.has(id)) runs.delete(id);
215
+ changed();
216
+ };
217
+ const stop = context.buttons.watch(refresh);
218
+ refresh();
219
+ return () => {
220
+ stop();
221
+ for (const alarm of alarms.values()) clearTimeout(alarm);
222
+ alarms.clear();
223
+ };
224
+ }
package/src/theme.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  /** The colours and shapes Basics draws with, so its keys look like one set. */
2
2
  import { KEY } from "@sdeck/schema";
3
- import type { CSSProperties } from "react";
4
3
 
5
4
  export const THEME = {
6
5
  background: KEY,
@@ -16,16 +15,6 @@ export const THEME = {
16
15
  success: "#3ddc84",
17
16
  } as const;
18
17
 
19
- export const fill: CSSProperties = {
20
- display: "flex",
21
- width: "100%",
22
- height: "100%",
23
- alignItems: "center",
24
- justifyContent: "center",
25
- };
26
-
27
- export const column: CSSProperties = { ...fill, flexDirection: "column" };
28
-
29
18
  /** `m:ss`, or `h:mm:ss` from an hour up. Rounds up, so a timer shows 0:00 only when done. */
30
19
  export function formatDuration(ms: number, roundUp = true): string {
31
20
  const total = Math.max(0, roundUp ? Math.ceil(ms / 1000) : Math.floor(ms / 1000));