@sdeck/plugin-basics 0.0.0-stage → 1.0.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/dist/index.js ADDED
@@ -0,0 +1,1559 @@
1
+ // ../core/src/element.ts
2
+ var runtime;
3
+ function registerElementRuntime(next) {
4
+ runtime = next;
5
+ }
6
+ // ../react/src/render.ts
7
+ function isReactElement(value) {
8
+ return typeof value === "object" && value !== null && "$$typeof" in value;
9
+ }
10
+ var defaultRenderer = {};
11
+ var fontRenderers = new WeakMap;
12
+ async function createRenderer(fonts) {
13
+ const { Renderer } = await import("@takumi-rs/core");
14
+ const renderer = new Renderer;
15
+ for (const font of fonts) {
16
+ await renderer.registerFont({
17
+ name: font.name,
18
+ data: font.data,
19
+ ...font.weight !== undefined && { weight: font.weight },
20
+ ...font.style !== undefined && { style: font.style }
21
+ });
22
+ }
23
+ return renderer;
24
+ }
25
+ function getRenderer(fonts) {
26
+ if (!fonts?.length) {
27
+ defaultRenderer.current ??= createRenderer([]);
28
+ defaultRenderer.current.catch(() => {
29
+ defaultRenderer.current = undefined;
30
+ });
31
+ return defaultRenderer.current;
32
+ }
33
+ let renderer = fontRenderers.get(fonts);
34
+ if (!renderer) {
35
+ renderer = createRenderer(fonts);
36
+ renderer.catch(() => fontRenderers.delete(fonts));
37
+ fontRenderers.set(fonts, renderer);
38
+ }
39
+ return renderer;
40
+ }
41
+ var number = (value) => typeof value === "number" && Number.isFinite(value) ? value : undefined;
42
+ function toNode(node, text = true) {
43
+ if ("text" in node) {
44
+ return text ? { type: "text", text: node.text } : { type: "container", children: [] };
45
+ }
46
+ const { style, tw, src, width, height } = node.props;
47
+ const common = {
48
+ ...typeof tw === "string" && { tw }
49
+ };
50
+ if (node.type === "img") {
51
+ if (typeof src !== "string")
52
+ throw new Error("<img> needs a string `src` (URL or data: URI)");
53
+ return {
54
+ type: "image",
55
+ src,
56
+ ...number(width) !== undefined && { width: number(width) },
57
+ ...number(height) !== undefined && { height: number(height) },
58
+ ...typeof style === "object" && style !== null && { style },
59
+ ...common
60
+ };
61
+ }
62
+ return {
63
+ type: "container",
64
+ style: { display: "flex", ...typeof style === "object" ? style : {} },
65
+ children: node.children.filter((child) => text || !("text" in child)).map((child) => toNode(child, text)),
66
+ ...common
67
+ };
68
+ }
69
+ var reconciler;
70
+ var flushing = 0;
71
+ function flushAll(renderer) {
72
+ flushing++;
73
+ try {
74
+ renderer.flushSyncWork();
75
+ for (let i = 0;i < 20 && renderer.flushPassiveEffects(); i++)
76
+ renderer.flushSyncWork();
77
+ } finally {
78
+ flushing--;
79
+ }
80
+ }
81
+ function loadReconciler() {
82
+ reconciler ??= (async () => {
83
+ let factoryModule;
84
+ let constants;
85
+ let React;
86
+ try {
87
+ [factoryModule, constants, React] = await Promise.all([
88
+ import("react-reconciler"),
89
+ import("react-reconciler/constants.js"),
90
+ import("react")
91
+ ]);
92
+ } catch (cause) {
93
+ throw new Error("Rendering React elements requires `react` (>=19.3) to be installed", {
94
+ cause
95
+ });
96
+ }
97
+ let priority = constants.NoEventPriority;
98
+ const noop = () => {};
99
+ const hostConfig = {
100
+ supportsMutation: true,
101
+ supportsPersistence: false,
102
+ supportsHydration: false,
103
+ isPrimaryRenderer: true,
104
+ warnsIfNotActing: false,
105
+ noTimeout: -1,
106
+ scheduleTimeout: setTimeout,
107
+ cancelTimeout: clearTimeout,
108
+ supportsMicrotasks: true,
109
+ scheduleMicrotask: queueMicrotask,
110
+ createInstance: (type, props) => {
111
+ const { children: _children, ...rest } = props;
112
+ return { type, props: rest, children: [] };
113
+ },
114
+ createTextInstance: (text) => ({ text }),
115
+ shouldSetTextContent: () => false,
116
+ appendInitialChild: (parent, child) => parent.children.push(child),
117
+ appendChild: (parent, child) => parent.children.push(child),
118
+ appendChildToContainer: (container, child) => container.children.push(child),
119
+ insertBefore: (parent, child, before) => {
120
+ const children = parent.children;
121
+ const existing = children.indexOf(child);
122
+ if (existing !== -1)
123
+ children.splice(existing, 1);
124
+ children.splice(children.indexOf(before), 0, child);
125
+ },
126
+ insertInContainerBefore: (container, child, before) => {
127
+ const children = container.children;
128
+ const existing = children.indexOf(child);
129
+ if (existing !== -1)
130
+ children.splice(existing, 1);
131
+ children.splice(children.indexOf(before), 0, child);
132
+ },
133
+ removeChild: (parent, child) => {
134
+ parent.children.splice(parent.children.indexOf(child), 1);
135
+ },
136
+ removeChildFromContainer: (container, child) => {
137
+ container.children.splice(container.children.indexOf(child), 1);
138
+ },
139
+ clearContainer: (container) => {
140
+ container.children = [];
141
+ },
142
+ commitUpdate: (instance, _type, _prev, next) => {
143
+ const { children: _children, ...rest } = next;
144
+ instance.props = rest;
145
+ },
146
+ commitTextUpdate: (text, _old, next) => {
147
+ text.text = next;
148
+ },
149
+ finalizeInitialChildren: () => false,
150
+ getPublicInstance: (instance) => instance,
151
+ getRootHostContext: () => ({}),
152
+ getChildHostContext: (parent) => parent,
153
+ prepareForCommit: () => null,
154
+ resetAfterCommit: (container) => container.onCommit(),
155
+ preparePortalMount: noop,
156
+ detachDeletedInstance: noop,
157
+ hideInstance: noop,
158
+ unhideInstance: noop,
159
+ hideTextInstance: noop,
160
+ unhideTextInstance: noop,
161
+ getInstanceFromNode: () => null,
162
+ beforeActiveInstanceBlur: noop,
163
+ afterActiveInstanceBlur: noop,
164
+ prepareScopeUpdate: noop,
165
+ getInstanceFromScope: () => null,
166
+ bindToConsole: (method, args) => console[method]?.bind(console, ...args) ?? noop,
167
+ extraDevToolsConfig: null,
168
+ rendererVersion: "0.0.0",
169
+ rendererPackageName: "sdeck",
170
+ getCurrentUpdatePriority: () => priority,
171
+ setCurrentUpdatePriority: (next) => {
172
+ priority = next;
173
+ },
174
+ resolveUpdatePriority: () => priority !== constants.NoEventPriority ? priority : flushing > 0 ? constants.DiscreteEventPriority : constants.DefaultEventPriority,
175
+ resolveEventType: () => null,
176
+ resolveEventTimeStamp: () => -1.1,
177
+ shouldAttemptEagerTransition: () => false,
178
+ trackSchedulerEvent: noop,
179
+ requestPostPaintCallback: noop,
180
+ maySuspendCommit: () => false,
181
+ preloadInstance: () => true,
182
+ startSuspendingCommit: noop,
183
+ suspendInstance: noop,
184
+ waitForCommitToBeReady: () => null,
185
+ getSuspendedCommitReason: () => null,
186
+ NotPendingTransition: null,
187
+ HostTransitionContext: React.createContext(null),
188
+ resetFormInstance: noop
189
+ };
190
+ const factory = factoryModule.default ?? factoryModule;
191
+ return factory(hostConfig);
192
+ })();
193
+ reconciler.catch(() => {
194
+ reconciler = undefined;
195
+ });
196
+ return reconciler;
197
+ }
198
+ function noopIndicator() {}
199
+ async function createReactRoot(size, onFrame, options = {}) {
200
+ const [takumi, renderer] = await Promise.all([getRenderer(options.fonts), loadReconciler()]);
201
+ let dirty = false;
202
+ let drawing;
203
+ let lastTree;
204
+ let unmounted = false;
205
+ let renderError;
206
+ let initial = true;
207
+ const fail = (error) => {
208
+ if (initial)
209
+ renderError ??= { error };
210
+ else
211
+ (options.onError ?? ((e) => console.error("sdeck: React render failed:", e)))(error);
212
+ };
213
+ async function draw() {
214
+ await Promise.resolve();
215
+ while (dirty && !unmounted) {
216
+ dirty = false;
217
+ try {
218
+ const [root] = container.children;
219
+ if (!root)
220
+ continue;
221
+ const tree = toNode(root, options.text !== false);
222
+ const key = JSON.stringify(tree);
223
+ if (key === lastTree)
224
+ continue;
225
+ lastTree = key;
226
+ const pixels = await takumi.render(tree, {
227
+ width: size.width,
228
+ height: size.height,
229
+ format: "raw",
230
+ ...options.scale !== undefined && { devicePixelRatio: options.scale }
231
+ });
232
+ await onFrame({
233
+ data: new Uint8Array(pixels.buffer, pixels.byteOffset, pixels.byteLength),
234
+ width: size.width,
235
+ height: size.height,
236
+ channels: 4
237
+ });
238
+ } catch (error) {
239
+ lastTree = undefined;
240
+ fail(error);
241
+ }
242
+ }
243
+ drawing = undefined;
244
+ }
245
+ const container = {
246
+ children: [],
247
+ onCommit() {
248
+ dirty = true;
249
+ drawing ??= draw();
250
+ }
251
+ };
252
+ const onError = (error) => fail(error);
253
+ const onCaughtError = () => {};
254
+ const root = renderer.createContainer(container, 1, null, false, null, "", onError, onCaughtError, onError, noopIndicator, null);
255
+ const flush = () => flushAll(renderer);
256
+ const handle = {
257
+ render(element) {
258
+ if (unmounted)
259
+ throw new Error("This React root was unmounted");
260
+ renderer.updateContainerSync(element, root, null, null);
261
+ flush();
262
+ },
263
+ async idle() {
264
+ while (drawing)
265
+ await drawing;
266
+ if (initial && renderError) {
267
+ const { error } = renderError;
268
+ renderError = undefined;
269
+ throw error;
270
+ }
271
+ initial = false;
272
+ },
273
+ async unmount() {
274
+ if (unmounted)
275
+ return;
276
+ renderer.updateContainerSync(null, root, null, null);
277
+ flush();
278
+ unmounted = true;
279
+ await drawing;
280
+ }
281
+ };
282
+ return handle;
283
+ }
284
+ async function renderReact(element, size, fonts, scale) {
285
+ let frame;
286
+ const root = await createReactRoot(size, (next) => {
287
+ frame = next;
288
+ }, { ...fonts && { fonts }, ...scale !== undefined && { scale } });
289
+ try {
290
+ root.render(element);
291
+ await root.idle();
292
+ } finally {
293
+ await root.unmount();
294
+ }
295
+ if (!frame)
296
+ throw new Error("React element rendered nothing");
297
+ return frame;
298
+ }
299
+ registerElementRuntime({
300
+ matches: isReactElement,
301
+ render: (element, size, options) => renderReact(element, size, options?.fonts),
302
+ createRoot: (size, onFrame, options) => createReactRoot(size, onFrame, options)
303
+ });
304
+ // ../app/src/app.tsx
305
+ import { Fragment, useSyncExternalStore } from "react";
306
+
307
+ // ../app/src/context.ts
308
+ import { createContext, useContext } from "react";
309
+ var DeckContext = createContext(undefined);
310
+ var SlotContext = createContext(undefined);
311
+ var NavigatorContext = createContext(undefined);
312
+ function useDeck() {
313
+ const deck = useContext(DeckContext);
314
+ if (!deck)
315
+ throw new Error("useDeck() must be used inside a component mounted by @sdeck/app");
316
+ return deck;
317
+ }
318
+ function useSlot() {
319
+ return useContext(SlotContext);
320
+ }
321
+ // ../app/src/hooks.ts
322
+ import { useContext as useContext2, useEffect, useRef, useState, useSyncExternalStore as useSyncExternalStore2 } from "react";
323
+
324
+ // ../app/src/swipe.ts
325
+ var SWIPE_WINDOW_MS = 400;
326
+
327
+ class SwipeTracker {
328
+ #handlers = new Set;
329
+ #stamps = new Map;
330
+ #completing = new Set;
331
+ #first;
332
+ constructor(deck) {
333
+ deck.on("sensorDown", (index) => this.#down(index));
334
+ }
335
+ get active() {
336
+ return this.#handlers.size > 0;
337
+ }
338
+ stamp(index) {
339
+ return this.#stamps.get(index) ?? 0;
340
+ }
341
+ completes(index) {
342
+ return this.#completing.has(index);
343
+ }
344
+ listen(handler) {
345
+ this.#handlers.add(handler);
346
+ return () => void this.#handlers.delete(handler);
347
+ }
348
+ #down(index) {
349
+ this.#completing.delete(index);
350
+ const now = performance.now();
351
+ const first = this.#first;
352
+ if (!this.active || !first || first.index === index || now - first.at > SWIPE_WINDOW_MS) {
353
+ this.#first = { index, at: now };
354
+ return;
355
+ }
356
+ this.#first = undefined;
357
+ this.#completing.add(index);
358
+ for (const sensor of [first.index, index])
359
+ this.#stamps.set(sensor, this.stamp(sensor) + 1);
360
+ const direction = index > first.index ? "right" : "left";
361
+ for (const handler of [...this.#handlers])
362
+ handler(direction);
363
+ }
364
+ }
365
+ var trackers = new WeakMap;
366
+ function swipeTracker(deck) {
367
+ let tracker = trackers.get(deck);
368
+ if (!tracker) {
369
+ tracker = new SwipeTracker(deck);
370
+ trackers.set(deck, tracker);
371
+ }
372
+ return tracker;
373
+ }
374
+
375
+ // ../app/src/hooks.ts
376
+ function useLatest(value) {
377
+ const ref = useRef(value);
378
+ useEffect(() => {
379
+ ref.current = value;
380
+ });
381
+ return ref;
382
+ }
383
+ function useTarget(kind, explicit) {
384
+ const slot = useSlot();
385
+ if (explicit !== undefined)
386
+ return explicit;
387
+ return slot?.kind === kind ? slot.index : undefined;
388
+ }
389
+ function usePressed(kind, explicit) {
390
+ const deck = useDeck();
391
+ const target = useTarget(kind, explicit);
392
+ const [pressed, setPressed] = useState(false);
393
+ if (target === undefined) {
394
+ throw new Error(`use${kind === "key" ? "Key" : "Sensor"}Pressed() needs an index outside a ${kind} slot`);
395
+ }
396
+ useEffect(() => {
397
+ setPressed(false);
398
+ const offDown = deck.on(`${kind}Down`, (i) => i === target && setPressed(true));
399
+ const offUp = deck.on(`${kind}Up`, (i) => i === target && setPressed(false));
400
+ return () => {
401
+ offDown();
402
+ offUp();
403
+ };
404
+ }, [deck, kind, target]);
405
+ return pressed;
406
+ }
407
+ function useKeyPressed(key) {
408
+ return usePressed("key", key);
409
+ }
410
+ function usePress(kind, onPress, gestures, explicit) {
411
+ const deck = useDeck();
412
+ const target = useTarget(kind, explicit);
413
+ const latest = useLatest({
414
+ onPress,
415
+ onLongPress: gestures.onLongPress,
416
+ longPressMs: gestures.longPressMs ?? 500,
417
+ onDoublePress: gestures.onDoublePress ?? gestures.onDoubleTap,
418
+ doublePressMs: gestures.doublePressMs ?? gestures.doubleTapMs ?? 300,
419
+ onRelease: gestures.onRelease ?? false
420
+ });
421
+ useEffect(() => {
422
+ const swipes = kind === "sensor" ? swipeTracker(deck) : undefined;
423
+ const state = new Map;
424
+ const held = new Set;
425
+ const get = (index) => {
426
+ let s = state.get(index);
427
+ if (!s) {
428
+ s = { longFired: false, immediate: false, downAt: 0, stamp: 0 };
429
+ state.set(index, s);
430
+ }
431
+ return s;
432
+ };
433
+ const offDown = deck.on(`${kind}Down`, (index) => {
434
+ if (target !== undefined && index !== target)
435
+ return;
436
+ if (swipes?.completes(index))
437
+ return;
438
+ held.add(index);
439
+ const o = latest.current;
440
+ const s = get(index);
441
+ s.longFired = false;
442
+ s.downAt = performance.now();
443
+ s.stamp = swipes?.stamp(index) ?? 0;
444
+ s.immediate = !o.onLongPress && !o.onDoublePress && !o.onRelease && !swipes?.active;
445
+ if (s.immediate) {
446
+ o.onPress?.(index);
447
+ return;
448
+ }
449
+ if (o.onLongPress) {
450
+ s.long = setTimeout(() => {
451
+ if (swipes && swipes.stamp(index) !== s.stamp)
452
+ return;
453
+ s.longFired = true;
454
+ clearTimeout(s.double);
455
+ s.double = undefined;
456
+ latest.current.onLongPress?.(index);
457
+ }, o.longPressMs);
458
+ }
459
+ });
460
+ const offUp = deck.on(`${kind}Up`, (index) => {
461
+ if (!held.delete(index))
462
+ return;
463
+ const s = get(index);
464
+ clearTimeout(s.long);
465
+ if (s.immediate || s.longFired)
466
+ return;
467
+ if (!swipes?.active)
468
+ return released(index, s);
469
+ const wait = Math.max(0, SWIPE_WINDOW_MS - (performance.now() - s.downAt));
470
+ s.deferred = setTimeout(() => {
471
+ if (swipes.stamp(index) === s.stamp)
472
+ released(index, s);
473
+ }, wait);
474
+ });
475
+ function released(index, s) {
476
+ const o = latest.current;
477
+ if (!o.onDoublePress) {
478
+ o.onPress?.(index);
479
+ } else if (s.double !== undefined) {
480
+ clearTimeout(s.double);
481
+ s.double = undefined;
482
+ o.onDoublePress(index);
483
+ } else {
484
+ s.double = setTimeout(() => {
485
+ s.double = undefined;
486
+ latest.current.onPress?.(index);
487
+ }, o.doublePressMs);
488
+ }
489
+ }
490
+ return () => {
491
+ offDown();
492
+ offUp();
493
+ for (const s of state.values()) {
494
+ clearTimeout(s.long);
495
+ clearTimeout(s.double);
496
+ clearTimeout(s.deferred);
497
+ }
498
+ };
499
+ }, [deck, kind, target, latest]);
500
+ }
501
+ function useKeyPress(onPress, options = {}) {
502
+ usePress("key", onPress, options, options.key);
503
+ }
504
+ function useInterval(callback, ms) {
505
+ const latest = useLatest(callback);
506
+ useEffect(() => {
507
+ if (ms === null)
508
+ return;
509
+ const id = setInterval(() => latest.current(), ms);
510
+ return () => clearInterval(id);
511
+ }, [ms, latest]);
512
+ }
513
+ function useNow(ms = 1000) {
514
+ const [now, setNow] = useState(() => new Date);
515
+ useInterval(() => setNow(new Date), ms);
516
+ return now;
517
+ }
518
+ function useNavigation() {
519
+ const nav = useContext2(NavigatorContext);
520
+ if (!nav)
521
+ throw new Error("useNavigation() must be used inside a component mounted by sdeck/app");
522
+ const state = useSyncExternalStore2(nav.subscribe, nav.getSnapshot);
523
+ return {
524
+ ...state,
525
+ canGoBack: state.stack.length > 1,
526
+ canGoForward: state.forwardStack.length > 0,
527
+ push: nav.push,
528
+ replace: nav.replace,
529
+ back: nav.back,
530
+ forward: nav.forward,
531
+ next: nav.next,
532
+ previous: nav.previous,
533
+ pages: nav.pages,
534
+ sequence: nav.sequence,
535
+ home: nav.home
536
+ };
537
+ }
538
+ function usePage() {
539
+ return useNavigation().page;
540
+ }
541
+ // ../schema/src/layers.ts
542
+ function iconLayer(id, icon, options = {}) {
543
+ const { color, size = 52, position = "middle", visible, row, frame } = options;
544
+ const src = /^[a-z0-9]+\/[A-Za-z0-9-]+$/.test(icon) ? `icon:${icon}` : icon;
545
+ return {
546
+ id,
547
+ type: "image",
548
+ src,
549
+ size,
550
+ position,
551
+ ...color && { color },
552
+ ...visible && { visible },
553
+ ...row && { row },
554
+ ...frame && { frame }
555
+ };
556
+ }
557
+ function textLayer(id, text, options = {}) {
558
+ const { color = "#ffffff", size = 14, weight = 700, position = "middle" } = options;
559
+ const { visible, row, frame } = options;
560
+ return {
561
+ id,
562
+ type: "text",
563
+ text,
564
+ color,
565
+ size,
566
+ weight,
567
+ position,
568
+ ...visible && { visible },
569
+ ...row && { row },
570
+ ...frame && { frame }
571
+ };
572
+ }
573
+ // ../plugin/src/settings.ts
574
+ function checkSchema(schema, sources = {}) {
575
+ const problems = [];
576
+ const types = new Set([
577
+ "text",
578
+ "number",
579
+ "boolean",
580
+ "color",
581
+ "select",
582
+ "page",
583
+ "image",
584
+ "secret"
585
+ ]);
586
+ for (const [key, field] of Object.entries(schema)) {
587
+ if (!field || typeof field !== "object" || !types.has(field.type)) {
588
+ problems.push(`setting "${key}" has an unknown type`);
589
+ continue;
590
+ }
591
+ if (typeof field.label !== "string")
592
+ problems.push(`setting "${key}" needs a label`);
593
+ const source = "source" in field ? field.source : undefined;
594
+ if (source !== undefined && !(source in sources)) {
595
+ problems.push(`setting "${key}" uses unknown option source "${source}"`);
596
+ }
597
+ if (field.type === "select" && (!Array.isArray(field.options) || field.options.length === 0 && source === undefined)) {
598
+ problems.push(`setting "${key}" needs at least one option or a source`);
599
+ }
600
+ for (const other of "dependsOn" in field && field.dependsOn || []) {
601
+ if (!(other in schema))
602
+ problems.push(`setting "${key}" depends on unknown "${other}"`);
603
+ }
604
+ if (field.visibleIf !== undefined) {
605
+ for (const other of Object.keys(field.visibleIf)) {
606
+ if (!(other in schema))
607
+ problems.push(`setting "${key}" depends on unknown "${other}"`);
608
+ }
609
+ }
610
+ }
611
+ return problems;
612
+ }
613
+
614
+ // ../plugin/src/plugin.ts
615
+ var PERMISSIONS = [
616
+ "shell",
617
+ "process",
618
+ "filesystem",
619
+ "network",
620
+ "input",
621
+ "audio",
622
+ "clipboard"
623
+ ];
624
+ var ID = /^(@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*$/;
625
+ var NAMESPACE = /^[a-z][\w-]{0,31}$/;
626
+ var LOCAL_ID = /^[\w.-]+$/;
627
+ function defineAction(def) {
628
+ return {
629
+ ...def,
630
+ slots: def.slots ?? ["key"],
631
+ settings: def.settings ?? {}
632
+ };
633
+ }
634
+ function defineTrigger(def) {
635
+ return { ...def, settings: def.settings ?? {} };
636
+ }
637
+ function definePlugin(def) {
638
+ const problems = checkPlugin(def);
639
+ if (problems.length > 0) {
640
+ throw new TypeError(`invalid plugin "${def?.id}": ${problems.join("; ")}`);
641
+ }
642
+ return def;
643
+ }
644
+ function checkLocalIds(kind, items, problems) {
645
+ const seen = new Set;
646
+ for (const item of items) {
647
+ const name = typeof item?.id === "string" ? item.id : "?";
648
+ if (typeof item?.id !== "string" || !LOCAL_ID.test(item.id)) {
649
+ problems.push(`${kind} "${name}": id must be letters, digits, ".", "-" or "_"`);
650
+ } else if (seen.has(item.id)) {
651
+ problems.push(`${kind} "${name}" is defined twice`);
652
+ }
653
+ seen.add(name);
654
+ }
655
+ return seen;
656
+ }
657
+ function checkPlugin(value) {
658
+ if (!value || typeof value !== "object")
659
+ return ["not an object"];
660
+ const def = value;
661
+ const problems = [];
662
+ if (typeof def.id !== "string" || !ID.test(def.id)) {
663
+ problems.push("id must be a package-style name (lowercase, e.g. `my-plugin` or `@me/plugin`)");
664
+ }
665
+ if (typeof def.name !== "string" || def.name === "")
666
+ problems.push("name is required");
667
+ if (typeof def.version !== "string" || def.version === "")
668
+ problems.push("version is required");
669
+ if (def.namespace !== undefined && !NAMESPACE.test(def.namespace)) {
670
+ problems.push("namespace must be lowercase letters, digits, - or _ (starting with a letter)");
671
+ }
672
+ if (def.activate !== undefined && typeof def.activate !== "function") {
673
+ problems.push("activate must be a function");
674
+ }
675
+ if (def.permissions !== undefined) {
676
+ if (!Array.isArray(def.permissions))
677
+ problems.push("permissions must be an array");
678
+ else
679
+ for (const p of def.permissions)
680
+ if (!PERMISSIONS.includes(p))
681
+ problems.push(`unknown permission "${String(p)}"`);
682
+ }
683
+ if (def.settings !== undefined) {
684
+ for (const p of checkSchema(def.settings, def.optionSources ?? {})) {
685
+ problems.push(`plugin ${p}`);
686
+ }
687
+ }
688
+ if (def.commands !== undefined) {
689
+ if (!Array.isArray(def.commands))
690
+ problems.push("commands must be an array");
691
+ else {
692
+ checkLocalIds("command", def.commands, problems);
693
+ for (const c of def.commands) {
694
+ const name = typeof c?.id === "string" ? c.id : "?";
695
+ if (typeof c?.name !== "string")
696
+ problems.push(`command "${name}": name is required`);
697
+ if (typeof c?.run !== "function")
698
+ problems.push(`command "${name}": run is required`);
699
+ }
700
+ }
701
+ }
702
+ if (def.onboarding !== undefined)
703
+ problems.push(...checkOnboarding(def));
704
+ const sources = def.optionSources ?? {};
705
+ if (typeof sources !== "object")
706
+ problems.push("optionSources must be an object");
707
+ else
708
+ for (const [name, fn] of Object.entries(sources))
709
+ if (typeof fn !== "function")
710
+ problems.push(`option source "${name}" must be a function`);
711
+ if (!Array.isArray(def.actions))
712
+ return [...problems, "actions must be an array"];
713
+ checkLocalIds("action", def.actions, problems);
714
+ for (const action of def.actions) {
715
+ const name = typeof action?.id === "string" ? action.id : "?";
716
+ if (typeof action?.name !== "string")
717
+ problems.push(`action "${name}": name is required`);
718
+ const hasComponent = typeof action?.component === "function" || typeof action?.component === "object";
719
+ const hasRun = typeof action?.run === "function";
720
+ if (!hasComponent && !hasRun)
721
+ problems.push(`action "${name}": needs run or component`);
722
+ if (action?.look !== undefined && typeof action.look !== "function") {
723
+ problems.push(`action "${name}": look must be a function`);
724
+ }
725
+ const slots = action?.slots ?? ["key"];
726
+ if (!Array.isArray(slots) || slots.length === 0 || slots.some((s) => !["key", "sensor", "window"].includes(s))) {
727
+ problems.push(`action "${name}": slots must list "key", "sensor" and/or "window"`);
728
+ }
729
+ for (const p of checkSchema(action?.settings ?? {}, sources)) {
730
+ problems.push(`action "${name}": ${p}`);
731
+ }
732
+ for (const [key, field] of Object.entries(action?.settings ?? {})) {
733
+ if (field?.type === "secret") {
734
+ problems.push(`action "${name}": setting "${key}": secrets belong in the plugin settings`);
735
+ }
736
+ }
737
+ }
738
+ if (def.state !== undefined) {
739
+ if (!Array.isArray(def.state))
740
+ problems.push("state must be an array");
741
+ else {
742
+ checkLocalIds("state", def.state, problems);
743
+ for (const s of def.state) {
744
+ const name = typeof s?.id === "string" ? s.id : "?";
745
+ if (typeof s?.name !== "string")
746
+ problems.push(`state "${name}": name is required`);
747
+ if (!["number", "string", "boolean", "json"].includes(s?.type)) {
748
+ problems.push(`state "${name}": type must be number, string, boolean or json`);
749
+ }
750
+ if (s?.poll && (typeof s.poll.read !== "function" || !(s.poll.everyMs > 0))) {
751
+ problems.push(`state "${name}": poll needs read() and everyMs > 0`);
752
+ }
753
+ if (s?.start !== undefined && typeof s.start !== "function") {
754
+ problems.push(`state "${name}": start must be a function`);
755
+ }
756
+ }
757
+ }
758
+ }
759
+ if (def.triggers !== undefined) {
760
+ if (!Array.isArray(def.triggers))
761
+ problems.push("triggers must be an array");
762
+ else {
763
+ checkLocalIds("trigger", def.triggers, problems);
764
+ for (const t of def.triggers) {
765
+ const name = typeof t?.id === "string" ? t.id : "?";
766
+ if (typeof t?.name !== "string")
767
+ problems.push(`trigger "${name}": name is required`);
768
+ if (typeof t?.subscribe !== "function") {
769
+ problems.push(`trigger "${name}": subscribe is required`);
770
+ }
771
+ for (const p of checkSchema(t?.settings ?? {}, sources)) {
772
+ problems.push(`trigger "${name}": ${p}`);
773
+ }
774
+ }
775
+ }
776
+ }
777
+ return problems;
778
+ }
779
+ function checkOnboarding(def) {
780
+ const onboarding = def.onboarding;
781
+ if (!Array.isArray(onboarding?.steps))
782
+ return ["onboarding: steps must be an array"];
783
+ const problems = [];
784
+ checkLocalIds("onboarding step", onboarding.steps, problems);
785
+ const settings = def.settings ?? {};
786
+ const commands = new Set((def.commands ?? []).map((c) => c.id));
787
+ for (const step of onboarding.steps) {
788
+ const name = typeof step?.id === "string" ? step.id : "?";
789
+ if (typeof step?.title !== "string")
790
+ problems.push(`onboarding step "${name}": title is required`);
791
+ for (const key of step?.settings ?? []) {
792
+ if (!(key in settings))
793
+ problems.push(`onboarding step "${name}": no setting "${key}"`);
794
+ }
795
+ if (step?.command !== undefined && !commands.has(step.command)) {
796
+ problems.push(`onboarding step "${name}": no command "${step.command}"`);
797
+ }
798
+ if (step?.done !== undefined && typeof step.done !== "function") {
799
+ problems.push(`onboarding step "${name}": done must be a function`);
800
+ }
801
+ }
802
+ const page = onboarding.starterPage;
803
+ if (page) {
804
+ const actions = new Set((def.actions ?? []).map((a) => a.id));
805
+ const used = [
806
+ ...Object.values(page.keys ?? {}),
807
+ ...Object.values(page.sensors ?? {}),
808
+ ...page.window ? [page.window] : []
809
+ ];
810
+ for (const { action } of used) {
811
+ if (!actions.has(action))
812
+ problems.push(`onboarding starter page: no action "${action}"`);
813
+ }
814
+ }
815
+ return problems;
816
+ }
817
+ // src/theme.ts
818
+ var THEME = {
819
+ background: "#16171d",
820
+ text: "#f4f4f5",
821
+ muted: "#8b8d98",
822
+ faint: "#2b2d36",
823
+ accent: "#5b8cff",
824
+ warm: "#ffb547",
825
+ danger: "#ff5d5d",
826
+ success: "#3ddc84"
827
+ };
828
+ var fill = {
829
+ display: "flex",
830
+ width: "100%",
831
+ height: "100%",
832
+ alignItems: "center",
833
+ justifyContent: "center"
834
+ };
835
+ var column = { ...fill, flexDirection: "column" };
836
+ function formatDuration(ms, roundUp = true) {
837
+ const total = Math.max(0, roundUp ? Math.ceil(ms / 1000) : Math.floor(ms / 1000));
838
+ const hours = Math.floor(total / 3600);
839
+ const minutes = Math.floor(total % 3600 / 60);
840
+ const seconds = total % 60;
841
+ const ss = String(seconds).padStart(2, "0");
842
+ return hours > 0 ? `${hours}:${String(minutes).padStart(2, "0")}:${ss}` : `${minutes}:${ss}`;
843
+ }
844
+ var svg = (body, size = 100) => `data:image/svg+xml,${encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${size} ${size}" width="${size}" height="${size}">${body}</svg>`)}`;
845
+ function ring(part, color, track, width = 7) {
846
+ const r = 50 - width / 2 - 1;
847
+ const length = 2 * Math.PI * r;
848
+ const shown = Math.min(1, Math.max(0, part)) * length;
849
+ return svg(`<circle cx="50" cy="50" r="${r}" fill="none" stroke="${track}" stroke-width="${width}"/>` + (shown > 0 ? `<circle cx="50" cy="50" r="${r}" fill="none" stroke="${color}" stroke-width="${width}" stroke-linecap="round" stroke-dasharray="${shown} ${length}" transform="rotate(-90 50 50)"/>` : ""));
850
+ }
851
+
852
+ // src/clock.tsx
853
+ import { jsx, jsxs } from "react/jsx-runtime";
854
+ function analogFace(date, colors, seconds) {
855
+ const h = date.getHours() % 12;
856
+ const m = date.getMinutes();
857
+ const s = date.getSeconds();
858
+ const hand = (angle, length, width, color, tail = 0) => `<line x1="50" y1="${50 + tail}" x2="50" y2="${50 - length}" stroke="${color}" stroke-width="${width}" stroke-linecap="round" transform="rotate(${angle} 50 50)"/>`;
859
+ const ticks = Array.from({ length: 12 }, (_, i) => {
860
+ const major = i % 3 === 0;
861
+ return `<line x1="50" y1="${major ? 6 : 7}" x2="50" y2="${major ? 13 : 11}" stroke="${colors.ticks}" stroke-width="${major ? 3 : 2}" stroke-linecap="round" transform="rotate(${i * 30} 50 50)"/>`;
862
+ }).join("");
863
+ return svg(`<circle cx="50" cy="50" r="47" fill="${colors.face}"/>${ticks}` + hand((h + m / 60) * 30, 24, 6, colors.hands) + hand((m + s / 60) * 6, 35, 4, colors.hands) + (seconds ? hand(s * 6, 38, 1.8, colors.accent, 8) : "") + `<circle cx="50" cy="50" r="3.5" fill="${seconds ? colors.accent : colors.hands}"/>`);
864
+ }
865
+ function timeParts(date, hour12) {
866
+ const hours = date.getHours();
867
+ const shown = hour12 ? hours % 12 || 12 : hours;
868
+ return {
869
+ main: `${hour12 ? shown : String(shown).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`,
870
+ seconds: String(date.getSeconds()).padStart(2, "0"),
871
+ period: hour12 ? hours < 12 ? "AM" : "PM" : ""
872
+ };
873
+ }
874
+ var clock = defineAction({
875
+ id: "clock",
876
+ name: "Clock",
877
+ description: "The time, as digits or hands, and optionally the date.",
878
+ category: "Time",
879
+ icon: "clock",
880
+ slots: ["key", "window"],
881
+ settings: {
882
+ style: {
883
+ type: "select",
884
+ label: "Style",
885
+ default: "digital",
886
+ options: [
887
+ { value: "digital", label: "Digits" },
888
+ { value: "analog", label: "Hands" }
889
+ ]
890
+ },
891
+ hour12: { type: "boolean", label: "12-hour clock", visibleIf: { style: "digital" } },
892
+ seconds: { type: "boolean", label: "Show seconds", default: true },
893
+ date: { type: "boolean", label: "Show the date" },
894
+ color: { type: "color", label: "Colour", default: THEME.text },
895
+ accent: { type: "color", label: "Accent", default: THEME.accent },
896
+ background: { type: "color", label: "Background", default: THEME.background }
897
+ },
898
+ component: ({ settings, slot }) => {
899
+ const now = useNow(settings.seconds ? 1000 : 1e4);
900
+ const wide = slot.kind === "window";
901
+ const day = now.toLocaleDateString(undefined, {
902
+ weekday: "short",
903
+ day: "numeric",
904
+ month: "short"
905
+ });
906
+ if (settings.style === "analog") {
907
+ const face = analogFace(now, { face: THEME.faint, hands: settings.color, accent: settings.accent, ticks: THEME.muted }, settings.seconds);
908
+ const size = wide ? 50 : settings.date ? 66 : 82;
909
+ return /* @__PURE__ */ jsxs("div", {
910
+ style: {
911
+ ...fill,
912
+ flexDirection: wide ? "row" : "column",
913
+ gap: wide ? 12 : 4,
914
+ background: settings.background
915
+ },
916
+ children: [
917
+ /* @__PURE__ */ jsx("img", {
918
+ src: face,
919
+ width: size,
920
+ height: size,
921
+ alt: ""
922
+ }),
923
+ settings.date || wide ? /* @__PURE__ */ jsx("div", {
924
+ style: {
925
+ display: "flex",
926
+ color: THEME.muted,
927
+ fontSize: wide ? 18 : 12,
928
+ fontWeight: 700
929
+ },
930
+ children: day
931
+ }) : null
932
+ ]
933
+ });
934
+ }
935
+ const { main, seconds, period } = timeParts(now, settings.hour12);
936
+ const small = [settings.seconds ? `:${seconds}` : "", period].filter(Boolean).join(" ");
937
+ const big = wide ? 34 : main.length > 4 ? 27 : 31;
938
+ return /* @__PURE__ */ jsxs("div", {
939
+ style: {
940
+ ...column,
941
+ background: settings.background,
942
+ color: settings.color,
943
+ fontWeight: 700,
944
+ gap: wide ? 0 : 2,
945
+ ...wide && { flexDirection: "row", gap: 14 }
946
+ },
947
+ children: [
948
+ /* @__PURE__ */ jsxs("div", {
949
+ style: { display: "flex", alignItems: "baseline", gap: 3 },
950
+ children: [
951
+ /* @__PURE__ */ jsx("div", {
952
+ style: { display: "flex", fontSize: big, letterSpacing: -0.5 },
953
+ children: main
954
+ }),
955
+ wide && small ? /* @__PURE__ */ jsx("div", {
956
+ style: { display: "flex", fontSize: 16, color: settings.accent },
957
+ children: small
958
+ }) : null
959
+ ]
960
+ }),
961
+ !wide && small ? /* @__PURE__ */ jsx("div", {
962
+ style: { display: "flex", fontSize: 13, color: settings.accent },
963
+ children: small
964
+ }) : null,
965
+ settings.date ? /* @__PURE__ */ jsx("div", {
966
+ style: { display: "flex", fontSize: wide ? 16 : 12, color: THEME.muted },
967
+ children: day
968
+ }) : null
969
+ ]
970
+ });
971
+ }
972
+ });
973
+ var date = defineAction({
974
+ id: "date",
975
+ name: "Date",
976
+ description: "Today's date, like a page torn off a calendar.",
977
+ category: "Time",
978
+ icon: "calendar",
979
+ slots: ["key", "window"],
980
+ settings: {
981
+ accent: { type: "color", label: "Accent", default: THEME.danger },
982
+ background: { type: "color", label: "Background", default: THEME.background }
983
+ },
984
+ component: ({ settings, slot }) => {
985
+ const now = useNow(60000);
986
+ const weekday = now.toLocaleDateString(undefined, { weekday: "short" });
987
+ const month = now.toLocaleDateString(undefined, { month: "short" });
988
+ if (slot.kind === "window") {
989
+ return /* @__PURE__ */ jsxs("div", {
990
+ style: { ...fill, gap: 14, background: settings.background, fontWeight: 700 },
991
+ children: [
992
+ /* @__PURE__ */ jsx("div", {
993
+ style: { display: "flex", fontSize: 36, color: THEME.text },
994
+ children: now.getDate()
995
+ }),
996
+ /* @__PURE__ */ jsxs("div", {
997
+ style: { display: "flex", flexDirection: "column" },
998
+ children: [
999
+ /* @__PURE__ */ jsx("div", {
1000
+ style: { display: "flex", fontSize: 15, color: settings.accent },
1001
+ children: now.toLocaleDateString(undefined, { weekday: "long" })
1002
+ }),
1003
+ /* @__PURE__ */ jsx("div", {
1004
+ style: { display: "flex", fontSize: 14, color: THEME.muted },
1005
+ children: now.toLocaleDateString(undefined, { month: "long", year: "numeric" })
1006
+ })
1007
+ ]
1008
+ })
1009
+ ]
1010
+ });
1011
+ }
1012
+ return /* @__PURE__ */ jsxs("div", {
1013
+ style: {
1014
+ ...column,
1015
+ justifyContent: "flex-start",
1016
+ background: settings.background,
1017
+ fontWeight: 700
1018
+ },
1019
+ children: [
1020
+ /* @__PURE__ */ jsx("div", {
1021
+ style: {
1022
+ display: "flex",
1023
+ width: "100%",
1024
+ height: 26,
1025
+ alignItems: "center",
1026
+ justifyContent: "center",
1027
+ background: settings.accent,
1028
+ color: "#ffffff",
1029
+ fontSize: 13,
1030
+ letterSpacing: 1
1031
+ },
1032
+ children: weekday.toUpperCase()
1033
+ }),
1034
+ /* @__PURE__ */ jsx("div", {
1035
+ style: { display: "flex", fontSize: 40, color: THEME.text, marginTop: 4 },
1036
+ children: now.getDate()
1037
+ }),
1038
+ /* @__PURE__ */ jsx("div", {
1039
+ style: { display: "flex", fontSize: 12, color: THEME.muted },
1040
+ children: month
1041
+ })
1042
+ ]
1043
+ });
1044
+ }
1045
+ });
1046
+
1047
+ // src/timers.tsx
1048
+ import { useEffect as useEffect2, useReducer } from "react";
1049
+ import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
1050
+ var elapsed = (run, now) => run.banked + (run.startedAt === undefined ? 0 : now - run.startedAt);
1051
+ function toggled(run, now) {
1052
+ return run.startedAt === undefined ? { ...run, startedAt: now } : { banked: elapsed(run, now) };
1053
+ }
1054
+ var runs = new Map;
1055
+ var runOf = (id) => runs.get(id) ?? { banked: 0 };
1056
+ var slotId = (page, slot, kind) => `${kind}|${page}|${slot.kind}|${"index" in slot ? slot.index : 0}`;
1057
+ var ended = new Set;
1058
+ var timerEnded = defineTrigger({
1059
+ id: "timer-ended",
1060
+ name: "When a timer ends",
1061
+ description: "Fires when any Basics timer reaches zero.",
1062
+ subscribe: ({ fire }) => {
1063
+ const listener = (event) => fire(event);
1064
+ ended.add(listener);
1065
+ return () => ended.delete(listener);
1066
+ }
1067
+ });
1068
+ function Countdown(props) {
1069
+ const { remaining, total, running, label, accent, wide } = props;
1070
+ const done = remaining <= 0;
1071
+ const now = useNow(done ? 500 : 60000);
1072
+ const flash = done && now.getTime() % 1000 < 500;
1073
+ const background = flash ? THEME.danger : props.pressed ? THEME.faint : props.background;
1074
+ const caption = done ? "Done" : running ? label : remaining < total ? "Paused" : label;
1075
+ const time = formatDuration(remaining);
1076
+ const color = done ? "#ffffff" : running ? THEME.text : THEME.muted;
1077
+ if (wide) {
1078
+ return /* @__PURE__ */ jsxs2("div", {
1079
+ style: { ...column, background, padding: "0 16px", gap: 6, fontWeight: 700 },
1080
+ children: [
1081
+ /* @__PURE__ */ jsxs2("div", {
1082
+ style: {
1083
+ display: "flex",
1084
+ width: "100%",
1085
+ justifyContent: "space-between",
1086
+ alignItems: "baseline"
1087
+ },
1088
+ children: [
1089
+ /* @__PURE__ */ jsx2("div", {
1090
+ style: { display: "flex", fontSize: 14, color: done ? "#ffffff" : THEME.muted },
1091
+ children: caption || "Timer"
1092
+ }),
1093
+ /* @__PURE__ */ jsx2("div", {
1094
+ style: { display: "flex", fontSize: 26, color },
1095
+ children: time
1096
+ })
1097
+ ]
1098
+ }),
1099
+ /* @__PURE__ */ jsx2("div", {
1100
+ style: {
1101
+ display: "flex",
1102
+ width: "100%",
1103
+ height: 4,
1104
+ background: THEME.faint,
1105
+ borderRadius: 2
1106
+ },
1107
+ children: /* @__PURE__ */ jsx2("div", {
1108
+ style: {
1109
+ display: "flex",
1110
+ width: `${Math.round((1 - remaining / total) * 100)}%`,
1111
+ height: 4,
1112
+ background: accent,
1113
+ borderRadius: 2
1114
+ }
1115
+ })
1116
+ })
1117
+ ]
1118
+ });
1119
+ }
1120
+ return /* @__PURE__ */ jsxs2("div", {
1121
+ style: { ...fill, background, position: "relative" },
1122
+ children: [
1123
+ /* @__PURE__ */ jsx2("img", {
1124
+ src: ring(1 - remaining / total, done ? "#ffffff" : accent, THEME.faint),
1125
+ width: 86,
1126
+ height: 86,
1127
+ alt: "",
1128
+ style: { position: "absolute", left: 5, top: 5 }
1129
+ }),
1130
+ /* @__PURE__ */ jsxs2("div", {
1131
+ style: { ...column, fontWeight: 700 },
1132
+ children: [
1133
+ /* @__PURE__ */ jsx2("div", {
1134
+ style: { display: "flex", fontSize: time.length > 5 ? 17 : 22, color },
1135
+ children: time
1136
+ }),
1137
+ caption ? /* @__PURE__ */ jsx2("div", {
1138
+ style: {
1139
+ display: "flex",
1140
+ fontSize: 10,
1141
+ color: done ? "#ffffff" : THEME.muted,
1142
+ maxWidth: 60
1143
+ },
1144
+ children: caption
1145
+ }) : null
1146
+ ]
1147
+ })
1148
+ ]
1149
+ });
1150
+ }
1151
+ var timer = defineAction({
1152
+ id: "timer",
1153
+ name: "Timer",
1154
+ description: "Counts down. Press to start or pause, hold to reset. Blinks when it ends.",
1155
+ category: "Time",
1156
+ icon: "timer",
1157
+ slots: ["key", "window"],
1158
+ settings: {
1159
+ minutes: { type: "number", label: "Minutes", default: 5, min: 0, max: 600 },
1160
+ seconds: { type: "number", label: "Seconds", default: 0, min: 0, max: 59 },
1161
+ label: { type: "text", label: "Label", placeholder: "Tea, Focus…" },
1162
+ accent: { type: "color", label: "Ring colour", default: THEME.warm },
1163
+ background: { type: "color", label: "Background", default: THEME.background }
1164
+ },
1165
+ component: ({ settings, slot, plugin }) => {
1166
+ const page = usePage();
1167
+ const id = slotId(page, slot, "timer");
1168
+ const total = Math.max(1, (settings.minutes * 60 + settings.seconds) * 1000);
1169
+ const [, redraw] = useReducer((n) => n + 1, 0);
1170
+ const pressed = useKeyPressed();
1171
+ const run = runOf(id);
1172
+ const running = run.startedAt !== undefined;
1173
+ const now = useNow(running ? 250 : 60000).getTime();
1174
+ const remaining = Math.max(0, total - elapsed(run, now));
1175
+ const finished = running && remaining <= 0;
1176
+ useEffect2(() => {
1177
+ if (!finished)
1178
+ return;
1179
+ runs.set(id, { banked: total });
1180
+ const event = { label: settings.label, seconds: total / 1000 };
1181
+ for (const listener of [...ended])
1182
+ listener(event);
1183
+ plugin.emit("timer-ended", event);
1184
+ redraw();
1185
+ }, [finished, id, total, settings.label, plugin]);
1186
+ useKeyPress(() => {
1187
+ const current = runOf(id);
1188
+ runs.set(id, elapsed(current, Date.now()) >= total ? { banked: 0, startedAt: Date.now() } : toggled(current, Date.now()));
1189
+ redraw();
1190
+ }, {
1191
+ onLongPress: () => {
1192
+ runs.delete(id);
1193
+ redraw();
1194
+ }
1195
+ });
1196
+ return /* @__PURE__ */ jsx2(Countdown, {
1197
+ remaining,
1198
+ total,
1199
+ running,
1200
+ label: settings.label,
1201
+ accent: settings.accent,
1202
+ background: settings.background,
1203
+ wide: slot.kind === "window",
1204
+ pressed
1205
+ });
1206
+ }
1207
+ });
1208
+ var stopwatch = defineAction({
1209
+ id: "stopwatch",
1210
+ name: "Stopwatch",
1211
+ description: "Counts up. Press to start or stop, hold to reset.",
1212
+ category: "Time",
1213
+ icon: "watch",
1214
+ slots: ["key", "window"],
1215
+ settings: {
1216
+ label: { type: "text", label: "Label", placeholder: "Shown under the time" },
1217
+ accent: { type: "color", label: "Colour while running", default: THEME.success },
1218
+ background: { type: "color", label: "Background", default: THEME.background }
1219
+ },
1220
+ component: ({ settings, slot }) => {
1221
+ const page = usePage();
1222
+ const id = slotId(page, slot, "stopwatch");
1223
+ const [, redraw] = useReducer((n) => n + 1, 0);
1224
+ const pressed = useKeyPressed();
1225
+ const run = runOf(id);
1226
+ const running = run.startedAt !== undefined;
1227
+ const now = useNow(running ? 100 : 60000).getTime();
1228
+ const ms = elapsed(run, now);
1229
+ useKeyPress(() => {
1230
+ runs.set(id, toggled(runOf(id), Date.now()));
1231
+ redraw();
1232
+ }, {
1233
+ onLongPress: () => {
1234
+ runs.delete(id);
1235
+ redraw();
1236
+ }
1237
+ });
1238
+ const time = formatDuration(ms, false);
1239
+ const tenths = Math.floor(ms % 1000 / 100);
1240
+ const color = running ? settings.accent : ms > 0 ? THEME.text : THEME.muted;
1241
+ const caption = settings.label || (running ? "" : ms > 0 ? "Stopped" : "Stopwatch");
1242
+ const wide = slot.kind === "window";
1243
+ return /* @__PURE__ */ jsxs2("div", {
1244
+ style: {
1245
+ ...column,
1246
+ ...wide && { flexDirection: "row", gap: 14 },
1247
+ background: pressed ? THEME.faint : settings.background,
1248
+ fontWeight: 700
1249
+ },
1250
+ children: [
1251
+ /* @__PURE__ */ jsxs2("div", {
1252
+ style: { display: "flex", alignItems: "baseline" },
1253
+ children: [
1254
+ /* @__PURE__ */ jsx2("div", {
1255
+ style: { display: "flex", fontSize: wide ? 32 : time.length > 5 ? 20 : 26, color },
1256
+ children: time
1257
+ }),
1258
+ /* @__PURE__ */ jsxs2("div", {
1259
+ style: { display: "flex", fontSize: wide ? 20 : 15, color: THEME.muted },
1260
+ children: [
1261
+ ".",
1262
+ tenths
1263
+ ]
1264
+ })
1265
+ ]
1266
+ }),
1267
+ caption ? /* @__PURE__ */ jsx2("div", {
1268
+ style: { display: "flex", fontSize: wide ? 14 : 11, color: THEME.muted },
1269
+ children: caption
1270
+ }) : null
1271
+ ]
1272
+ });
1273
+ }
1274
+ });
1275
+
1276
+ // src/index.tsx
1277
+ import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
1278
+ function iconWithCaption(options) {
1279
+ const { icon, iconColor, caption, captionColor, background } = options;
1280
+ return {
1281
+ background,
1282
+ layers: [
1283
+ iconLayer("icon", icon, {
1284
+ color: iconColor,
1285
+ size: caption ? 44 : 54,
1286
+ position: caption ? "top" : "middle"
1287
+ }),
1288
+ ...caption ? [textLayer("label", caption, { color: captionColor, size: 13, position: "bottom" })] : []
1289
+ ]
1290
+ };
1291
+ }
1292
+ var label = defineAction({
1293
+ id: "label",
1294
+ name: "Label",
1295
+ description: "Text and an icon or picture. The text can show live values: CPU {{system.cpu}}%.",
1296
+ category: "Display",
1297
+ icon: "type",
1298
+ slots: ["key", "sensor", "window"],
1299
+ settings: {
1300
+ text: { type: "text", label: "Text", default: "Hello" },
1301
+ image: { type: "image", label: "Icon or picture" },
1302
+ background: { type: "color", label: "Background", default: THEME.background },
1303
+ color: { type: "color", label: "Text colour", default: THEME.text },
1304
+ fontSize: { type: "number", label: "Text size", default: 18, min: 8, max: 60 }
1305
+ },
1306
+ run: () => {
1307
+ return;
1308
+ },
1309
+ look: (s) => {
1310
+ const layers = [];
1311
+ if (s.image) {
1312
+ layers.push({
1313
+ id: "icon",
1314
+ type: "image",
1315
+ src: s.image,
1316
+ size: s.text ? 50 : 68,
1317
+ position: s.text ? "top" : "middle",
1318
+ color: s.color
1319
+ });
1320
+ }
1321
+ if (s.text) {
1322
+ layers.push(textLayer("label", s.text, {
1323
+ color: s.color,
1324
+ size: s.image ? Math.min(s.fontSize, 14) : s.fontSize,
1325
+ position: s.image ? "bottom" : "middle"
1326
+ }));
1327
+ }
1328
+ return { background: s.background, layers };
1329
+ }
1330
+ });
1331
+ var counter = defineAction({
1332
+ id: "counter",
1333
+ name: "Counter",
1334
+ description: "Counts presses. Hold to reset. The count is saved.",
1335
+ category: "Display",
1336
+ icon: "hash",
1337
+ settings: {
1338
+ title: { type: "text", label: "Title", default: "" },
1339
+ count: { type: "number", label: "Count", default: 0 },
1340
+ step: { type: "number", label: "Step", default: 1 },
1341
+ accent: { type: "color", label: "Colour", default: THEME.accent },
1342
+ background: { type: "color", label: "Background", default: THEME.background }
1343
+ },
1344
+ component: ({ settings, setSettings }) => {
1345
+ const pressed = useKeyPressed();
1346
+ useKeyPress(() => setSettings({ count: settings.count + settings.step }), {
1347
+ onLongPress: () => setSettings({ count: 0 })
1348
+ });
1349
+ const text = String(settings.count);
1350
+ const size = text.length <= 2 ? 44 : text.length <= 4 ? 32 : 22;
1351
+ return /* @__PURE__ */ jsxs3("div", {
1352
+ style: {
1353
+ ...column,
1354
+ background: pressed ? settings.accent : settings.background,
1355
+ fontWeight: 700,
1356
+ gap: 2
1357
+ },
1358
+ children: [
1359
+ settings.title ? /* @__PURE__ */ jsx3("div", {
1360
+ style: {
1361
+ display: "flex",
1362
+ fontSize: 12,
1363
+ color: pressed ? "#ffffff" : THEME.muted,
1364
+ maxWidth: 86
1365
+ },
1366
+ children: settings.title
1367
+ }) : null,
1368
+ /* @__PURE__ */ jsx3("div", {
1369
+ style: { display: "flex", fontSize: size, color: pressed ? "#ffffff" : THEME.text },
1370
+ children: text
1371
+ }),
1372
+ /* @__PURE__ */ jsx3("div", {
1373
+ style: {
1374
+ display: "flex",
1375
+ width: 26,
1376
+ height: 3,
1377
+ borderRadius: 2,
1378
+ background: pressed ? "#ffffff" : settings.accent,
1379
+ marginTop: 2
1380
+ }
1381
+ })
1382
+ ]
1383
+ });
1384
+ }
1385
+ });
1386
+ var NAVIGATE_ICONS = {
1387
+ page: "lucide/folder-open",
1388
+ back: "lucide/arrow-left",
1389
+ forward: "lucide/arrow-right",
1390
+ next: "lucide/chevron-right",
1391
+ previous: "lucide/chevron-left",
1392
+ home: "lucide/house",
1393
+ favorite: "lucide/star"
1394
+ };
1395
+ var targets = {
1396
+ back: "Back",
1397
+ forward: "Forward",
1398
+ next: "Next",
1399
+ previous: "Prev",
1400
+ home: "Home",
1401
+ favorite: "Favorites"
1402
+ };
1403
+ var navigate = defineAction({
1404
+ id: "navigate",
1405
+ name: "Navigate",
1406
+ description: "Go to a page, back, forward, or to the next or previous page.",
1407
+ category: "Navigation",
1408
+ icon: "move-right",
1409
+ slots: ["key", "sensor"],
1410
+ settings: {
1411
+ to: {
1412
+ type: "select",
1413
+ label: "Go to",
1414
+ default: "page",
1415
+ options: [
1416
+ { value: "page", label: "A page" },
1417
+ { value: "back", label: "Back (history)" },
1418
+ { value: "forward", label: "Forward (history)" },
1419
+ { value: "next", label: "Next page" },
1420
+ { value: "previous", label: "Previous page" },
1421
+ { value: "home", label: "First page" },
1422
+ { value: "favorite", label: "Next favorite page" }
1423
+ ]
1424
+ },
1425
+ page: { type: "page", label: "Page", visibleIf: { to: "page" } },
1426
+ wrap: {
1427
+ type: "boolean",
1428
+ label: "Wrap around",
1429
+ description: "After the last page comes the first.",
1430
+ visibleIf: { to: ["next", "previous"] }
1431
+ },
1432
+ text: { type: "text", label: "Text", placeholder: "Defaults to the target" },
1433
+ background: { type: "color", label: "Background", default: THEME.background },
1434
+ color: { type: "color", label: "Icon colour", default: THEME.accent }
1435
+ },
1436
+ run: ({ settings, deck }) => {
1437
+ if (settings.to === "page") {
1438
+ if (!settings.page)
1439
+ throw new Error("no page chosen");
1440
+ deck.navigate("page", settings.page);
1441
+ } else
1442
+ deck.navigate(settings.to, undefined, { wrap: settings.wrap });
1443
+ return { label: settings.to === "page" ? `Go to ${settings.page}` : targets[settings.to] };
1444
+ },
1445
+ look: (s) => iconWithCaption({
1446
+ icon: NAVIGATE_ICONS[s.to],
1447
+ iconColor: s.to === "favorite" ? THEME.warm : s.color,
1448
+ caption: s.text || (s.to === "page" ? s.page : ""),
1449
+ captionColor: THEME.text,
1450
+ background: s.background
1451
+ })
1452
+ });
1453
+ var pageName = defineAction({
1454
+ id: "page-name",
1455
+ name: "Page name",
1456
+ description: "Shows which page is open.",
1457
+ category: "Navigation",
1458
+ icon: "file-text",
1459
+ slots: ["key", "sensor", "window"],
1460
+ settings: {
1461
+ color: { type: "color", label: "Text colour", default: THEME.text },
1462
+ accent: { type: "color", label: "Icon colour", default: THEME.accent },
1463
+ background: { type: "color", label: "Background", default: THEME.background },
1464
+ fontSize: { type: "number", label: "Text size", default: 20, min: 8, max: 60 }
1465
+ },
1466
+ run: () => {
1467
+ return;
1468
+ },
1469
+ look: (s) => ({
1470
+ background: s.background,
1471
+ layers: [
1472
+ iconLayer("icon", "lucide/layers", { color: s.accent, size: 30, row: "name" }),
1473
+ textLayer("label", "{{page.name}}", { color: s.color, size: s.fontSize, row: "name" })
1474
+ ]
1475
+ })
1476
+ });
1477
+ function parseLevels(list) {
1478
+ return list.split(",").map((s) => s.trim()).filter((s) => s !== "").map(Number).filter((n) => Number.isFinite(n) && n >= 0 && n <= 100);
1479
+ }
1480
+ function nextLevel(levels, current) {
1481
+ if (levels.length === 0)
1482
+ return;
1483
+ const i = levels.indexOf(current);
1484
+ return levels[(i + 1) % levels.length];
1485
+ }
1486
+ var brightness = defineAction({
1487
+ id: "brightness",
1488
+ name: "Brightness",
1489
+ description: "Set the deck's brightness, or cycle through levels.",
1490
+ category: "Deck",
1491
+ icon: "sun",
1492
+ slots: ["key", "sensor"],
1493
+ settings: {
1494
+ mode: {
1495
+ type: "select",
1496
+ label: "Mode",
1497
+ default: "cycle",
1498
+ options: [
1499
+ { value: "cycle", label: "Cycle through levels" },
1500
+ { value: "set", label: "Set a level" }
1501
+ ]
1502
+ },
1503
+ level: {
1504
+ type: "number",
1505
+ label: "Level (%)",
1506
+ default: 100,
1507
+ min: 0,
1508
+ max: 100,
1509
+ visibleIf: { mode: "set" }
1510
+ },
1511
+ levels: {
1512
+ type: "text",
1513
+ label: "Levels to cycle",
1514
+ default: "10, 40, 70, 100",
1515
+ visibleIf: { mode: "cycle" }
1516
+ },
1517
+ background: { type: "color", label: "Background", default: THEME.background }
1518
+ },
1519
+ run: async ({ settings, deck }) => {
1520
+ const before = deck.brightness();
1521
+ const next = settings.mode === "cycle" ? nextLevel(parseLevels(settings.levels), before) : settings.level;
1522
+ if (next === undefined)
1523
+ throw new Error("no valid levels to cycle through");
1524
+ await deck.setBrightness(next);
1525
+ return {
1526
+ result: next,
1527
+ label: `Brightness ${next}%`,
1528
+ undo: () => deck.setBrightness(before)
1529
+ };
1530
+ },
1531
+ look: (s) => iconWithCaption({
1532
+ icon: s.mode === "cycle" ? "lucide/sun-medium" : s.level < 50 ? "lucide/sun-dim" : "lucide/sun",
1533
+ iconColor: THEME.warm,
1534
+ caption: s.mode === "cycle" ? "" : `${s.level}%`,
1535
+ captionColor: THEME.text,
1536
+ background: s.background
1537
+ })
1538
+ });
1539
+ var src_default = definePlugin({
1540
+ id: "@sdeck/plugin-basics",
1541
+ name: "Basics",
1542
+ version: "1.0.0",
1543
+ description: "Labels, a clock, the date, timers, a counter, page navigation and brightness.",
1544
+ author: "sdeck",
1545
+ actions: [label, clock, date, timer, stopwatch, counter, navigate, pageName, brightness],
1546
+ triggers: [timerEnded]
1547
+ });
1548
+ export {
1549
+ analogFace,
1550
+ src_default as default,
1551
+ elapsed,
1552
+ formatDuration,
1553
+ nextLevel,
1554
+ parseLevels,
1555
+ timeParts,
1556
+ toggled
1557
+ };
1558
+
1559
+ //# debugId=D0258EC14311275064756E2164756E21