@sdeck/veadotube 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,747 @@
1
+ // @bun
2
+ // src/index.tsx
3
+ import { defineAction, definePlugin, defineTrigger, useImage } from "@sdeck/plugin";
4
+ import { iconLook } from "@sdeck/schema";
5
+
6
+ // src/connection.ts
7
+ import { ManagedConnection, PermanentError as PermanentError2 } from "@sdeck/plugin";
8
+ import { useEffect, useSyncExternalStore } from "react";
9
+
10
+ // src/client.ts
11
+ import { readdir, readFile } from "fs/promises";
12
+ import { homedir } from "os";
13
+ import { join } from "path";
14
+ import { PermanentError } from "@sdeck/plugin";
15
+ var FRESH_SECONDS = 10;
16
+ async function findAddress(dir = join(homedir(), ".veadotube", "instances"), now = Date.now() / 1000) {
17
+ let files = [];
18
+ try {
19
+ files = await readdir(dir);
20
+ } catch (error) {
21
+ if (error.code !== "ENOENT")
22
+ throw error;
23
+ }
24
+ let running = false;
25
+ const started = (name) => name.split("-")[1] ?? "";
26
+ for (const file of files.sort((a, b) => started(a).localeCompare(started(b)))) {
27
+ let instance;
28
+ try {
29
+ instance = JSON.parse(await readFile(join(dir, file), "utf8"));
30
+ } catch {
31
+ continue;
32
+ }
33
+ if (!(Math.abs(now - Number(instance?.time)) <= FRESH_SECONDS))
34
+ continue;
35
+ running = true;
36
+ if (instance.server)
37
+ return instance.server;
38
+ }
39
+ throw new Error(running ? "veadotube's websocket server is off; turn it on in its program settings" : "veadotube is not running");
40
+ }
41
+ function socketUrl(address) {
42
+ const url = URL.parse(`ws://${address.trim().replace(/^\w+:\/\//, "")}`);
43
+ if (!url?.port)
44
+ throw new PermanentError(`"${address}" is not an address like localhost:1234`);
45
+ return `ws://${url.host}/?n=sdeck`;
46
+ }
47
+ var EMPTY = {
48
+ app: "veadotube",
49
+ nodes: [],
50
+ states: {},
51
+ current: {},
52
+ switches: {},
53
+ numbers: {},
54
+ thumbs: {}
55
+ };
56
+ var record = (value) => typeof value === "object" && value !== null ? value : {};
57
+ var keyOf = (type, id) => `${type} ${id}`;
58
+ var VALUES_MS = 400;
59
+ function connectVeado(url, onChange, lost, signal) {
60
+ return new Promise((resolve, reject) => {
61
+ const socket = new WebSocket(url);
62
+ let snapshot = EMPTY;
63
+ let ready = false;
64
+ let closed = false;
65
+ let failure;
66
+ let waiting;
67
+ let grace;
68
+ const asked = new Set;
69
+ const say = (message) => socket.send(`nodes:${JSON.stringify(message)}`);
70
+ const send = (type, id, payload) => {
71
+ if (socket.readyState !== WebSocket.OPEN)
72
+ throw new Error("veadotube is not connected");
73
+ say({ event: "payload", type, id, payload });
74
+ };
75
+ const update = (patch) => {
76
+ snapshot = { ...snapshot, ...patch };
77
+ if (ready && !closed)
78
+ onChange(snapshot);
79
+ };
80
+ const close = () => {
81
+ closed = true;
82
+ socket.close();
83
+ };
84
+ const timer = setTimeout(() => {
85
+ failure = new Error("veadotube did not answer");
86
+ socket.close();
87
+ }, 5000);
88
+ signal.addEventListener("abort", close, { once: true });
89
+ const veado = {
90
+ snapshot: () => snapshot,
91
+ send,
92
+ wantThumb: (node, { id, thumbHash }) => {
93
+ if (!thumbHash || asked.has(thumbHash))
94
+ return;
95
+ send("stateEvents", node, { event: "thumb", state: id });
96
+ asked.add(thumbHash);
97
+ }
98
+ };
99
+ const settle = () => {
100
+ if (ready || !waiting || waiting.size > 0)
101
+ return;
102
+ ready = true;
103
+ clearTimeout(timer);
104
+ clearTimeout(grace);
105
+ if (!closed)
106
+ onChange(snapshot);
107
+ resolve({ value: veado, close });
108
+ };
109
+ const readNodes = (entries) => {
110
+ const nodes = (Array.isArray(entries) ? entries : []).map((entry) => {
111
+ const { type, id, name } = record(entry);
112
+ return { type: String(type), id: String(id), name: String(name ?? id) };
113
+ });
114
+ const known = new Set(snapshot.nodes.map((n) => keyOf(n.type, n.id)));
115
+ const first = waiting === undefined;
116
+ waiting ??= new Set;
117
+ update({ nodes });
118
+ for (const { type, id } of nodes) {
119
+ if (known.has(keyOf(type, id)))
120
+ continue;
121
+ if (type !== "stateEvents" && type !== "boolean" && type !== "number")
122
+ continue;
123
+ if (first)
124
+ waiting.add(keyOf(type, id));
125
+ send(type, id, { event: "listen", token: "sdeck" });
126
+ if (type === "stateEvents") {
127
+ send(type, id, { event: "list" });
128
+ send(type, id, { event: "peek" });
129
+ } else
130
+ send(type, id, { event: "get" });
131
+ }
132
+ if (first) {
133
+ grace = setTimeout(() => {
134
+ waiting?.clear();
135
+ settle();
136
+ }, VALUES_MS);
137
+ }
138
+ settle();
139
+ };
140
+ const readStates = (id, data) => {
141
+ if (data.event === "list" && Array.isArray(data.states)) {
142
+ const states = data.states.map((entry) => {
143
+ const { id: state, name, thumbHash } = record(entry);
144
+ return {
145
+ id: String(state),
146
+ name: String(name ?? state),
147
+ ...typeof thumbHash === "string" && thumbHash !== "" && { thumbHash }
148
+ };
149
+ });
150
+ update({ states: { ...snapshot.states, [id]: states } });
151
+ } else if (data.event === "thumb" && typeof data.png === "string") {
152
+ const uri = `data:image/png;base64,${data.png.replace(/^data:[^,]*,/, "")}`;
153
+ update({ thumbs: { ...snapshot.thumbs, [String(data.hash)]: uri } });
154
+ } else if (data.event === "peek") {
155
+ const state = String(data.state ?? "");
156
+ update({ current: { ...snapshot.current, [id]: state } });
157
+ const states = snapshot.states[id];
158
+ if (state && states && !states.some((s) => s.id === state)) {
159
+ send("stateEvents", id, { event: "list" });
160
+ }
161
+ waiting?.delete(keyOf("stateEvents", id));
162
+ }
163
+ };
164
+ const readPayload = (type, id, payload) => {
165
+ if (type === "stateEvents")
166
+ readStates(id, record(payload));
167
+ else if (type === "boolean") {
168
+ const on = payload === true || payload === 1;
169
+ update({ switches: { ...snapshot.switches, [id]: on } });
170
+ waiting?.delete(keyOf(type, id));
171
+ } else if (type === "number") {
172
+ const { value, min, max } = record(payload);
173
+ const next = {
174
+ value: Number(value ?? 0),
175
+ ...typeof min === "number" && { min },
176
+ ...typeof max === "number" && { max }
177
+ };
178
+ update({ numbers: { ...snapshot.numbers, [id]: next } });
179
+ waiting?.delete(keyOf(type, id));
180
+ }
181
+ settle();
182
+ };
183
+ socket.onopen = () => {
184
+ say({ event: "listen", token: "sdeck" });
185
+ say({ event: "list" });
186
+ };
187
+ socket.onmessage = ({ data }) => {
188
+ if (closed || socket.readyState !== WebSocket.OPEN)
189
+ return;
190
+ const text = String(data);
191
+ const colon = text.indexOf(":");
192
+ const channel = text.slice(0, colon);
193
+ let message;
194
+ try {
195
+ message = record(JSON.parse(text.slice(colon + 1)));
196
+ } catch {
197
+ return;
198
+ }
199
+ if (channel === "instance" && typeof message.name === "string")
200
+ update({ app: message.name });
201
+ if (channel !== "nodes")
202
+ return;
203
+ if (message.event === "list")
204
+ readNodes(message.entries);
205
+ else if (message.event === "payload") {
206
+ readPayload(String(message.type), String(message.id), message.payload);
207
+ }
208
+ };
209
+ socket.onclose = () => {
210
+ clearTimeout(timer);
211
+ clearTimeout(grace);
212
+ signal.removeEventListener("abort", close);
213
+ if (!ready)
214
+ reject(failure ?? new Error(`cannot reach veadotube at ${new URL(url).host}`));
215
+ else if (!closed)
216
+ lost(new Error("veadotube closed the connection"));
217
+ };
218
+ socket.onerror = () => {};
219
+ });
220
+ }
221
+
222
+ // src/connection.ts
223
+ var context;
224
+ var snapshot;
225
+ var listeners = new Set;
226
+ function publish(next) {
227
+ if (next === snapshot)
228
+ return;
229
+ snapshot = next;
230
+ for (const listener of [...listeners])
231
+ listener();
232
+ }
233
+ var current = () => snapshot;
234
+ async function address() {
235
+ const entered = String(context?.settings().address ?? "").trim();
236
+ if (entered)
237
+ return entered;
238
+ try {
239
+ return await findAddress();
240
+ } catch (error) {
241
+ if (error.code !== "EACCES")
242
+ throw error;
243
+ throw new PermanentError2("Allow files, so veadotube can be found, or enter its address in the settings");
244
+ }
245
+ }
246
+ var connection = new ManagedConnection({
247
+ open: async (lost, signal) => {
248
+ const url = socketUrl(await address());
249
+ const link = await connectVeado(url, publish, (error) => {
250
+ publish(undefined);
251
+ lost(error);
252
+ }, signal);
253
+ return {
254
+ value: link.value,
255
+ close: () => {
256
+ link.close();
257
+ publish(undefined);
258
+ }
259
+ };
260
+ },
261
+ onStatus: (state, error) => {
262
+ if (state === "connected")
263
+ context?.status(`Connected to ${snapshot?.app}`, "ok");
264
+ else if (state === "disconnected") {
265
+ context?.status(error?.message, error instanceof PermanentError2 ? "error" : "info");
266
+ }
267
+ },
268
+ retry: { minMs: 1000, maxMs: 5000 }
269
+ });
270
+ var withVeado = (use) => connection.with(use);
271
+ function follow(listener) {
272
+ listeners.add(listener);
273
+ const release = connection.hold();
274
+ return () => {
275
+ listeners.delete(listener);
276
+ release();
277
+ };
278
+ }
279
+ var useVeado = () => useSyncExternalStore(follow, current, current);
280
+ function useThumb(node, id) {
281
+ const now = useVeado();
282
+ const state = node === undefined ? undefined : now?.states[node]?.find((s) => s.id === id);
283
+ const uri = state?.thumbHash ? now?.thumbs[state.thumbHash] : undefined;
284
+ useEffect(() => {
285
+ if (node === undefined || !state || uri)
286
+ return;
287
+ withVeado((veado) => veado.wantThumb(node, state)).catch(() => {});
288
+ }, [node, state, uri]);
289
+ return uri;
290
+ }
291
+ function start(activated) {
292
+ context = activated;
293
+ let before = activated.settings().address;
294
+ const off = activated.onSettings(() => {
295
+ const next = activated.settings().address;
296
+ if (next === before)
297
+ return;
298
+ before = next;
299
+ connection.restart();
300
+ });
301
+ return () => {
302
+ off();
303
+ connection.close();
304
+ publish(undefined);
305
+ context = undefined;
306
+ };
307
+ }
308
+ async function test() {
309
+ connection.restart();
310
+ await withVeado(() => {});
311
+ }
312
+
313
+ // src/key.tsx
314
+ import { useKeyDown, useKeyUp } from "@sdeck/plugin";
315
+ import { useEffect as useEffect2, useRef, useState } from "react";
316
+ import { jsx, jsxs } from "react/jsx-runtime";
317
+ function useHold(down, up) {
318
+ const [failed, setFailed] = useState(false);
319
+ const queue = useRef(Promise.resolve());
320
+ const release = useRef(undefined);
321
+ const run = (task) => {
322
+ queue.current = queue.current.then(task).then(() => setFailed(false), () => setFailed(true));
323
+ };
324
+ useKeyDown(() => {
325
+ release.current = up;
326
+ run(down);
327
+ });
328
+ useKeyUp(() => {
329
+ const task = release.current;
330
+ release.current = undefined;
331
+ if (task)
332
+ run(task);
333
+ });
334
+ useEffect2(() => () => {
335
+ const task = release.current;
336
+ release.current = undefined;
337
+ if (task)
338
+ queue.current.then(task).catch(() => {});
339
+ }, []);
340
+ useEffect2(() => {
341
+ if (!failed)
342
+ return;
343
+ const timer = setTimeout(() => setFailed(false), 1200);
344
+ return () => clearTimeout(timer);
345
+ }, [failed]);
346
+ return failed;
347
+ }
348
+ var fill = {
349
+ display: "flex",
350
+ position: "absolute",
351
+ left: 0,
352
+ top: 0,
353
+ width: "100%",
354
+ height: "100%"
355
+ };
356
+ var shorten = (text, length) => {
357
+ const letters = [...text];
358
+ return letters.length > length ? `${letters.slice(0, length - 1).join("")}\u2026` : text;
359
+ };
360
+ function Key(props) {
361
+ const { image, size, caption, color, background, on, connected, failed } = props;
362
+ const frame = failed ? "#ef4444" : on ? color : undefined;
363
+ return /* @__PURE__ */ jsxs("div", {
364
+ style: { ...fill, backgroundColor: background },
365
+ children: [
366
+ /* @__PURE__ */ jsx("div", {
367
+ style: {
368
+ ...fill,
369
+ alignItems: "center",
370
+ justifyContent: "center",
371
+ paddingBottom: caption ? 16 : 0,
372
+ opacity: connected ? 1 : 0.35
373
+ },
374
+ children: image ? /* @__PURE__ */ jsx("img", {
375
+ src: image,
376
+ width: size,
377
+ height: size,
378
+ style: { objectFit: "contain" },
379
+ alt: ""
380
+ }) : null
381
+ }),
382
+ caption ? /* @__PURE__ */ jsx("div", {
383
+ style: {
384
+ display: "flex",
385
+ position: "absolute",
386
+ left: 4,
387
+ right: 4,
388
+ bottom: 6,
389
+ justifyContent: "center",
390
+ whiteSpace: "nowrap",
391
+ color: "#ffffff",
392
+ fontSize: 12,
393
+ fontWeight: 700,
394
+ lineHeight: 1.2
395
+ },
396
+ children: shorten(caption, 12)
397
+ }) : null,
398
+ frame ? /* @__PURE__ */ jsx("div", {
399
+ style: { ...fill, border: `4px solid ${frame}` }
400
+ }) : null
401
+ ]
402
+ });
403
+ }
404
+
405
+ // src/index.tsx
406
+ import { jsx as jsx2 } from "react/jsx-runtime";
407
+ var NETWORK = ["network"];
408
+ var BACKGROUND = "#1f1a24";
409
+ var PINK = "#f472b6";
410
+ var GREEN = "#4ade80";
411
+ var GREY = "#9ca3af";
412
+ var KINDS = { stateEvents: "avatar", boolean: "switch", number: "number" };
413
+ var nodeIn = (now, type, id = "") => now?.nodes.find((n) => n.type === type && (!id || n.id === id))?.id;
414
+ function nodeOf(veado, type, id) {
415
+ const node = nodeIn(veado.snapshot(), type, id);
416
+ if (node === undefined) {
417
+ throw new Error(id ? `veadotube has no "${id}"` : `veadotube has no ${KINDS[type]} to control`);
418
+ }
419
+ return node;
420
+ }
421
+ var nodeField = (source, label) => ({
422
+ type: "select",
423
+ label,
424
+ source,
425
+ options: [{ value: "", label: "The first one" }],
426
+ description: "veadotube mini has only one."
427
+ });
428
+ var nodeOptions = (type) => () => withVeado((veado) => veado.snapshot().nodes.filter((n) => n.type === type).map((n) => ({ value: n.id, label: n.name })));
429
+ async function goTo(node, state) {
430
+ const set = (to) => withVeado((veado) => {
431
+ const before = veado.snapshot().current[node];
432
+ veado.send("stateEvents", node, { event: "set", state: to });
433
+ return before;
434
+ });
435
+ const before = await set(state);
436
+ return {
437
+ result: state,
438
+ label: `Avatar ${state}`,
439
+ ...before && before !== state && { undo: () => set(before) }
440
+ };
441
+ }
442
+ var avatarState = defineAction({
443
+ id: "state",
444
+ name: "Avatar state",
445
+ description: "Shows a state of your avatar, with its picture on the key.",
446
+ category: "veadotube",
447
+ icon: "smile",
448
+ permissions: NETWORK,
449
+ settings: {
450
+ node: nodeField("avatars", "Avatar"),
451
+ state: { type: "select", label: "State", source: "states", dependsOn: ["node"], options: [] },
452
+ mode: {
453
+ type: "select",
454
+ label: "When pressed",
455
+ default: "set",
456
+ options: [
457
+ { value: "set", label: "Switch to it" },
458
+ { value: "toggle", label: "Switch to it, or back" },
459
+ { value: "hold", label: "Show it while held" }
460
+ ],
461
+ description: "A workflow cannot hold a key, so there the last one switches to it."
462
+ },
463
+ caption: { type: "boolean", label: "Show its name", default: true, appearance: true },
464
+ background: { type: "color", label: "Background", default: BACKGROUND, appearance: true }
465
+ },
466
+ component: ({ settings }) => {
467
+ const { state, mode, caption, background } = settings;
468
+ const now = useVeado();
469
+ const node = nodeIn(now, "stateEvents", settings.node);
470
+ const thumb = useThumb(node, state);
471
+ const icon = useImage("icon:lucide/smile", "#ffffff");
472
+ const tell = (event) => () => withVeado((veado) => {
473
+ if (!state)
474
+ throw new Error("choose a state");
475
+ veado.send("stateEvents", nodeOf(veado, "stateEvents", settings.node), { event, state });
476
+ });
477
+ const hold = mode === "hold";
478
+ const failed = useHold(tell(hold ? "push" : mode), hold ? tell("pop") : undefined);
479
+ return /* @__PURE__ */ jsx2(Key, {
480
+ image: thumb ?? icon,
481
+ size: thumb ? caption ? 68 : 86 : 44,
482
+ caption: caption ? state || "Choose one" : "",
483
+ color: PINK,
484
+ background,
485
+ on: state !== "" && node !== undefined && now?.current[node] === state,
486
+ connected: now !== undefined,
487
+ failed
488
+ });
489
+ },
490
+ run: async ({ settings }) => {
491
+ const { state, mode } = settings;
492
+ if (!state)
493
+ throw new Error("choose a state");
494
+ const node = await withVeado((veado) => nodeOf(veado, "stateEvents", settings.node));
495
+ if (mode !== "toggle")
496
+ return goTo(node, state);
497
+ const toggle = () => withVeado((veado) => veado.send("stateEvents", node, { event: "toggle", state }));
498
+ await toggle();
499
+ return { result: state, label: `Toggle avatar ${state}`, undo: toggle };
500
+ }
501
+ });
502
+ var WHICH_ICONS = { next: "skip-forward", previous: "skip-back", random: "shuffle" };
503
+ var otherState = defineAction({
504
+ id: "other-state",
505
+ name: "Next, previous or random state",
506
+ category: "veadotube",
507
+ icon: "shuffle",
508
+ slots: ["key", "sensor"],
509
+ permissions: NETWORK,
510
+ settings: {
511
+ node: nodeField("avatars", "Avatar"),
512
+ which: {
513
+ type: "select",
514
+ label: "Switch to",
515
+ default: "next",
516
+ options: [
517
+ { value: "next", label: "The next state" },
518
+ { value: "previous", label: "The previous state" },
519
+ { value: "random", label: "A random other state" }
520
+ ]
521
+ }
522
+ },
523
+ run: async ({ settings }) => {
524
+ const { node, state } = await withVeado((veado) => {
525
+ const id = nodeOf(veado, "stateEvents", settings.node);
526
+ const now = veado.snapshot();
527
+ const states = now.states[id] ?? [];
528
+ const count = states.length;
529
+ const at = states.findIndex((s) => s.id === now.current[id]);
530
+ const steps = { next: 1, previous: -1, random: 1 + Math.floor(Math.random() * (count - 1)) };
531
+ const from = at < 0 && settings.which === "previous" ? 0 : at;
532
+ const next = states[(from + steps[settings.which] + count) % count];
533
+ if (!next)
534
+ throw new Error("this avatar has no states");
535
+ return { node: id, state: next.id };
536
+ });
537
+ return goTo(node, state);
538
+ },
539
+ look: (s) => iconLook({ icon: `lucide/${WHICH_ICONS[s.which]}`, background: BACKGROUND, color: PINK })
540
+ });
541
+ var isOn = (now, node) => node !== undefined && now?.switches[node] === true;
542
+ var talk = defineAction({
543
+ id: "talk",
544
+ name: "Push to talk",
545
+ description: "The microphone of veadotube mini, or any websocket switch of veadotube.",
546
+ category: "veadotube",
547
+ icon: "mic",
548
+ permissions: NETWORK,
549
+ settings: {
550
+ node: nodeField("switches", "Switch"),
551
+ mode: {
552
+ type: "select",
553
+ label: "When pressed",
554
+ default: "hold",
555
+ options: [
556
+ { value: "hold", label: "On while held" },
557
+ { value: "toggle", label: "On or off" },
558
+ { value: "on", label: "On" },
559
+ { value: "off", label: "Off" }
560
+ ],
561
+ description: "A workflow cannot hold a key, so there the first one turns it on or off."
562
+ },
563
+ caption: { type: "text", label: "Caption", appearance: true },
564
+ background: { type: "color", label: "Background", default: BACKGROUND, appearance: true }
565
+ },
566
+ component: ({ settings }) => {
567
+ const { mode, caption, background } = settings;
568
+ const now = useVeado();
569
+ const on = isOn(now, nodeIn(now, "boolean", settings.node));
570
+ const image = useImage(`icon:lucide/${on ? "mic" : "mic-off"}`, on ? GREEN : GREY);
571
+ const tell = (payload) => () => withVeado((veado) => veado.send("boolean", nodeOf(veado, "boolean", settings.node), payload));
572
+ const failed = useHold(tell(mode === "toggle" ? { event: "toggle" } : { event: "set", value: mode !== "off" }), mode === "hold" ? tell({ event: "set", value: false }) : undefined);
573
+ return /* @__PURE__ */ jsx2(Key, {
574
+ image,
575
+ size: 48,
576
+ caption,
577
+ color: GREEN,
578
+ background,
579
+ on,
580
+ connected: now !== undefined,
581
+ failed
582
+ });
583
+ },
584
+ run: ({ settings }) => withVeado((veado) => {
585
+ const node = nodeOf(veado, "boolean", settings.node);
586
+ const before = isOn(veado.snapshot(), node);
587
+ const value = settings.mode === "on" || settings.mode !== "off" && !before;
588
+ veado.send("boolean", node, { event: "set", value });
589
+ return {
590
+ result: value,
591
+ label: `Push to talk ${value ? "on" : "off"}`,
592
+ ...value !== before && {
593
+ undo: () => withVeado((v) => v.send("boolean", node, { event: "set", value: before }))
594
+ }
595
+ };
596
+ })
597
+ });
598
+ var changeNumber = defineAction({
599
+ id: "number",
600
+ name: "Change a number",
601
+ description: "A websocket number node of veadotube. veadotube mini has none.",
602
+ category: "veadotube",
603
+ icon: "hash",
604
+ slots: ["key", "sensor"],
605
+ permissions: NETWORK,
606
+ settings: {
607
+ node: nodeField("numbers", "Number"),
608
+ operation: {
609
+ type: "select",
610
+ label: "When pressed",
611
+ default: "add",
612
+ options: [
613
+ { value: "add", label: "Add" },
614
+ { value: "set", label: "Set to" }
615
+ ]
616
+ },
617
+ value: { type: "number", label: "Value", default: 1 }
618
+ },
619
+ run: ({ settings }) => withVeado((veado) => {
620
+ const node = nodeOf(veado, "number", settings.node);
621
+ const { operation, value } = settings;
622
+ const before = veado.snapshot().numbers[node];
623
+ const set = (to) => {
624
+ const ranged = before?.min !== undefined || before?.max !== undefined;
625
+ return { event: "set", value: ranged ? { ...before, value: to } : to };
626
+ };
627
+ veado.send("number", node, operation === "add" ? { event: "add", value } : set(value));
628
+ return {
629
+ label: `${operation === "add" ? "Add" : "Set to"} ${value}`,
630
+ ...before && { undo: () => withVeado((v) => v.send("number", node, set(before.value))) }
631
+ };
632
+ }),
633
+ look: ({ operation, value }) => iconLook({
634
+ icon: `lucide/${operation === "set" ? "hash" : value < 0 ? "minus" : "plus"}`,
635
+ background: BACKGROUND,
636
+ color: PINK,
637
+ caption: String(operation === "set" ? value : Math.abs(value))
638
+ })
639
+ });
640
+ var live = (id, name, type, pick) => ({
641
+ id,
642
+ name,
643
+ type,
644
+ permissions: NETWORK,
645
+ start: (set) => {
646
+ const read = () => {
647
+ const now = current();
648
+ set(now && pick(now));
649
+ };
650
+ const stop = follow(read);
651
+ read();
652
+ return stop;
653
+ }
654
+ });
655
+ var stateChanged = defineTrigger({
656
+ id: "state-changed",
657
+ name: "When the avatar's state changes",
658
+ permissions: NETWORK,
659
+ settings: {
660
+ node: nodeField("avatars", "Avatar"),
661
+ state: {
662
+ type: "select",
663
+ label: "To",
664
+ source: "states",
665
+ dependsOn: ["node"],
666
+ options: [{ value: "", label: "Any state" }]
667
+ }
668
+ },
669
+ subscribe: ({ settings, fire }) => {
670
+ const read = () => {
671
+ const now = current();
672
+ const node = nodeIn(now, "stateEvents", settings.node);
673
+ return node === undefined ? undefined : now?.current[node];
674
+ };
675
+ let before = read();
676
+ return follow(() => {
677
+ const state = read();
678
+ const previous = before;
679
+ before = state;
680
+ if (state === previous || state === undefined || previous === undefined)
681
+ return;
682
+ if (!settings.state || settings.state === state)
683
+ fire({ state, previous });
684
+ });
685
+ }
686
+ });
687
+ var src_default = definePlugin({
688
+ id: "@sdeck/veadotube",
689
+ name: "Veadotube",
690
+ version: "1.0.0",
691
+ namespace: "veadotube",
692
+ description: "A collection of tools created to make live avatars more accessible to those who enjoy virtual puppetry.",
693
+ author: "ivanoliverfabra",
694
+ homepage: "https://veado.tube",
695
+ permissions: ["network", "filesystem"],
696
+ settings: {
697
+ address: {
698
+ type: "text",
699
+ label: "Address",
700
+ placeholder: "Found automatically",
701
+ description: "Leave it empty to use the veadotube running here: its address changes every time it starts. Enter one, like 192.168.1.20:2424, for a fixed address or another computer."
702
+ }
703
+ },
704
+ onboarding: {
705
+ steps: [
706
+ {
707
+ id: "server",
708
+ title: "Turn on veadotube's websocket server",
709
+ body: `In veadotube mini, open the **program settings** and make sure the **websocket server** is on. In veadotube, it has its own panel.
710
+
711
+ For the **Push to talk** key, also turn on **use websocket** in veadotube mini's push-to-talk settings.`
712
+ },
713
+ {
714
+ id: "connect",
715
+ title: "Test the connection",
716
+ body: "veadotube has to be running. Its address is found automatically.",
717
+ command: "connect"
718
+ }
719
+ ]
720
+ },
721
+ commands: [{ id: "connect", name: "Test the connection", permissions: NETWORK, run: test }],
722
+ actions: [avatarState, otherState, talk, changeNumber],
723
+ triggers: [stateChanged],
724
+ optionSources: {
725
+ avatars: nodeOptions("stateEvents"),
726
+ switches: nodeOptions("boolean"),
727
+ numbers: nodeOptions("number"),
728
+ states: (_context, settings) => withVeado((veado) => {
729
+ const node = nodeOf(veado, "stateEvents", String(settings.node ?? ""));
730
+ return (veado.snapshot().states[node] ?? []).map((s) => ({ value: s.id, label: s.name }));
731
+ })
732
+ },
733
+ state: [
734
+ live("connected", "Connected", "boolean", () => true),
735
+ live("state", "Avatar state", "string", (now) => now.current[nodeIn(now, "stateEvents") ?? ""]),
736
+ live("states", "Avatar states", "json", (now) => (now.states[nodeIn(now, "stateEvents") ?? ""] ?? []).map((s) => s.id)),
737
+ live("talking", "Push to talk is on", "boolean", (now) => isOn(now, nodeIn(now, "boolean"))),
738
+ live("switches", "Switches", "json", (now) => now.switches),
739
+ live("numbers", "Numbers", "json", (now) => Object.fromEntries(Object.entries(now.numbers).map(([id, { value }]) => [id, value])))
740
+ ],
741
+ activate: start
742
+ });
743
+ export {
744
+ src_default as default
745
+ };
746
+
747
+ //# debugId=354F5D116153328A64756E2164756E21