@sdeck/plugin-spotify 0.1.0 → 0.3.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 CHANGED
@@ -1,870 +1,19 @@
1
1
  // @bun
2
- // ../core/src/element.ts
3
- var runtime;
4
- function registerElementRuntime(next) {
5
- runtime = next;
6
- }
7
- // ../react/src/render.ts
8
- function isReactElement(value) {
9
- return typeof value === "object" && value !== null && "$$typeof" in value;
10
- }
11
- var defaultRenderer = {};
12
- var fontRenderers = new WeakMap;
13
- async function createRenderer(fonts) {
14
- const { Renderer } = await import("@takumi-rs/core");
15
- const renderer = new Renderer;
16
- for (const font of fonts) {
17
- await renderer.registerFont({
18
- name: font.name,
19
- data: font.data,
20
- ...font.weight !== undefined && { weight: font.weight },
21
- ...font.style !== undefined && { style: font.style }
22
- });
23
- }
24
- return renderer;
25
- }
26
- function getRenderer(fonts) {
27
- if (!fonts?.length) {
28
- defaultRenderer.current ??= createRenderer([]);
29
- defaultRenderer.current.catch(() => {
30
- defaultRenderer.current = undefined;
31
- });
32
- return defaultRenderer.current;
33
- }
34
- let renderer = fontRenderers.get(fonts);
35
- if (!renderer) {
36
- renderer = createRenderer(fonts);
37
- renderer.catch(() => fontRenderers.delete(fonts));
38
- fontRenderers.set(fonts, renderer);
39
- }
40
- return renderer;
41
- }
42
- var number = (value) => typeof value === "number" && Number.isFinite(value) ? value : undefined;
43
- function toNode(node, text = true) {
44
- if ("text" in node) {
45
- return text ? { type: "text", text: node.text } : { type: "container", children: [] };
46
- }
47
- const { style, tw, src, width, height } = node.props;
48
- const common = {
49
- ...typeof tw === "string" && { tw }
50
- };
51
- if (node.type === "img") {
52
- if (typeof src !== "string")
53
- throw new Error("<img> needs a string `src` (URL or data: URI)");
54
- return {
55
- type: "image",
56
- src,
57
- ...number(width) !== undefined && { width: number(width) },
58
- ...number(height) !== undefined && { height: number(height) },
59
- ...typeof style === "object" && style !== null && { style },
60
- ...common
61
- };
62
- }
63
- return {
64
- type: "container",
65
- style: { display: "flex", ...typeof style === "object" ? style : {} },
66
- children: node.children.filter((child) => text || !("text" in child)).map((child) => toNode(child, text)),
67
- ...common
68
- };
69
- }
70
- var reconciler;
71
- var flushing = 0;
72
- function flushAll(renderer) {
73
- flushing++;
74
- try {
75
- renderer.flushSyncWork();
76
- for (let i = 0;i < 20 && renderer.flushPassiveEffects(); i++)
77
- renderer.flushSyncWork();
78
- } finally {
79
- flushing--;
80
- }
81
- }
82
- function loadReconciler() {
83
- reconciler ??= (async () => {
84
- let factoryModule;
85
- let constants;
86
- let React;
87
- try {
88
- [factoryModule, constants, React] = await Promise.all([
89
- import("react-reconciler"),
90
- import("react-reconciler/constants.js"),
91
- import("react")
92
- ]);
93
- } catch (cause) {
94
- throw new Error("Rendering React elements requires `react` (>=19.3) to be installed", {
95
- cause
96
- });
97
- }
98
- let priority = constants.NoEventPriority;
99
- const noop = () => {};
100
- const hostConfig = {
101
- supportsMutation: true,
102
- supportsPersistence: false,
103
- supportsHydration: false,
104
- isPrimaryRenderer: true,
105
- warnsIfNotActing: false,
106
- noTimeout: -1,
107
- scheduleTimeout: setTimeout,
108
- cancelTimeout: clearTimeout,
109
- supportsMicrotasks: true,
110
- scheduleMicrotask: queueMicrotask,
111
- createInstance: (type, props) => {
112
- const { children: _children, ...rest } = props;
113
- return { type, props: rest, children: [] };
114
- },
115
- createTextInstance: (text) => ({ text }),
116
- shouldSetTextContent: () => false,
117
- appendInitialChild: (parent, child) => parent.children.push(child),
118
- appendChild: (parent, child) => parent.children.push(child),
119
- appendChildToContainer: (container, child) => container.children.push(child),
120
- insertBefore: (parent, child, before) => {
121
- const children = parent.children;
122
- const existing = children.indexOf(child);
123
- if (existing !== -1)
124
- children.splice(existing, 1);
125
- children.splice(children.indexOf(before), 0, child);
126
- },
127
- insertInContainerBefore: (container, child, before) => {
128
- const children = container.children;
129
- const existing = children.indexOf(child);
130
- if (existing !== -1)
131
- children.splice(existing, 1);
132
- children.splice(children.indexOf(before), 0, child);
133
- },
134
- removeChild: (parent, child) => {
135
- parent.children.splice(parent.children.indexOf(child), 1);
136
- },
137
- removeChildFromContainer: (container, child) => {
138
- container.children.splice(container.children.indexOf(child), 1);
139
- },
140
- clearContainer: (container) => {
141
- container.children = [];
142
- },
143
- commitUpdate: (instance, _type, _prev, next) => {
144
- const { children: _children, ...rest } = next;
145
- instance.props = rest;
146
- },
147
- commitTextUpdate: (text, _old, next) => {
148
- text.text = next;
149
- },
150
- finalizeInitialChildren: () => false,
151
- getPublicInstance: (instance) => instance,
152
- getRootHostContext: () => ({}),
153
- getChildHostContext: (parent) => parent,
154
- prepareForCommit: () => null,
155
- resetAfterCommit: (container) => container.onCommit(),
156
- preparePortalMount: noop,
157
- detachDeletedInstance: noop,
158
- hideInstance: noop,
159
- unhideInstance: noop,
160
- hideTextInstance: noop,
161
- unhideTextInstance: noop,
162
- getInstanceFromNode: () => null,
163
- beforeActiveInstanceBlur: noop,
164
- afterActiveInstanceBlur: noop,
165
- prepareScopeUpdate: noop,
166
- getInstanceFromScope: () => null,
167
- bindToConsole: (method, args) => console[method]?.bind(console, ...args) ?? noop,
168
- extraDevToolsConfig: null,
169
- rendererVersion: "0.0.0",
170
- rendererPackageName: "sdeck",
171
- getCurrentUpdatePriority: () => priority,
172
- setCurrentUpdatePriority: (next) => {
173
- priority = next;
174
- },
175
- resolveUpdatePriority: () => priority !== constants.NoEventPriority ? priority : flushing > 0 ? constants.DiscreteEventPriority : constants.DefaultEventPriority,
176
- resolveEventType: () => null,
177
- resolveEventTimeStamp: () => -1.1,
178
- shouldAttemptEagerTransition: () => false,
179
- trackSchedulerEvent: noop,
180
- requestPostPaintCallback: noop,
181
- maySuspendCommit: () => false,
182
- preloadInstance: () => true,
183
- startSuspendingCommit: noop,
184
- suspendInstance: noop,
185
- waitForCommitToBeReady: () => null,
186
- getSuspendedCommitReason: () => null,
187
- NotPendingTransition: null,
188
- HostTransitionContext: React.createContext(null),
189
- resetFormInstance: noop
190
- };
191
- const factory = factoryModule.default ?? factoryModule;
192
- return factory(hostConfig);
193
- })();
194
- reconciler.catch(() => {
195
- reconciler = undefined;
196
- });
197
- return reconciler;
198
- }
199
- function noopIndicator() {}
200
- async function createReactRoot(size, onFrame, options = {}) {
201
- const [takumi, renderer] = await Promise.all([getRenderer(options.fonts), loadReconciler()]);
202
- let dirty = false;
203
- let drawing;
204
- let lastTree;
205
- let unmounted = false;
206
- let renderError;
207
- let initial = true;
208
- const fail = (error) => {
209
- if (initial)
210
- renderError ??= { error };
211
- else
212
- (options.onError ?? ((e) => console.error("sdeck: React render failed:", e)))(error);
213
- };
214
- async function draw() {
215
- await Promise.resolve();
216
- while (dirty && !unmounted) {
217
- dirty = false;
218
- try {
219
- const [root] = container.children;
220
- if (!root)
221
- continue;
222
- const tree = toNode(root, options.text !== false);
223
- const key = JSON.stringify(tree);
224
- if (key === lastTree)
225
- continue;
226
- lastTree = key;
227
- const pixels = await takumi.render(tree, {
228
- width: size.width,
229
- height: size.height,
230
- format: "raw",
231
- ...options.scale !== undefined && { devicePixelRatio: options.scale }
232
- });
233
- await onFrame({
234
- data: new Uint8Array(pixels.buffer, pixels.byteOffset, pixels.byteLength),
235
- width: size.width,
236
- height: size.height,
237
- channels: 4
238
- });
239
- } catch (error) {
240
- lastTree = undefined;
241
- fail(error);
242
- }
243
- }
244
- drawing = undefined;
245
- }
246
- const container = {
247
- children: [],
248
- onCommit() {
249
- dirty = true;
250
- drawing ??= draw();
251
- }
252
- };
253
- const onError = (error) => fail(error);
254
- const onCaughtError = () => {};
255
- const root = renderer.createContainer(container, 1, null, false, null, "", onError, onCaughtError, onError, noopIndicator, null);
256
- const flush = () => flushAll(renderer);
257
- const handle = {
258
- render(element) {
259
- if (unmounted)
260
- throw new Error("This React root was unmounted");
261
- renderer.updateContainerSync(element, root, null, null);
262
- flush();
263
- },
264
- async idle() {
265
- while (drawing)
266
- await drawing;
267
- if (initial && renderError) {
268
- const { error } = renderError;
269
- renderError = undefined;
270
- throw error;
271
- }
272
- initial = false;
273
- },
274
- async unmount() {
275
- if (unmounted)
276
- return;
277
- renderer.updateContainerSync(null, root, null, null);
278
- flush();
279
- unmounted = true;
280
- await drawing;
281
- }
282
- };
283
- return handle;
284
- }
285
- async function renderReact(element, size, fonts, scale) {
286
- let frame;
287
- const root = await createReactRoot(size, (next) => {
288
- frame = next;
289
- }, { ...fonts && { fonts }, ...scale !== undefined && { scale } });
290
- try {
291
- root.render(element);
292
- await root.idle();
293
- } finally {
294
- await root.unmount();
295
- }
296
- if (!frame)
297
- throw new Error("React element rendered nothing");
298
- return frame;
299
- }
300
- registerElementRuntime({
301
- matches: isReactElement,
302
- render: (element, size, options) => renderReact(element, size, options?.fonts),
303
- createRoot: (size, onFrame, options) => createReactRoot(size, onFrame, options)
304
- });
305
- // ../app/src/app.tsx
306
- import { Fragment, useSyncExternalStore } from "react";
307
-
308
- // ../app/src/context.ts
309
- import { createContext, useContext } from "react";
310
- var DeckContext = createContext(undefined);
311
- var SlotContext = createContext(undefined);
312
- var NavigatorContext = createContext(undefined);
313
- function useDeck() {
314
- const deck = useContext(DeckContext);
315
- if (!deck)
316
- throw new Error("useDeck() must be used inside a component mounted by @sdeck/app");
317
- return deck;
318
- }
319
- function useSlot() {
320
- return useContext(SlotContext);
321
- }
322
- // ../app/src/hooks.ts
323
- import { useContext as useContext2, useEffect, useRef, useState, useSyncExternalStore as useSyncExternalStore2 } from "react";
324
-
325
- // ../app/src/swipe.ts
326
- var SWIPE_WINDOW_MS = 400;
327
-
328
- class SwipeTracker {
329
- #handlers = new Set;
330
- #stamps = new Map;
331
- #completing = new Set;
332
- #first;
333
- constructor(deck) {
334
- deck.on("sensorDown", (index) => this.#down(index));
335
- }
336
- get active() {
337
- return this.#handlers.size > 0;
338
- }
339
- stamp(index) {
340
- return this.#stamps.get(index) ?? 0;
341
- }
342
- completes(index) {
343
- return this.#completing.has(index);
344
- }
345
- listen(handler) {
346
- this.#handlers.add(handler);
347
- return () => void this.#handlers.delete(handler);
348
- }
349
- #down(index) {
350
- this.#completing.delete(index);
351
- const now = performance.now();
352
- const first = this.#first;
353
- if (!this.active || !first || first.index === index || now - first.at > SWIPE_WINDOW_MS) {
354
- this.#first = { index, at: now };
355
- return;
356
- }
357
- this.#first = undefined;
358
- this.#completing.add(index);
359
- for (const sensor of [first.index, index])
360
- this.#stamps.set(sensor, this.stamp(sensor) + 1);
361
- const direction = index > first.index ? "right" : "left";
362
- for (const handler of [...this.#handlers])
363
- handler(direction);
364
- }
365
- }
366
- var trackers = new WeakMap;
367
- function swipeTracker(deck) {
368
- let tracker = trackers.get(deck);
369
- if (!tracker) {
370
- tracker = new SwipeTracker(deck);
371
- trackers.set(deck, tracker);
372
- }
373
- return tracker;
374
- }
375
-
376
- // ../app/src/hooks.ts
377
- function useLatest(value) {
378
- const ref = useRef(value);
379
- useEffect(() => {
380
- ref.current = value;
381
- });
382
- return ref;
383
- }
384
- function useTarget(kind, explicit) {
385
- const slot = useSlot();
386
- if (explicit !== undefined)
387
- return explicit;
388
- return slot?.kind === kind ? slot.index : undefined;
389
- }
390
- function usePress(kind, onPress, gestures, explicit) {
391
- const deck = useDeck();
392
- const target = useTarget(kind, explicit);
393
- const latest = useLatest({
394
- onPress,
395
- onLongPress: gestures.onLongPress,
396
- longPressMs: gestures.longPressMs ?? 500,
397
- onDoublePress: gestures.onDoublePress ?? gestures.onDoubleTap,
398
- doublePressMs: gestures.doublePressMs ?? gestures.doubleTapMs ?? 300,
399
- onRelease: gestures.onRelease ?? false
400
- });
401
- useEffect(() => {
402
- const swipes = kind === "sensor" ? swipeTracker(deck) : undefined;
403
- const state = new Map;
404
- const held = new Set;
405
- const get = (index) => {
406
- let s = state.get(index);
407
- if (!s) {
408
- s = { longFired: false, immediate: false, downAt: 0, stamp: 0 };
409
- state.set(index, s);
410
- }
411
- return s;
412
- };
413
- const offDown = deck.on(`${kind}Down`, (index) => {
414
- if (target !== undefined && index !== target)
415
- return;
416
- if (swipes?.completes(index))
417
- return;
418
- held.add(index);
419
- const o = latest.current;
420
- const s = get(index);
421
- s.longFired = false;
422
- s.downAt = performance.now();
423
- s.stamp = swipes?.stamp(index) ?? 0;
424
- s.immediate = !o.onLongPress && !o.onDoublePress && !o.onRelease && !swipes?.active;
425
- if (s.immediate) {
426
- o.onPress?.(index);
427
- return;
428
- }
429
- if (o.onLongPress) {
430
- s.long = setTimeout(() => {
431
- if (swipes && swipes.stamp(index) !== s.stamp)
432
- return;
433
- s.longFired = true;
434
- clearTimeout(s.double);
435
- s.double = undefined;
436
- latest.current.onLongPress?.(index);
437
- }, o.longPressMs);
438
- }
439
- });
440
- const offUp = deck.on(`${kind}Up`, (index) => {
441
- if (!held.delete(index))
442
- return;
443
- const s = get(index);
444
- clearTimeout(s.long);
445
- if (s.immediate || s.longFired)
446
- return;
447
- if (!swipes?.active)
448
- return released(index, s);
449
- const wait = Math.max(0, SWIPE_WINDOW_MS - (performance.now() - s.downAt));
450
- s.deferred = setTimeout(() => {
451
- if (swipes.stamp(index) === s.stamp)
452
- released(index, s);
453
- }, wait);
454
- });
455
- function released(index, s) {
456
- const o = latest.current;
457
- if (!o.onDoublePress) {
458
- o.onPress?.(index);
459
- } else if (s.double !== undefined) {
460
- clearTimeout(s.double);
461
- s.double = undefined;
462
- o.onDoublePress(index);
463
- } else {
464
- s.double = setTimeout(() => {
465
- s.double = undefined;
466
- latest.current.onPress?.(index);
467
- }, o.doublePressMs);
468
- }
469
- }
470
- return () => {
471
- offDown();
472
- offUp();
473
- for (const s of state.values()) {
474
- clearTimeout(s.long);
475
- clearTimeout(s.double);
476
- clearTimeout(s.deferred);
477
- }
478
- };
479
- }, [deck, kind, target, latest]);
480
- }
481
- function useKeyPress(onPress, options = {}) {
482
- usePress("key", onPress, options, options.key);
483
- }
484
- function useSensorPress(onPress, options = {}) {
485
- usePress("sensor", onPress, options, options.sensor);
486
- }
487
- // ../engine/src/state.ts
488
- function sameValue(a, b) {
489
- if (Object.is(a, b))
490
- return true;
491
- if (typeof a !== "object" || typeof b !== "object" || a === null || b === null)
492
- return false;
493
- if (Array.isArray(a) !== Array.isArray(b))
494
- return false;
495
- const ka = Object.keys(a);
496
- const kb = Object.keys(b);
497
- if (ka.length !== kb.length)
498
- return false;
499
- return ka.every((k) => Object.hasOwn(b, k) && sameValue(a[k], b[k]));
500
- }
501
- // ../schema/src/layers.ts
502
- function iconLayer(id, icon, options = {}) {
503
- const { color, size = 52, position = "middle", visible, row, frame } = options;
504
- const src = /^[a-z0-9]+\/[A-Za-z0-9-]+$/.test(icon) ? `icon:${icon}` : icon;
505
- return {
506
- id,
507
- type: "image",
508
- src,
509
- size,
510
- position,
511
- ...color && { color },
512
- ...visible && { visible },
513
- ...row && { row },
514
- ...frame && { frame }
515
- };
516
- }
517
- function iconLook(options) {
518
- const { icon, background, caption = "", color = "#ffffff" } = options;
519
- return {
520
- background,
521
- layers: [
522
- iconLayer("icon", icon, {
523
- color,
524
- size: caption ? 46 : 58,
525
- position: caption ? "top" : "middle"
526
- }),
527
- ...caption ? [textLayer("label", caption, { color, size: 13, position: "bottom" })] : []
528
- ]
529
- };
530
- }
531
- function textLayer(id, text, options = {}) {
532
- const { color = "#ffffff", size = 14, weight = 700, position = "middle" } = options;
533
- const { visible, row, frame } = options;
534
- return {
535
- id,
536
- type: "text",
537
- text,
538
- color,
539
- size,
540
- weight,
541
- position,
542
- ...visible && { visible },
543
- ...row && { row },
544
- ...frame && { frame }
545
- };
546
- }
547
- // ../plugin/src/bridge.ts
2
+ // src/index.tsx
548
3
  import {
549
- createContext as createContext2,
550
- useCallback,
551
- useContext as useContext3,
552
- useEffect as useEffect2,
553
- useMemo,
554
- useRef as useRef2,
555
- useState as useState2,
556
- useSyncExternalStore as useSyncExternalStore3
557
- } from "react";
558
- var HostBridgeContext = createContext2(undefined);
559
- function useBridge() {
560
- const bridge = useContext3(HostBridgeContext);
561
- if (!bridge)
562
- throw new Error("sdeck live-state hooks must be used inside an action drawn by the host");
563
- return bridge;
564
- }
565
- function useWatched(paths, read) {
566
- const bridge = useBridge();
567
- const key = paths.join(`
568
- `);
569
- const subscribe = useCallback((listener) => bridge.watch(paths, listener), [bridge, key]);
570
- const last = useRef2(undefined);
571
- const snapshot = () => {
572
- const value = read();
573
- if (last.current && sameValue(last.current.value, value))
574
- return last.current.value;
575
- last.current = { value };
576
- return value;
577
- };
578
- return useSyncExternalStore3(subscribe, snapshot);
579
- }
580
- function useHostState(key) {
581
- const bridge = useBridge();
582
- const paths = useMemo(() => [key], [key]);
583
- return useWatched(paths, () => {
584
- const dot = key.indexOf(".");
585
- const ns = bridge.scope()[key.slice(0, dot)];
586
- return dot > 0 ? ns?.[key.slice(dot + 1)] : undefined;
587
- });
588
- }
589
- function useImage(src, color) {
590
- const bridge = useBridge();
591
- return useSyncExternalStore3(bridge.watchImages, () => src ? bridge.image(src, color) : undefined);
592
- }
593
- // ../plugin/src/settings.ts
594
- function checkSchema(schema, sources = {}) {
595
- const problems = [];
596
- const types = new Set([
597
- "text",
598
- "number",
599
- "boolean",
600
- "color",
601
- "select",
602
- "page",
603
- "image",
604
- "secret"
605
- ]);
606
- for (const [key, field] of Object.entries(schema)) {
607
- if (!field || typeof field !== "object" || !types.has(field.type)) {
608
- problems.push(`setting "${key}" has an unknown type`);
609
- continue;
610
- }
611
- if (typeof field.label !== "string")
612
- problems.push(`setting "${key}" needs a label`);
613
- const source = "source" in field ? field.source : undefined;
614
- if (source !== undefined && !(source in sources)) {
615
- problems.push(`setting "${key}" uses unknown option source "${source}"`);
616
- }
617
- if (field.type === "select" && (!Array.isArray(field.options) || field.options.length === 0 && source === undefined)) {
618
- problems.push(`setting "${key}" needs at least one option or a source`);
619
- }
620
- for (const other of "dependsOn" in field && field.dependsOn || []) {
621
- if (!(other in schema))
622
- problems.push(`setting "${key}" depends on unknown "${other}"`);
623
- }
624
- if (field.visibleIf !== undefined) {
625
- for (const other of Object.keys(field.visibleIf)) {
626
- if (!(other in schema))
627
- problems.push(`setting "${key}" depends on unknown "${other}"`);
628
- }
629
- }
630
- }
631
- return problems;
632
- }
4
+ defineAction,
5
+ definePlugin,
6
+ defineTrigger,
7
+ Shared,
8
+ useKeyPress,
9
+ useSensorPress
10
+ } from "@sdeck/plugin";
11
+ import {
12
+ iconLayer,
13
+ iconLook,
14
+ textLayer
15
+ } from "@sdeck/schema";
633
16
 
634
- // ../plugin/src/plugin.ts
635
- var PERMISSIONS = [
636
- "shell",
637
- "process",
638
- "filesystem",
639
- "network",
640
- "input",
641
- "audio",
642
- "clipboard"
643
- ];
644
- var ID = /^(@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*$/;
645
- var NAMESPACE = /^[a-z][\w-]{0,31}$/;
646
- var LOCAL_ID = /^[\w.-]+$/;
647
- function defineAction(def) {
648
- return {
649
- ...def,
650
- slots: def.slots ?? ["key"],
651
- settings: def.settings ?? {}
652
- };
653
- }
654
- function defineTrigger(def) {
655
- return { ...def, settings: def.settings ?? {} };
656
- }
657
- function definePlugin(def) {
658
- const problems = checkPlugin(def);
659
- if (problems.length > 0) {
660
- throw new TypeError(`invalid plugin "${def?.id}": ${problems.join("; ")}`);
661
- }
662
- return def;
663
- }
664
- function checkLocalIds(kind, items, problems) {
665
- const seen = new Set;
666
- for (const item of items) {
667
- const name = typeof item?.id === "string" ? item.id : "?";
668
- if (typeof item?.id !== "string" || !LOCAL_ID.test(item.id)) {
669
- problems.push(`${kind} "${name}": id must be letters, digits, ".", "-" or "_"`);
670
- } else if (seen.has(item.id)) {
671
- problems.push(`${kind} "${name}" is defined twice`);
672
- }
673
- seen.add(name);
674
- }
675
- return seen;
676
- }
677
- function checkPlugin(value) {
678
- if (!value || typeof value !== "object")
679
- return ["not an object"];
680
- const def = value;
681
- const problems = [];
682
- if (typeof def.id !== "string" || !ID.test(def.id)) {
683
- problems.push("id must be a package-style name (lowercase, e.g. `my-plugin` or `@me/plugin`)");
684
- }
685
- if (typeof def.name !== "string" || def.name === "")
686
- problems.push("name is required");
687
- if (typeof def.version !== "string" || def.version === "")
688
- problems.push("version is required");
689
- if (def.namespace !== undefined && !NAMESPACE.test(def.namespace)) {
690
- problems.push("namespace must be lowercase letters, digits, - or _ (starting with a letter)");
691
- }
692
- if (def.activate !== undefined && typeof def.activate !== "function") {
693
- problems.push("activate must be a function");
694
- }
695
- if (def.permissions !== undefined) {
696
- if (!Array.isArray(def.permissions))
697
- problems.push("permissions must be an array");
698
- else
699
- for (const p of def.permissions)
700
- if (!PERMISSIONS.includes(p))
701
- problems.push(`unknown permission "${String(p)}"`);
702
- }
703
- if (def.settings !== undefined) {
704
- for (const p of checkSchema(def.settings, def.optionSources ?? {})) {
705
- problems.push(`plugin ${p}`);
706
- }
707
- }
708
- if (def.commands !== undefined) {
709
- if (!Array.isArray(def.commands))
710
- problems.push("commands must be an array");
711
- else {
712
- checkLocalIds("command", def.commands, problems);
713
- for (const c of def.commands) {
714
- const name = typeof c?.id === "string" ? c.id : "?";
715
- if (typeof c?.name !== "string")
716
- problems.push(`command "${name}": name is required`);
717
- if (typeof c?.run !== "function")
718
- problems.push(`command "${name}": run is required`);
719
- }
720
- }
721
- }
722
- if (def.onboarding !== undefined)
723
- problems.push(...checkOnboarding(def));
724
- const sources = def.optionSources ?? {};
725
- if (typeof sources !== "object")
726
- problems.push("optionSources must be an object");
727
- else
728
- for (const [name, fn] of Object.entries(sources))
729
- if (typeof fn !== "function")
730
- problems.push(`option source "${name}" must be a function`);
731
- if (!Array.isArray(def.actions))
732
- return [...problems, "actions must be an array"];
733
- checkLocalIds("action", def.actions, problems);
734
- for (const action of def.actions) {
735
- const name = typeof action?.id === "string" ? action.id : "?";
736
- if (typeof action?.name !== "string")
737
- problems.push(`action "${name}": name is required`);
738
- const hasComponent = typeof action?.component === "function" || typeof action?.component === "object";
739
- const hasRun = typeof action?.run === "function";
740
- if (!hasComponent && !hasRun)
741
- problems.push(`action "${name}": needs run or component`);
742
- if (action?.look !== undefined && typeof action.look !== "function") {
743
- problems.push(`action "${name}": look must be a function`);
744
- }
745
- const slots = action?.slots ?? ["key"];
746
- if (!Array.isArray(slots) || slots.length === 0 || slots.some((s) => !["key", "sensor", "window"].includes(s))) {
747
- problems.push(`action "${name}": slots must list "key", "sensor" and/or "window"`);
748
- }
749
- for (const p of checkSchema(action?.settings ?? {}, sources)) {
750
- problems.push(`action "${name}": ${p}`);
751
- }
752
- for (const [key, field] of Object.entries(action?.settings ?? {})) {
753
- if (field?.type === "secret") {
754
- problems.push(`action "${name}": setting "${key}": secrets belong in the plugin settings`);
755
- }
756
- }
757
- }
758
- if (def.state !== undefined) {
759
- if (!Array.isArray(def.state))
760
- problems.push("state must be an array");
761
- else {
762
- checkLocalIds("state", def.state, problems);
763
- for (const s of def.state) {
764
- const name = typeof s?.id === "string" ? s.id : "?";
765
- if (typeof s?.name !== "string")
766
- problems.push(`state "${name}": name is required`);
767
- if (!["number", "string", "boolean", "json"].includes(s?.type)) {
768
- problems.push(`state "${name}": type must be number, string, boolean or json`);
769
- }
770
- if (s?.poll && (typeof s.poll.read !== "function" || !(s.poll.everyMs > 0))) {
771
- problems.push(`state "${name}": poll needs read() and everyMs > 0`);
772
- }
773
- if (s?.start !== undefined && typeof s.start !== "function") {
774
- problems.push(`state "${name}": start must be a function`);
775
- }
776
- }
777
- }
778
- }
779
- if (def.triggers !== undefined) {
780
- if (!Array.isArray(def.triggers))
781
- problems.push("triggers must be an array");
782
- else {
783
- checkLocalIds("trigger", def.triggers, problems);
784
- for (const t of def.triggers) {
785
- const name = typeof t?.id === "string" ? t.id : "?";
786
- if (typeof t?.name !== "string")
787
- problems.push(`trigger "${name}": name is required`);
788
- if (typeof t?.subscribe !== "function") {
789
- problems.push(`trigger "${name}": subscribe is required`);
790
- }
791
- for (const p of checkSchema(t?.settings ?? {}, sources)) {
792
- problems.push(`trigger "${name}": ${p}`);
793
- }
794
- }
795
- }
796
- }
797
- return problems;
798
- }
799
- function checkOnboarding(def) {
800
- const onboarding = def.onboarding;
801
- if (!Array.isArray(onboarding?.steps))
802
- return ["onboarding: steps must be an array"];
803
- const problems = [];
804
- checkLocalIds("onboarding step", onboarding.steps, problems);
805
- const settings = def.settings ?? {};
806
- const commands = new Set((def.commands ?? []).map((c) => c.id));
807
- for (const step of onboarding.steps) {
808
- const name = typeof step?.id === "string" ? step.id : "?";
809
- if (typeof step?.title !== "string")
810
- problems.push(`onboarding step "${name}": title is required`);
811
- for (const key of step?.settings ?? []) {
812
- if (!(key in settings))
813
- problems.push(`onboarding step "${name}": no setting "${key}"`);
814
- }
815
- if (step?.command !== undefined && !commands.has(step.command)) {
816
- problems.push(`onboarding step "${name}": no command "${step.command}"`);
817
- }
818
- if (step?.done !== undefined && typeof step.done !== "function") {
819
- problems.push(`onboarding step "${name}": done must be a function`);
820
- }
821
- }
822
- const page = onboarding.starterPage;
823
- if (page) {
824
- const actions = new Set((def.actions ?? []).map((a) => a.id));
825
- const used = [
826
- ...Object.values(page.keys ?? {}),
827
- ...Object.values(page.sensors ?? {}),
828
- ...page.window ? [page.window] : []
829
- ];
830
- for (const { action } of used) {
831
- if (!actions.has(action))
832
- problems.push(`onboarding starter page: no action "${action}"`);
833
- }
834
- }
835
- return problems;
836
- }
837
- // ../plugin/src/shared.ts
838
- class Shared {
839
- #listeners = new Set;
840
- #start;
841
- #stop;
842
- #last;
843
- constructor(start) {
844
- this.#start = start;
845
- }
846
- get last() {
847
- return this.#last?.value;
848
- }
849
- listen(listener) {
850
- this.#listeners.add(listener);
851
- if (!this.#stop) {
852
- this.#stop = this.#start((value) => {
853
- this.#last = { value };
854
- for (const l of [...this.#listeners])
855
- l(value);
856
- });
857
- }
858
- return () => {
859
- this.#listeners.delete(listener);
860
- if (this.#listeners.size === 0) {
861
- this.#stop?.();
862
- this.#stop = undefined;
863
- this.#last = undefined;
864
- }
865
- };
866
- }
867
- }
868
17
  // src/api.ts
869
18
  import { createHash, randomBytes } from "crypto";
870
19
  var SCOPES = [
@@ -897,7 +46,7 @@ class RateLimited extends Error {
897
46
  }
898
47
 
899
48
  class SignedOut extends Error {
900
- constructor(message = "Sign in to Spotify from the plugin's page") {
49
+ constructor(message = "Sign in to Spotify from the plugin's settings") {
901
50
  super(message);
902
51
  }
903
52
  }
@@ -959,7 +108,7 @@ class SpotifyClient {
959
108
  return page("sdeck is connected to Spotify. You can close this tab.");
960
109
  } catch (error) {
961
110
  close(error);
962
- return page("Signing in failed. See the plugin's page in sdeck.");
111
+ return page("Signing in failed. See the plugin's settings in sdeck.");
963
112
  }
964
113
  }
965
114
  });
@@ -1074,6 +223,9 @@ var IDLE = {
1074
223
  art: "",
1075
224
  progress: 0,
1076
225
  positionMs: 0,
226
+ position: 0,
227
+ duration: 0,
228
+ startedAt: undefined,
1077
229
  durationMs: 0,
1078
230
  volume: undefined,
1079
231
  shuffle: false,
@@ -1082,7 +234,7 @@ var IDLE = {
1082
234
  deviceId: "",
1083
235
  context: ""
1084
236
  };
1085
- function parsePlayer(body) {
237
+ function parsePlayer(body, at = Date.now()) {
1086
238
  if (typeof body !== "object" || body === null)
1087
239
  return IDLE;
1088
240
  const raw = body;
@@ -1100,6 +252,9 @@ function parsePlayer(body) {
1100
252
  art,
1101
253
  progress: duration > 0 ? Math.round(100 * position / duration) : 0,
1102
254
  positionMs: position,
255
+ position: position / 1000,
256
+ duration: duration / 1000,
257
+ startedAt: raw.is_playing && item ? Math.round(at - position) : undefined,
1103
258
  durationMs: duration,
1104
259
  volume: raw.device?.volume_percent ?? undefined,
1105
260
  shuffle: raw.shuffle_state === true,
@@ -1149,6 +304,7 @@ function parseDevices(body) {
1149
304
  }
1150
305
 
1151
306
  // src/panels.tsx
307
+ import { useHostState, useImage } from "@sdeck/plugin";
1152
308
  import { jsx, jsxs } from "react/jsx-runtime";
1153
309
  var GREEN = "#1ed760";
1154
310
  var BACKGROUND = "#121212";
@@ -1438,9 +594,14 @@ var player = new Shared((emit) => {
1438
594
  clearTimeout(timer);
1439
595
  let wait = POLL_MS;
1440
596
  try {
1441
- const next = parsePlayer(await spotify.request("GET", "/me/player"));
597
+ const asked = Date.now();
598
+ const body = await spotify.request("GET", "/me/player");
599
+ const next = parsePlayer(body, (asked + Date.now()) / 2);
1442
600
  if (!stopped)
1443
601
  emit(next);
602
+ const left = next.durationMs - next.positionMs;
603
+ if (next.playing && left > 0)
604
+ wait = Math.min(wait, left + 400);
1444
605
  context?.status("Signed in to Spotify", "ok");
1445
606
  } catch (error) {
1446
607
  if (!stopped)
@@ -1552,7 +713,7 @@ var playPause = defineAction({
1552
713
  icon: "play",
1553
714
  slots: ["key", "sensor"],
1554
715
  settings: {
1555
- cover: { type: "boolean", label: "Show the cover art", default: true }
716
+ cover: { type: "boolean", label: "Show the cover art", default: true, appearance: true }
1556
717
  },
1557
718
  run: async () => {
1558
719
  const before = (await readPlayer()).playing;
@@ -1630,6 +791,7 @@ var nowPlaying = defineAction({
1630
791
  ]
1631
792
  }
1632
793
  },
794
+ display: true,
1633
795
  run: async () => ({ result: await readPlayer() }),
1634
796
  component: ({ settings, slot, plugin }) => {
1635
797
  const act = () => {
@@ -1852,7 +1014,7 @@ var addToPlaylist = defineAction({
1852
1014
  source: "playlists",
1853
1015
  description: "Yours, and ones you collaborate on."
1854
1016
  },
1855
- text: { type: "text", label: "Text", placeholder: "Shown under the icon" }
1017
+ text: { type: "text", label: "Text", placeholder: "Shown under the icon", appearance: true }
1856
1018
  },
1857
1019
  run: async ({ settings }) => {
1858
1020
  if (!settings.playlist)
@@ -1895,7 +1057,7 @@ var play = defineAction({
1895
1057
  default: false,
1896
1058
  visibleIf: { mode: "play" }
1897
1059
  },
1898
- text: { type: "text", label: "Text", placeholder: "Shown under the icon" }
1060
+ text: { type: "text", label: "Text", placeholder: "Shown under the icon", appearance: true }
1899
1061
  },
1900
1062
  run: async ({ settings }) => {
1901
1063
  const target = spotifyUri(settings.item);
@@ -1969,7 +1131,7 @@ var device = defineAction({
1969
1131
  source: "devices",
1970
1132
  description: "Only devices with Spotify open are listed."
1971
1133
  },
1972
- text: { type: "text", label: "Text", placeholder: "Shown under the icon" }
1134
+ text: { type: "text", label: "Text", placeholder: "Shown under the icon", appearance: true }
1973
1135
  },
1974
1136
  run: async ({ settings }) => {
1975
1137
  if (!settings.device)
@@ -2008,7 +1170,7 @@ var playlistOptions = async (writable) => (await playlists()).filter((p) => !wri
2008
1170
  var src_default = definePlugin({
2009
1171
  id: "@sdeck/plugin-spotify",
2010
1172
  name: "Spotify",
2011
- version: "0.1.0",
1173
+ version: "0.3.0",
2012
1174
  namespace: "spotify",
2013
1175
  description: "Now playing, playback, Liked Songs, playlists and devices through the Spotify Web API.",
2014
1176
  author: "sdeck",
@@ -2122,6 +1284,12 @@ var src_default = definePlugin({
2122
1284
  stateOf("album", "Album", "string"),
2123
1285
  stateOf("art", "Cover art", "string"),
2124
1286
  stateOf("progress", "Progress", "number"),
1287
+ { ...stateOf("position", "Position", "number"), unit: "s" },
1288
+ { ...stateOf("duration", "Duration", "number"), unit: "s" },
1289
+ {
1290
+ ...stateOf("startedAt", "Started at", "number"),
1291
+ description: "When the track would have started to be where it is now, in ms since 1970. Only while playing: now() - spotify.startedAt is the exact position."
1292
+ },
2125
1293
  stateOf("volume", "Volume", "number"),
2126
1294
  stateOf("shuffle", "Shuffle", "boolean"),
2127
1295
  stateOf("repeat", "Repeat", "string"),
@@ -2162,4 +1330,4 @@ export {
2162
1330
  spotifyUri
2163
1331
  };
2164
1332
 
2165
- //# debugId=6E302A0FD592C41264756E2164756E21
1333
+ //# debugId=B1A1A70AF5BDAAD764756E2164756E21