@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/src/index.tsx ADDED
@@ -0,0 +1,407 @@
1
+ /**
2
+ * veadotube: avatar states, push-to-talk, and the websocket nodes of the full program, for
3
+ * veadotube mini and veadotube.
4
+ */
5
+ import { defineAction, definePlugin, defineTrigger, type StateDef, useImage } from "@sdeck/plugin";
6
+ import { iconLook } from "@sdeck/schema";
7
+ import type { Snapshot, Veado } from "./client.ts";
8
+ import { current, follow, start, test, useThumb, useVeado, withVeado } from "./connection.ts";
9
+ import { Key, useHold } from "./key.tsx";
10
+
11
+ const NETWORK = ["network"] as const;
12
+ const BACKGROUND = "#1f1a24";
13
+ const PINK = "#f472b6";
14
+ const GREEN = "#4ade80";
15
+ const GREY = "#9ca3af";
16
+
17
+ // -- Nodes --------------------------------------------------------------------------------------
18
+
19
+ const KINDS = { stateEvents: "avatar", boolean: "switch", number: "number" } as const;
20
+ type Kind = keyof typeof KINDS;
21
+
22
+ /** The node with this id, or without one the first of its kind. */
23
+ const nodeIn = (now: Snapshot | undefined, type: Kind, id = ""): string | undefined =>
24
+ now?.nodes.find((n) => n.type === type && (!id || n.id === id))?.id;
25
+
26
+ function nodeOf(veado: Veado, type: Kind, id: string): string {
27
+ const node = nodeIn(veado.snapshot(), type, id);
28
+ if (node === undefined) {
29
+ throw new Error(id ? `veadotube has no "${id}"` : `veadotube has no ${KINDS[type]} to control`);
30
+ }
31
+ return node;
32
+ }
33
+
34
+ /** Which node, for a veadotube with more than one. */
35
+ const nodeField = (source: string, label: string) =>
36
+ ({
37
+ type: "select",
38
+ label,
39
+ source,
40
+ options: [{ value: "", label: "The first one" }],
41
+ description: "veadotube mini has only one.",
42
+ }) as const;
43
+
44
+ const nodeOptions = (type: Kind) => () =>
45
+ withVeado((veado) =>
46
+ veado
47
+ .snapshot()
48
+ .nodes.filter((n) => n.type === type)
49
+ .map((n) => ({ value: n.id, label: n.name })),
50
+ );
51
+
52
+ // -- Avatar states ------------------------------------------------------------------------------
53
+
54
+ /** Goes to a state, and says how to go back. */
55
+ async function goTo(node: string, state: string) {
56
+ const set = (to: string) =>
57
+ withVeado((veado) => {
58
+ const before = veado.snapshot().current[node];
59
+ veado.send("stateEvents", node, { event: "set", state: to });
60
+ return before;
61
+ });
62
+ const before = await set(state);
63
+ return {
64
+ result: state,
65
+ label: `Avatar ${state}`,
66
+ ...(before && before !== state && { undo: () => set(before) }),
67
+ };
68
+ }
69
+
70
+ const avatarState = defineAction({
71
+ id: "state",
72
+ name: "Avatar state",
73
+ description: "Shows a state of your avatar, with its picture on the key.",
74
+ category: "veadotube",
75
+ icon: "smile",
76
+ permissions: NETWORK,
77
+ settings: {
78
+ node: nodeField("avatars", "Avatar"),
79
+ state: { type: "select", label: "State", source: "states", dependsOn: ["node"], options: [] },
80
+ mode: {
81
+ type: "select",
82
+ label: "When pressed",
83
+ default: "set",
84
+ options: [
85
+ { value: "set", label: "Switch to it" },
86
+ { value: "toggle", label: "Switch to it, or back" },
87
+ { value: "hold", label: "Show it while held" },
88
+ ],
89
+ description: "A workflow cannot hold a key, so there the last one switches to it.",
90
+ },
91
+ caption: { type: "boolean", label: "Show its name", default: true, appearance: true },
92
+ background: { type: "color", label: "Background", default: BACKGROUND, appearance: true },
93
+ },
94
+ component: ({ settings }) => {
95
+ const { state, mode, caption, background } = settings;
96
+ const now = useVeado();
97
+ const node = nodeIn(now, "stateEvents", settings.node);
98
+ const thumb = useThumb(node, state);
99
+ const icon = useImage("icon:lucide/smile", "#ffffff");
100
+ const tell = (event: string) => () =>
101
+ withVeado((veado) => {
102
+ if (!state) throw new Error("choose a state");
103
+ veado.send("stateEvents", nodeOf(veado, "stateEvents", settings.node), { event, state });
104
+ });
105
+ const hold = mode === "hold";
106
+ const failed = useHold(tell(hold ? "push" : mode), hold ? tell("pop") : undefined);
107
+ return (
108
+ <Key
109
+ image={thumb ?? icon}
110
+ size={thumb ? (caption ? 68 : 86) : 44}
111
+ caption={caption ? state || "Choose one" : ""}
112
+ color={PINK}
113
+ background={background}
114
+ on={state !== "" && node !== undefined && now?.current[node] === state}
115
+ connected={now !== undefined}
116
+ failed={failed}
117
+ />
118
+ );
119
+ },
120
+ run: async ({ settings }) => {
121
+ const { state, mode } = settings;
122
+ if (!state) throw new Error("choose a state");
123
+ const node = await withVeado((veado) => nodeOf(veado, "stateEvents", settings.node));
124
+ if (mode !== "toggle") return goTo(node, state);
125
+ const toggle = () =>
126
+ withVeado((veado) => veado.send("stateEvents", node, { event: "toggle", state }));
127
+ await toggle();
128
+ return { result: state, label: `Toggle avatar ${state}`, undo: toggle };
129
+ },
130
+ });
131
+
132
+ const WHICH_ICONS = { next: "skip-forward", previous: "skip-back", random: "shuffle" } as const;
133
+
134
+ const otherState = defineAction({
135
+ id: "other-state",
136
+ name: "Next, previous or random state",
137
+ category: "veadotube",
138
+ icon: "shuffle",
139
+ slots: ["key", "sensor"],
140
+ permissions: NETWORK,
141
+ settings: {
142
+ node: nodeField("avatars", "Avatar"),
143
+ which: {
144
+ type: "select",
145
+ label: "Switch to",
146
+ default: "next",
147
+ options: [
148
+ { value: "next", label: "The next state" },
149
+ { value: "previous", label: "The previous state" },
150
+ { value: "random", label: "A random other state" },
151
+ ],
152
+ },
153
+ },
154
+ run: async ({ settings }) => {
155
+ const { node, state } = await withVeado((veado) => {
156
+ const id = nodeOf(veado, "stateEvents", settings.node);
157
+ const now = veado.snapshot();
158
+ const states = now.states[id] ?? [];
159
+ const count = states.length;
160
+ const at = states.findIndex((s) => s.id === now.current[id]);
161
+ const steps = { next: 1, previous: -1, random: 1 + Math.floor(Math.random() * (count - 1)) };
162
+ // Without a current state, the next one is the first and the previous one the last.
163
+ const from = at < 0 && settings.which === "previous" ? 0 : at;
164
+ const next = states[(from + steps[settings.which] + count) % count];
165
+ if (!next) throw new Error("this avatar has no states");
166
+ return { node: id, state: next.id };
167
+ });
168
+ return goTo(node, state);
169
+ },
170
+ look: (s) =>
171
+ iconLook({ icon: `lucide/${WHICH_ICONS[s.which]}`, background: BACKGROUND, color: PINK }),
172
+ });
173
+
174
+ // -- Switches and numbers -----------------------------------------------------------------------
175
+
176
+ const isOn = (now: Snapshot | undefined, node: string | undefined) =>
177
+ node !== undefined && now?.switches[node] === true;
178
+
179
+ const talk = defineAction({
180
+ id: "talk",
181
+ name: "Push to talk",
182
+ description: "The microphone of veadotube mini, or any websocket switch of veadotube.",
183
+ category: "veadotube",
184
+ icon: "mic",
185
+ permissions: NETWORK,
186
+ settings: {
187
+ node: nodeField("switches", "Switch"),
188
+ mode: {
189
+ type: "select",
190
+ label: "When pressed",
191
+ default: "hold",
192
+ options: [
193
+ { value: "hold", label: "On while held" },
194
+ { value: "toggle", label: "On or off" },
195
+ { value: "on", label: "On" },
196
+ { value: "off", label: "Off" },
197
+ ],
198
+ description: "A workflow cannot hold a key, so there the first one turns it on or off.",
199
+ },
200
+ caption: { type: "text", label: "Caption", appearance: true },
201
+ background: { type: "color", label: "Background", default: BACKGROUND, appearance: true },
202
+ },
203
+ component: ({ settings }) => {
204
+ const { mode, caption, background } = settings;
205
+ const now = useVeado();
206
+ const on = isOn(now, nodeIn(now, "boolean", settings.node));
207
+ const image = useImage(`icon:lucide/${on ? "mic" : "mic-off"}`, on ? GREEN : GREY);
208
+ const tell = (payload: Record<string, unknown>) => () =>
209
+ withVeado((veado) => veado.send("boolean", nodeOf(veado, "boolean", settings.node), payload));
210
+ const failed = useHold(
211
+ tell(mode === "toggle" ? { event: "toggle" } : { event: "set", value: mode !== "off" }),
212
+ mode === "hold" ? tell({ event: "set", value: false }) : undefined,
213
+ );
214
+ return (
215
+ <Key
216
+ image={image}
217
+ size={48}
218
+ caption={caption}
219
+ color={GREEN}
220
+ background={background}
221
+ on={on}
222
+ connected={now !== undefined}
223
+ failed={failed}
224
+ />
225
+ );
226
+ },
227
+ run: ({ settings }) =>
228
+ withVeado((veado) => {
229
+ const node = nodeOf(veado, "boolean", settings.node);
230
+ const before = isOn(veado.snapshot(), node);
231
+ const value = settings.mode === "on" || (settings.mode !== "off" && !before);
232
+ veado.send("boolean", node, { event: "set", value });
233
+ return {
234
+ result: value,
235
+ label: `Push to talk ${value ? "on" : "off"}`,
236
+ ...(value !== before && {
237
+ undo: () => withVeado((v) => v.send("boolean", node, { event: "set", value: before })),
238
+ }),
239
+ };
240
+ }),
241
+ });
242
+
243
+ const changeNumber = defineAction({
244
+ id: "number",
245
+ name: "Change a number",
246
+ description: "A websocket number node of veadotube. veadotube mini has none.",
247
+ category: "veadotube",
248
+ icon: "hash",
249
+ slots: ["key", "sensor"],
250
+ permissions: NETWORK,
251
+ settings: {
252
+ node: nodeField("numbers", "Number"),
253
+ operation: {
254
+ type: "select",
255
+ label: "When pressed",
256
+ default: "add",
257
+ options: [
258
+ { value: "add", label: "Add" },
259
+ { value: "set", label: "Set to" },
260
+ ],
261
+ },
262
+ value: { type: "number", label: "Value", default: 1 },
263
+ },
264
+ run: ({ settings }) =>
265
+ withVeado((veado) => {
266
+ const node = nodeOf(veado, "number", settings.node);
267
+ const { operation, value } = settings;
268
+ const before = veado.snapshot().numbers[node];
269
+ // Setting a number forgets its range, unless that is sent along.
270
+ const set = (to: number) => {
271
+ const ranged = before?.min !== undefined || before?.max !== undefined;
272
+ return { event: "set", value: ranged ? { ...before, value: to } : to };
273
+ };
274
+ veado.send("number", node, operation === "add" ? { event: "add", value } : set(value));
275
+ return {
276
+ label: `${operation === "add" ? "Add" : "Set to"} ${value}`,
277
+ ...(before && { undo: () => withVeado((v) => v.send("number", node, set(before.value))) }),
278
+ };
279
+ }),
280
+ look: ({ operation, value }) =>
281
+ iconLook({
282
+ icon: `lucide/${operation === "set" ? "hash" : value < 0 ? "minus" : "plus"}`,
283
+ background: BACKGROUND,
284
+ color: PINK,
285
+ caption: String(operation === "set" ? value : Math.abs(value)),
286
+ }),
287
+ });
288
+
289
+ // -- Live values and triggers -------------------------------------------------------------------
290
+
291
+ const live = (
292
+ id: string,
293
+ name: string,
294
+ type: StateDef["type"],
295
+ pick: (now: Snapshot) => unknown,
296
+ ): StateDef => ({
297
+ id,
298
+ name,
299
+ type,
300
+ permissions: NETWORK,
301
+ start: (set) => {
302
+ const read = () => {
303
+ const now = current();
304
+ set(now && pick(now));
305
+ };
306
+ const stop = follow(read);
307
+ read();
308
+ return stop;
309
+ },
310
+ });
311
+
312
+ const stateChanged = defineTrigger({
313
+ id: "state-changed",
314
+ name: "When the avatar's state changes",
315
+ permissions: NETWORK,
316
+ settings: {
317
+ node: nodeField("avatars", "Avatar"),
318
+ state: {
319
+ type: "select",
320
+ label: "To",
321
+ source: "states",
322
+ dependsOn: ["node"],
323
+ options: [{ value: "", label: "Any state" }],
324
+ },
325
+ },
326
+ subscribe: ({ settings, fire }) => {
327
+ const read = () => {
328
+ const now = current();
329
+ const node = nodeIn(now, "stateEvents", settings.node);
330
+ return node === undefined ? undefined : now?.current[node];
331
+ };
332
+ let before = read();
333
+ return follow(() => {
334
+ const state = read();
335
+ const previous = before;
336
+ before = state;
337
+ // Connecting is not a change.
338
+ if (state === previous || state === undefined || previous === undefined) return;
339
+ if (!settings.state || settings.state === state) fire({ state, previous });
340
+ });
341
+ },
342
+ });
343
+
344
+ // -- Plugin -------------------------------------------------------------------------------------
345
+
346
+ export default definePlugin({
347
+ id: "@sdeck/veadotube",
348
+ name: "Veadotube",
349
+ version: "1.0.0",
350
+ namespace: "veadotube",
351
+ description:
352
+ "A collection of tools created to make live avatars more accessible to those who enjoy virtual puppetry.",
353
+ author: "ivanoliverfabra",
354
+ homepage: "https://veado.tube",
355
+ // Files, because veadotube writes down in the user's folder where it can be reached.
356
+ permissions: ["network", "filesystem"],
357
+ settings: {
358
+ address: {
359
+ type: "text",
360
+ label: "Address",
361
+ placeholder: "Found automatically",
362
+ description:
363
+ "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.",
364
+ },
365
+ },
366
+ onboarding: {
367
+ steps: [
368
+ {
369
+ id: "server",
370
+ title: "Turn on veadotube's websocket server",
371
+ body: "In veadotube mini, open the **program settings** and make sure the **websocket server** is on. In veadotube, it has its own panel.\n\nFor the **Push to talk** key, also turn on **use websocket** in veadotube mini's push-to-talk settings.",
372
+ },
373
+ {
374
+ id: "connect",
375
+ title: "Test the connection",
376
+ body: "veadotube has to be running. Its address is found automatically.",
377
+ command: "connect",
378
+ },
379
+ ],
380
+ },
381
+ commands: [{ id: "connect", name: "Test the connection", permissions: NETWORK, run: test }],
382
+ actions: [avatarState, otherState, talk, changeNumber],
383
+ triggers: [stateChanged],
384
+ optionSources: {
385
+ avatars: nodeOptions("stateEvents"),
386
+ switches: nodeOptions("boolean"),
387
+ numbers: nodeOptions("number"),
388
+ states: (_context, settings) =>
389
+ withVeado((veado) => {
390
+ const node = nodeOf(veado, "stateEvents", String(settings.node ?? ""));
391
+ return (veado.snapshot().states[node] ?? []).map((s) => ({ value: s.id, label: s.name }));
392
+ }),
393
+ },
394
+ state: [
395
+ live("connected", "Connected", "boolean", () => true),
396
+ live("state", "Avatar state", "string", (now) => now.current[nodeIn(now, "stateEvents") ?? ""]),
397
+ live("states", "Avatar states", "json", (now) =>
398
+ (now.states[nodeIn(now, "stateEvents") ?? ""] ?? []).map((s) => s.id),
399
+ ),
400
+ live("talking", "Push to talk is on", "boolean", (now) => isOn(now, nodeIn(now, "boolean"))),
401
+ live("switches", "Switches", "json", (now) => now.switches),
402
+ live("numbers", "Numbers", "json", (now) =>
403
+ Object.fromEntries(Object.entries(now.numbers).map(([id, { value }]) => [id, value])),
404
+ ),
405
+ ],
406
+ activate: start,
407
+ });
package/src/key.tsx ADDED
@@ -0,0 +1,111 @@
1
+ /** How a key looks, and what holding it does. */
2
+ import { useKeyDown, useKeyUp } from "@sdeck/plugin";
3
+ import { type CSSProperties, useEffect, useRef, useState } from "react";
4
+
5
+ type Task = () => Promise<unknown>;
6
+
7
+ /**
8
+ * Runs `down` when the key goes down and `up` when it is let go. One at a time, so that letting go
9
+ * quickly cannot overtake the press. A key that disappears while held is let go. Says for a moment
10
+ * that something failed.
11
+ */
12
+ export function useHold(down: Task, up: Task | undefined): boolean {
13
+ const [failed, setFailed] = useState(false);
14
+ const queue = useRef<Promise<unknown>>(Promise.resolve());
15
+ const release = useRef<Task | undefined>(undefined);
16
+ const run = (task: Task) => {
17
+ queue.current = queue.current.then(task).then(
18
+ () => setFailed(false),
19
+ () => setFailed(true),
20
+ );
21
+ };
22
+ useKeyDown(() => {
23
+ release.current = up;
24
+ run(down);
25
+ });
26
+ useKeyUp(() => {
27
+ const task = release.current;
28
+ release.current = undefined;
29
+ if (task) run(task);
30
+ });
31
+ useEffect(
32
+ () => () => {
33
+ const task = release.current;
34
+ release.current = undefined;
35
+ if (task) void queue.current.then(task).catch(() => {});
36
+ },
37
+ [],
38
+ );
39
+ useEffect(() => {
40
+ if (!failed) return;
41
+ const timer = setTimeout(() => setFailed(false), 1200);
42
+ return () => clearTimeout(timer);
43
+ }, [failed]);
44
+ return failed;
45
+ }
46
+
47
+ const fill: CSSProperties = {
48
+ display: "flex",
49
+ position: "absolute",
50
+ left: 0,
51
+ top: 0,
52
+ width: "100%",
53
+ height: "100%",
54
+ };
55
+
56
+ const shorten = (text: string, length: number) => {
57
+ const letters = [...text];
58
+ return letters.length > length ? `${letters.slice(0, length - 1).join("")}…` : text;
59
+ };
60
+
61
+ /** A picture with a name under it, framed while it is on and faded while there is no veadotube. */
62
+ export function Key(props: {
63
+ image: string | undefined;
64
+ size: number;
65
+ caption: string;
66
+ color: string;
67
+ background: string;
68
+ on: boolean;
69
+ connected: boolean;
70
+ failed: boolean;
71
+ }) {
72
+ const { image, size, caption, color, background, on, connected, failed } = props;
73
+ const frame = failed ? "#ef4444" : on ? color : undefined;
74
+ return (
75
+ <div style={{ ...fill, backgroundColor: background }}>
76
+ <div
77
+ style={{
78
+ ...fill,
79
+ alignItems: "center",
80
+ justifyContent: "center",
81
+ paddingBottom: caption ? 16 : 0,
82
+ opacity: connected ? 1 : 0.35,
83
+ }}
84
+ >
85
+ {image ? (
86
+ <img src={image} width={size} height={size} style={{ objectFit: "contain" }} alt="" />
87
+ ) : null}
88
+ </div>
89
+ {caption ? (
90
+ <div
91
+ style={{
92
+ display: "flex",
93
+ position: "absolute",
94
+ left: 4,
95
+ right: 4,
96
+ bottom: 6,
97
+ justifyContent: "center",
98
+ whiteSpace: "nowrap",
99
+ color: "#ffffff",
100
+ fontSize: 12,
101
+ fontWeight: 700,
102
+ lineHeight: 1.2,
103
+ }}
104
+ >
105
+ {shorten(caption, 12)}
106
+ </div>
107
+ ) : null}
108
+ {frame ? <div style={{ ...fill, border: `4px solid ${frame}` }} /> : null}
109
+ </div>
110
+ );
111
+ }