@sdeck/plugin-basics 1.3.0 → 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/timers.tsx CHANGED
@@ -1,142 +1,46 @@
1
- /**
2
- * A countdown timer and a stopwatch. Their state lives here, by page and slot, so they keep
3
- * running while another page is shown.
4
- */
5
- import { type SlotInfo, setting, useKeyPress, useKeyPressed, useNow, usePage } from "@sdeck/plugin";
6
- import { surfaceStyle } from "@sdeck/schema";
7
- import { useEffect, useReducer } from "react";
1
+ /** A countdown timer and a stopwatch: their settings, what their buttons know, and their looks. */
2
+ import { type ActionValue, setting, useKeyPress, useNow } from "@sdeck/plugin";
3
+ import { iconLayer, type Layer, type Look, rectLayer, surface, textLayer } from "@sdeck/schema";
8
4
  import { plugin } from "./plugin.ts";
9
- import { column, fill, formatDuration, ring, THEME } from "./theme.ts";
5
+ import {
6
+ elapsed,
7
+ endListeners,
8
+ IDLE,
9
+ lengthOf,
10
+ runOf,
11
+ setRun,
12
+ stopwatchValues,
13
+ type TimerEnd,
14
+ timerValues,
15
+ toggled,
16
+ useRun,
17
+ } from "./runs.ts";
18
+ import { ring, THEME } from "./theme.ts";
10
19
 
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
- }
20
+ const variable = (kind: "timers" | "stopwatches", example: string) =>
21
+ setting.text("Variable name", {
22
+ placeholder: "From the label",
23
+ description: `Reads it anywhere: {{basics.${kind}.${example}.time}}`,
24
+ validate: (name) =>
25
+ !name || /^[a-z_][a-z0-9_]*$/.test(name)
26
+ ? undefined
27
+ : "should be small letters, digits and _, like focus_time",
28
+ });
16
29
 
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
- const runs = new Map<string, Run>();
27
- const runOf = (id: string) => runs.get(id) ?? { banked: 0 };
28
-
29
- const slotId = (page: string, slot: SlotInfo, kind: string) =>
30
- `${kind}|${page}|${slot.kind}|${"index" in slot ? slot.index : 0}`;
31
-
32
- /** Listeners of the "timer ends" trigger. */
33
- const ended = new Set<(event: { label: string; seconds: number }) => void>();
30
+ const paused: ActionValue = { name: "Paused", type: "boolean" };
34
31
 
35
32
  export const timerEnded = plugin.trigger({
36
33
  id: "timer-ended",
37
34
  name: "When a timer ends",
38
- description: "Fires when any Basics timer reaches zero.",
35
+ description:
36
+ "Fires when any Basics timer reaches zero, also on a page that is not shown. event.name says which.",
39
37
  subscribe: ({ fire }) => {
40
- const listener = (event: { label: string; seconds: number }) => fire(event);
41
- ended.add(listener);
42
- return () => ended.delete(listener);
38
+ const listener = (event: TimerEnd) => fire(event);
39
+ endListeners.add(listener);
40
+ return () => endListeners.delete(listener);
43
41
  },
44
42
  });
45
43
 
46
- /** One countdown's ring, time and caption. */
47
- function Countdown(props: {
48
- remaining: number;
49
- total: number;
50
- running: boolean;
51
- label: string;
52
- accent: string;
53
- background: string;
54
- wide: boolean;
55
- pressed: boolean;
56
- }) {
57
- const { remaining, total, running, label, accent, wide } = props;
58
- const done = remaining <= 0;
59
- // A finished timer blinks until it is reset.
60
- const now = useNow(done ? 500 : 60_000);
61
- const flash = done && now.getTime() % 1000 < 500;
62
- const background = flash ? THEME.danger : props.pressed ? THEME.faint : props.background;
63
- const caption = done ? "Done" : running ? label : remaining < total ? "Paused" : label;
64
- const time = formatDuration(remaining);
65
- const color = done ? "#ffffff" : running ? THEME.text : THEME.muted;
66
- if (wide) {
67
- return (
68
- <div
69
- style={{
70
- ...column,
71
- ...surfaceStyle(background),
72
- padding: "0 16px",
73
- gap: 6,
74
- fontWeight: 700,
75
- }}
76
- >
77
- <div
78
- style={{
79
- display: "flex",
80
- width: "100%",
81
- justifyContent: "space-between",
82
- alignItems: "baseline",
83
- }}
84
- >
85
- <div style={{ display: "flex", fontSize: 14, color: done ? "#ffffff" : THEME.muted }}>
86
- {caption || "Timer"}
87
- </div>
88
- <div style={{ display: "flex", fontSize: 26, color }}>{time}</div>
89
- </div>
90
- <div
91
- style={{
92
- display: "flex",
93
- width: "100%",
94
- height: 4,
95
- background: THEME.faint,
96
- borderRadius: 2,
97
- }}
98
- >
99
- <div
100
- style={{
101
- display: "flex",
102
- width: `${Math.round((1 - remaining / total) * 100)}%`,
103
- height: 4,
104
- background: accent,
105
- borderRadius: 2,
106
- }}
107
- />
108
- </div>
109
- </div>
110
- );
111
- }
112
- return (
113
- <div style={{ ...fill, ...surfaceStyle(background), position: "relative" }}>
114
- <img
115
- src={ring(1 - remaining / total, done ? "#ffffff" : accent, THEME.faint)}
116
- width={86}
117
- height={86}
118
- alt=""
119
- style={{ position: "absolute", left: 5, top: 5 }}
120
- />
121
- <div style={{ ...column, fontWeight: 700 }}>
122
- <div style={{ display: "flex", fontSize: time.length > 5 ? 17 : 22, color }}>{time}</div>
123
- {caption ? (
124
- <div
125
- style={{
126
- display: "flex",
127
- fontSize: 10,
128
- color: done ? "#ffffff" : THEME.muted,
129
- maxWidth: 60,
130
- }}
131
- >
132
- {caption}
133
- </div>
134
- ) : null}
135
- </div>
136
- </div>
137
- );
138
- }
139
-
140
44
  export const timer = plugin.action({
141
45
  id: "timer",
142
46
  name: "Timer",
@@ -148,60 +52,114 @@ export const timer = plugin.action({
148
52
  minutes: setting.number("Minutes", { default: 5, min: 0, max: 600 }),
149
53
  seconds: setting.number("Seconds", { default: 0, min: 0, max: 59 }),
150
54
  label: setting.text("Label", { placeholder: "Tea, Focus…" }),
55
+ variable: variable("timers", "tea"),
151
56
  accent: setting.color("Ring colour", { default: THEME.warm }),
152
57
  background: setting.color("Background", { default: THEME.background }),
153
58
  },
154
- component: ({ settings, slot, plugin }) => {
155
- const page = usePage();
156
- const id = slotId(page, slot, "timer");
157
- const total = Math.max(1, (settings.minutes * 60 + settings.seconds) * 1000);
158
- const [, redraw] = useReducer((n: number) => n + 1, 0);
159
- const pressed = useKeyPressed();
160
- const run = runOf(id);
161
- const running = run.startedAt !== undefined;
162
- const now = useNow(running ? 250 : 60_000).getTime();
163
- const remaining = Math.max(0, total - elapsed(run, now));
164
- const finished = running && remaining <= 0;
165
- useEffect(() => {
166
- if (!finished) return;
167
- // Ended: stop counting, and tell whoever waits for it.
168
- runs.set(id, { banked: total });
169
- const event = { label: settings.label, seconds: total / 1000 };
170
- for (const listener of [...ended]) listener(event);
171
- plugin.emit("timer-ended", event);
172
- redraw();
173
- }, [finished, id, total, settings.label, plugin]);
59
+ values: {
60
+ time: { name: "Time left", type: "string", description: "4:59" },
61
+ remaining: {
62
+ name: "Seconds left",
63
+ type: "number",
64
+ description: 'For formats of your own: duration(self.remaining, "mm:ss")',
65
+ },
66
+ total: { name: "Seconds in all", type: "number" },
67
+ progress: { name: "Done so far (%)", type: "number", description: "0 to 100, for a bar" },
68
+ counting: { name: "Counting", type: "boolean" },
69
+ paused,
70
+ done: { name: "Ended", type: "boolean" },
71
+ endsAt: {
72
+ name: "Ends at",
73
+ type: "number",
74
+ description: 'While it counts: time("HH:mm", self.endsAt)',
75
+ },
76
+ blink: { name: "Blinking", type: "boolean", description: "On and off once it ended" },
77
+ caption: { name: "Caption", type: "string", description: "The label, Paused or Done" },
78
+ ring: { name: "Ring", type: "string", description: "A picture, for an image layer" },
79
+ },
80
+ useValues: ({ settings, button }) => {
81
+ const run = useRun(button);
82
+ const total = lengthOf(settings);
83
+ const over = elapsed(run, Date.now()) >= total;
84
+ // A finished timer blinks until it is reset.
85
+ const now = useNow(over ? 500 : run.startedAt === undefined ? 60_000 : 250).getTime();
174
86
  useKeyPress(
175
87
  () => {
176
- const current = runOf(id);
88
+ const at = Date.now();
89
+ const current = runOf(button);
177
90
  // A finished timer starts over.
178
- runs.set(
179
- id,
180
- elapsed(current, Date.now()) >= total
181
- ? { banked: 0, startedAt: Date.now() }
182
- : toggled(current, Date.now()),
183
- );
184
- redraw();
91
+ const next = elapsed(current, at) >= total ? IDLE : current;
92
+ setRun(button, toggled(next, at));
185
93
  },
186
- {
187
- onLongPress: () => {
188
- runs.delete(id);
189
- redraw();
190
- },
191
- },
192
- );
193
- return (
194
- <Countdown
195
- remaining={remaining}
196
- total={total}
197
- running={running}
198
- label={settings.label}
199
- accent={settings.accent}
200
- background={settings.background}
201
- wide={slot.kind === "window"}
202
- pressed={pressed}
203
- />
94
+ { onLongPress: () => setRun(button, IDLE) },
204
95
  );
96
+ const values = timerValues(run, total, now);
97
+ return {
98
+ ...values,
99
+ blink: values.done && now % 1000 < 500,
100
+ caption: values.done ? "Done" : values.paused ? "Paused" : settings.label,
101
+ ring: ring(values.progress / 100, values.done ? "#ffffff" : settings.accent, THEME.faint),
102
+ };
103
+ },
104
+ look: (s, slot): Look => {
105
+ const alert = rectLayer("alert", { fill: THEME.danger, visible: "self.blink" });
106
+ /** Bright while it counts, grey while it waits. */
107
+ const states = (
108
+ id: string,
109
+ words: string,
110
+ options: Parameters<typeof textLayer>[2],
111
+ ): Layer[] => [
112
+ textLayer(id, words, {
113
+ ...options,
114
+ color: THEME.text,
115
+ visible: "self.counting || self.done",
116
+ }),
117
+ textLayer(`${id}-waiting`, words, {
118
+ ...options,
119
+ color: THEME.muted,
120
+ visible: "!self.counting && !self.done",
121
+ }),
122
+ ];
123
+ if (slot === "window") {
124
+ return {
125
+ background: surface(s.background),
126
+ layers: [
127
+ alert,
128
+ textLayer("caption", '{{self.caption || "Timer"}}', {
129
+ color: THEME.muted,
130
+ size: 14,
131
+ align: "left",
132
+ frame: { x: 6.5, y: 12, width: 43, height: 56 },
133
+ }),
134
+ ...states("time", "{{self.time}}", {
135
+ size: 26,
136
+ align: "right",
137
+ frame: { x: 50, y: 12, width: 43.5, height: 56 },
138
+ }),
139
+ {
140
+ id: "bar",
141
+ type: "bar",
142
+ value: "self.progress",
143
+ color: s.accent,
144
+ track: THEME.faint,
145
+ position: "bottom",
146
+ thickness: 4,
147
+ radius: 2,
148
+ frame: { x: 6.5, y: 75, width: 87, height: 7 },
149
+ },
150
+ ],
151
+ };
152
+ }
153
+ const long = s.minutes >= 60;
154
+ return {
155
+ background: surface(s.background),
156
+ layers: [
157
+ alert,
158
+ iconLayer("ring", "{{self.ring}}", { frame: { x: 5, y: 5, width: 90, height: 90 } }),
159
+ ...states("time", "{{self.time}}", { size: long ? 17 : 22 }),
160
+ textLayer("caption", "{{self.caption}}", { color: "#b6b8c4", size: 10 }),
161
+ ],
162
+ };
205
163
  },
206
164
  });
207
165
 
@@ -214,58 +172,58 @@ export const stopwatch = plugin.action({
214
172
  slots: ["key", "window"],
215
173
  settings: {
216
174
  label: setting.text("Label", { placeholder: "Shown under the time" }),
175
+ variable: variable("stopwatches", "run"),
217
176
  accent: setting.color("Colour while running", { default: THEME.success }),
218
177
  background: setting.color("Background", { default: THEME.background }),
219
178
  },
220
- component: ({ settings, slot }) => {
221
- const page = usePage();
222
- const id = slotId(page, slot, "stopwatch");
223
- const [, redraw] = useReducer((n: number) => n + 1, 0);
224
- const pressed = useKeyPressed();
225
- const run = runOf(id);
226
- const running = run.startedAt !== undefined;
227
- const now = useNow(running ? 100 : 60_000).getTime();
228
- const ms = elapsed(run, now);
229
- useKeyPress(
230
- () => {
231
- runs.set(id, toggled(runOf(id), Date.now()));
232
- redraw();
233
- },
234
- {
235
- onLongPress: () => {
236
- runs.delete(id);
237
- redraw();
238
- },
239
- },
240
- );
241
- const time = formatDuration(ms, false);
242
- const tenths = Math.floor((ms % 1000) / 100);
243
- const color = running ? settings.accent : ms > 0 ? THEME.text : THEME.muted;
244
- const caption = settings.label || (running ? "" : ms > 0 ? "Stopped" : "Stopwatch");
245
- const wide = slot.kind === "window";
246
- return (
247
- <div
248
- style={{
249
- ...column,
250
- ...(wide && { flexDirection: "row", gap: 14 }),
251
- ...surfaceStyle(pressed ? THEME.faint : settings.background),
252
- fontWeight: 700,
253
- }}
254
- >
255
- <div style={{ display: "flex", alignItems: "baseline" }}>
256
- <div style={{ display: "flex", fontSize: wide ? 32 : time.length > 5 ? 20 : 26, color }}>
257
- {time}
258
- </div>
259
- <div style={{ display: "flex", fontSize: wide ? 20 : 15, color: THEME.muted }}>
260
- .{tenths}
261
- </div>
262
- </div>
263
- {caption ? (
264
- <div style={{ display: "flex", fontSize: wide ? 14 : 11, color: THEME.muted }}>
265
- {caption}
266
- </div>
267
- ) : null}
268
- </div>
269
- );
179
+ values: {
180
+ time: { name: "Time", type: "string", description: "1:23" },
181
+ tenths: { name: "Tenths", type: "number", description: "0 to 9" },
182
+ elapsed: {
183
+ name: "Seconds so far",
184
+ type: "number",
185
+ description: 'For formats of your own: duration(self.elapsed, "mm:ss")',
186
+ },
187
+ counting: { name: "Counting", type: "boolean" },
188
+ paused,
189
+ caption: { name: "Caption", type: "string", description: "The label, or Stopped" },
190
+ },
191
+ useValues: ({ settings, button }) => {
192
+ const run = useRun(button);
193
+ const now = useNow(run.startedAt === undefined ? 60_000 : 100).getTime();
194
+ useKeyPress(() => setRun(button, toggled(runOf(button), Date.now())), {
195
+ onLongPress: () => setRun(button, IDLE),
196
+ });
197
+ const values = stopwatchValues(run, now);
198
+ const ms = elapsed(run, Math.max(now, run.startedAt ?? 0));
199
+ return {
200
+ ...values,
201
+ tenths: Math.floor((ms % 1000) / 100),
202
+ caption: settings.label || (values.counting ? "" : values.paused ? "Stopped" : "Stopwatch"),
203
+ };
204
+ },
205
+ look: (s, slot): Look => {
206
+ const wide = slot === "window";
207
+ // From an hour up there is no room for tenths, and nobody reads them.
208
+ const words = '{{self.time}}{{self.elapsed < 3600 ? "." + self.tenths : ""}}';
209
+ const row = wide ? { row: "time" } : {};
210
+ const size = wide ? 32 : 22;
211
+ return {
212
+ background: surface(s.background),
213
+ layers: [
214
+ textLayer("time", words, { ...row, size, color: s.accent, visible: "self.counting" }),
215
+ textLayer("time-stopped", words, {
216
+ ...row,
217
+ size,
218
+ color: THEME.text,
219
+ visible: "!self.counting",
220
+ }),
221
+ textLayer("caption", "{{self.caption}}", {
222
+ ...row,
223
+ size: wide ? 14 : 11,
224
+ color: THEME.muted,
225
+ }),
226
+ ],
227
+ };
270
228
  },
271
229
  });