From 643a7232459e756a41efbd220e74d87dd9513dfb Mon Sep 17 00:00:00 2001 From: bubulux Date: Wed, 25 Nov 2026 15:36:47 +0100 Subject: [PATCH] Flows on the device: a native editor that works offline (#426) - packages/ext-flows: the editing rules both editors follow (edit.ts: add a track, a keyframe, a marker; move, remove; change the length), with tests. - Phone and tablet: the project's flows kept on the device (store.ts); changes kept at once and sent under the edit lock while online, freely offline; a flow changed elsewhere meanwhile gets the device's version beside it as a copy. The native editor (Editor, Lanes, Inspect): ruler, marker strip, lanes with zoom, Select/Insert, keyframes tapped and dragged, sheets for keyframes, fades, markers and tracks, add a track, the flow's settings; Play and Live through this device's own connections. The web view and the Studio's flow embed are gone. Co-Authored-By: Claude Opus 5.5 --- apps/mobile/src/api.ts | 10 +- apps/mobile/src/ext/flows/store.ts | 106 ++++++++++++ apps/mobile/src/ext/flows/ui/Editor.tsx | 189 ++++++++++++++++++++++ apps/mobile/src/ext/flows/ui/FlowsApp.tsx | 107 ++++-------- apps/mobile/src/ext/flows/ui/Inspect.tsx | 179 ++++++++++++++++++++ apps/mobile/src/ext/flows/ui/Lanes.tsx | 169 +++++++++++++++++++ apps/studio/src/ext/flows/FlowsApp.tsx | 11 +- apps/studio/src/ext/flows/embed.tsx | 17 -- apps/studio/src/ext/flows/flows.css | 1 - apps/studio/src/ext/flows/index.ts | 7 +- docs/features/flows.md | 8 +- docs/known-issues.md | 3 +- packages/ext-flows/src/edit.test.ts | 52 ++++++ packages/ext-flows/src/edit.ts | 74 +++++++++ packages/ext-flows/src/index.ts | 1 + 15 files changed, 819 insertions(+), 115 deletions(-) create mode 100644 apps/mobile/src/ext/flows/store.ts create mode 100644 apps/mobile/src/ext/flows/ui/Editor.tsx create mode 100644 apps/mobile/src/ext/flows/ui/Inspect.tsx create mode 100644 apps/mobile/src/ext/flows/ui/Lanes.tsx delete mode 100644 apps/studio/src/ext/flows/embed.tsx create mode 100644 packages/ext-flows/src/edit.test.ts create mode 100644 packages/ext-flows/src/edit.ts diff --git a/apps/mobile/src/api.ts b/apps/mobile/src/api.ts index 25d965c..41a0ef1 100644 --- a/apps/mobile/src/api.ts +++ b/apps/mobile/src/api.ts @@ -31,13 +31,13 @@ const WEB_PAGE = "the server answered with a web page (a Wi-Fi login?)"; export const canCall = () => isConfigured && !isOfflineMode() && !!getToken(); /** One request; `body` is sent as JSON. */ -export async function call(path: string, init: { method?: string; body?: unknown } = {}): Promise { +export async function call(path: string, init: { method?: string; body?: unknown; headers?: Record } = {}): Promise { if (!isConfigured) throw new ApiError(0, "API not configured in this build"); if (isOfflineMode()) throw new ApiError(0, "offline mode is on"); if (!getToken()) throw new ApiError(401, "not signed in"); const started = Date.now(); const method = init.method ?? "GET"; - const headers = authHeaders(init.body === undefined ? {} : { "content-type": "application/json" }); + const headers = authHeaders({ ...(init.body === undefined ? {} : { "content-type": "application/json" }), ...init.headers }); let res: Response; try { res = await fetch(`${API_URL}${path}`, { method, headers, body: init.body === undefined ? undefined : JSON.stringify(init.body) }); @@ -130,6 +130,12 @@ export async function listFiles(root: Root, q: { type?: string; container?: stri export const getFile = (id: string) => call<{ file: FileRec }>(`/api/files/${id}`).then((r) => r.file); export const putFile = (id: string, f: Partial> & { type: string; refs?: { kind: string; to: string; data?: Record | null }[] } & ({ project_id: string } | { home: true })) => call<{ file: FileRec }>(`/api/files/${id}`, { method: "PUT", body: f }).then((r) => r.file); +/** A save under an edit lock this client holds (docs/api.md, "the edit lock"): the holder goes along. */ +export const putLockedFile = (id: string, holder: string, f: Parameters[1]) => + call<{ file: FileRec }>(`/api/files/${id}`, { method: "PUT", body: f, headers: { "x-lock-holder": holder } }).then((r) => r.file); +/** Take or renew a lockable file's edit lock (it holds 60 s); 423 with the lock when someone else holds it. */ +export const lockFile = (id: string, holder: string) => call<{ lock: { by: string | null; until: string } }>(`/api/files/${id}/lock`, { method: "POST", body: { holder } }).then((r) => r.lock); +export const unlockFile = (id: string, holder: string) => call(`/api/files/${id}/lock?holder=${encodeURIComponent(holder)}`, { method: "DELETE" }); export const moveFiles = (ids: string[], container: string | null) => call("/api/files/move", { method: "POST", body: { ids, container } }); /** Property values of one file (null removes one) → the file's values after. */ export const putValues = (id: string, values: Record) => call<{ values: Record }>(`/api/files/${id}/properties`, { method: "PUT", body: { values } }).then((r) => r.values); diff --git a/apps/mobile/src/ext/flows/store.ts b/apps/mobile/src/ext/flows/store.ts new file mode 100644 index 0000000..7d5afe1 --- /dev/null +++ b/apps/mobile/src/ext/flows/store.ts @@ -0,0 +1,106 @@ +import { randomUUID } from "expo-crypto"; +import { emptyFlow, flowError, type FlowBody } from "@openclapper/ext-flows"; +import { ApiError, canCall, getFile, isRejection, listFiles, putFile, putLockedFile, type FileRec } from "../../api"; +import { log } from "../../log"; +import { persisted } from "../../store"; +import { onSync } from "../../sync"; +import { toast } from "../../ui"; + +/** + * The project's flows on this device (docs/features/flows.md, "On the device"; #426): kept here so a flow opens, + * changes and plays without a connection, as on set. An edit is saved here first and sent when the server answers: + * under the edit lock while the editor holds it, else as a save of the version it started from. When the server's + * flow changed meanwhile (the Studio edited it), or it is gone, the edit is saved as a copy beside it: nothing made + * on the device is lost, nothing made elsewhere is overwritten. + */ +export interface LocalFlow { id: string; projectId: string; name: string; body: FlowBody; /** The server's version; null: not on the server yet. */ updatedAt: string | null } +interface Pending { id: string; projectId: string; name: string; body: FlowBody; /** The server version the edit started from; null: new here. */ base: string | null; rev: number; holder?: string; error?: string } + +const isList = (v: unknown) => Array.isArray(v); +const isMap = (v: unknown) => typeof v === "object" && v !== null && !Array.isArray(v); +const kept = persisted("flows.v1", [], isList); +const pending = persisted>("flowEdits.v1", {}, isMap); +let rev = 0; + +const fromFile = (f: FileRec, projectId: string): LocalFlow => ({ id: f.id, projectId, name: f.name, body: { ...emptyFlow(), ...(f.body as Partial) }, updatedAt: f.updated_at }); +const upsert = (list: LocalFlow[], f: LocalFlow) => [...list.filter((x) => x.id !== f.id), f]; + +/** The server's flows of a project, kept for offline use (the device's unsent edits stay on top of them). */ +export async function loadFlows(projectId: string): Promise { + if (!canCall()) return; + try { + const files = await listFiles({ project_id: projectId }, { type: "flow", body: true }); + kept.set((all) => [...all.filter((x) => x.projectId !== projectId), ...files.map((f) => fromFile(f, projectId))]); + } catch (e) { log("info", "flows not loaded", { error: e }); } +} + +/** A project's flows as this device has them: its own edits over the server's copies, by name. */ +export function useFlows(projectId: string | undefined): LocalFlow[] { + const all = kept.use(), edits = pending.use(); + if (!projectId) return []; + const mine = all.filter((x) => x.projectId === projectId).map((x) => (edits[x.id] ? { ...x, name: edits[x.id].name, body: edits[x.id].body } : x)); + const fresh = Object.values(edits).filter((p) => p.projectId === projectId && !all.some((x) => x.id === p.id)).map((p): LocalFlow => ({ id: p.id, projectId, name: p.name, body: p.body, updatedAt: null })); + return [...mine, ...fresh].sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true })); +} +export const hasUnsent = (id: string) => !!pending.get()[id]; +export const usePendingOf = (id: string): Pending | undefined => pending.use()[id]; + +/** A change to a flow, kept here at once and sent soon; `holder`: the editor holds the edit lock. */ +export function saveFlow(f: { id: string; projectId: string; name: string; body: FlowBody }, holder?: string) { + const was = pending.get()[f.id]; + const base = was ? was.base : kept.get().find((x) => x.id === f.id)?.updatedAt ?? null; + pending.set((all) => ({ ...all, [f.id]: { ...f, base, rev: ++rev, holder } })); + schedule(); +} + +/** A new flow, made here (also offline); it goes to the server with the next send. */ +export function newFlow(projectId: string, count: number): string { + const id = randomUUID(); + saveFlow({ id, projectId, name: `Flow ${count + 1}`, body: emptyFlow() }); + return id; +} + +let timer: ReturnType | null = null; +function schedule() { if (timer) clearTimeout(timer); timer = setTimeout(() => { timer = null; void flushFlows(); }, 800); } + +let flushing: Promise | null = null; +/** Sends what waits, one flow at a time. A network error stops the run until the next sync. */ +export function flushFlows(): Promise { + if (flushing) return flushing; + flushing = (async () => { + for (const p of Object.values(pending.get())) { + if (!canCall()) return; + if (p.error) continue; // refused before and not edited since: shown, not retried in a loop + const bad = flowError(p.body as unknown as Record); + if (bad) { pending.set((all) => (all[p.id]?.rev === p.rev ? { ...all, [p.id]: { ...p, error: bad } } : all)); continue; } + try { + let server: FileRec | null = null; + if (p.base !== null) { try { server = await getFile(p.id); } catch (e) { if (!(e instanceof ApiError && e.status === 404)) throw e; } } + const changedElsewhere = p.base !== null && (!server || server.deleted_at !== null || server.updated_at !== p.base); + const body = p.body as unknown as Record; + if (changedElsewhere) { + // Edited in the Studio meanwhile, or deleted: this device's version goes beside it, as a copy. + const copy = randomUUID(), name = `${p.name} (from this device)`.slice(0, 120); + const f = await putFile(copy, { type: "flow", project_id: p.projectId, name, body }); + kept.set((all) => upsert(all, fromFile(f, p.projectId))); + toast(`“${p.name}” changed elsewhere while this device was editing: saved as “${name}”`, "neutral"); + } else { + const req = { type: "flow", project_id: p.projectId, name: p.name, body }; + const f = p.holder ? await putLockedFile(p.id, p.holder, req) : await putFile(p.id, req); + kept.set((all) => upsert(all, fromFile(f, p.projectId))); + // Edited again while it was on its way: that edit now starts from the version just saved. + if (pending.get()[p.id]?.rev !== p.rev) { pending.set((all) => (all[p.id] ? { ...all, [p.id]: { ...all[p.id], base: f.updated_at } } : all)); continue; } + } + pending.set((all) => { if (all[p.id]?.rev !== p.rev) return all; const { [p.id]: _sent, ...rest } = all; void _sent; return rest; }); + } catch (e) { + if (e instanceof ApiError && e.status === 423) { log("info", "flow held by someone else; kept here", { flow: p.id }); continue; } + if (!isRejection(e)) { log("info", "flows not sent", { error: e }); return; } + log("warn", "flow refused", { flow: p.id, error: e }); + pending.set((all) => (all[p.id]?.rev === p.rev ? { ...all, [p.id]: { ...p, error: (e as Error).message } } : all)); + toast(`“${p.name}” could not be saved: ${(e as Error).message}. It stays on this device.`, "danger"); + } + } + })().finally(() => { flushing = null; }); + return flushing; +} +onSync(flushFlows); diff --git a/apps/mobile/src/ext/flows/ui/Editor.tsx b/apps/mobile/src/ext/flows/ui/Editor.tsx new file mode 100644 index 0000000..e747506 --- /dev/null +++ b/apps/mobile/src/ext/flows/ui/Editor.tsx @@ -0,0 +1,189 @@ +import { useEffect, useMemo, useRef, useState } from "react"; +import { Text, View } from "react-native"; +import { randomUUID } from "expo-crypto"; +import { CATALOGUE, modelOf } from "@openclapper/ext-hardware"; +import { + addKeyframe, addMarker, addTrack, fmtSeconds, FlowPlayer, patchMarker, patchTrack, removeKeys, removeTrack, setDuration, setKeyframe, + START_KEYFRAME, type Flow, type FlowBody, type Keyframe, +} from "@openclapper/ext-flows"; +import { ApiError, canCall, lockFile, unlockFile } from "../../../api"; +import { log } from "../../../log"; +import { useBack } from "../../../shell/back"; +import { Banner, Block, Button, Header, Hint, IconButton, Input, ListRow, makeStyles, Seg, Sheet, SheetList, Slider, Toggle, type, useTheme } from "../../../ui"; +import { hub } from "../../hardware/hub"; +import { useDevices } from "../../hardware/library"; +import { proxyRunning, startProxy, useHardware } from "../../hardware/proxy"; +import { loadFlows, saveFlow, usePendingOf, type LocalFlow } from "../store"; +import { CameraKeyframe, FadeInspect, LightKeyframe, MarkerInspect, TrackInspect } from "./Inspect"; +import { Lanes, type Pick } from "./Lanes"; + +const RENEW_MS = 30_000; +const ZOOM_MAX = 32; +type Lock = { state: "mine"; holder: string } | { state: "offline" } | { state: "theirs"; by: string } | { state: "asking" }; + +/** + * A flow edited on the device itself (docs/features/flows.md, "On the device"; #426): the same tracks, keyframes, + * fades and markers as in the Studio, played on this device's own connections, without a connection to the server + * if need be. Online it holds the edit lock like the Studio (one editor at a time); offline it edits freely and the + * store sends the result later (saved beside the server's version when that changed meanwhile). + */ +export function FlowEditor({ flow, back }: { flow: LocalFlow; back: () => void }) { + const s = useStyles(); + const { c } = useTheme(); + const [body, setBody] = useState(flow.body); + const [name, setName] = useState(flow.name); + const [pick, setPick] = useState(null); + const [insert, setInsert] = useState(false); + const [zoom, setZoom] = useState(1); + const [playhead, setPlayhead] = useState(0); + const [playing, setPlaying] = useState(false); + const [live, setLive] = useState(true); + const [sheet, setSheet] = useState<"flow" | "track" | null>(null); + const [lock, setLock] = useState({ state: "asking" }); + const devices = useDevices(); + const hw = useHardware(); + const unsent = usePendingOf(flow.id); + useBack(back, true); + + // ---------- The edit lock: held while online, renewed; someone else holding it makes this read-only ---------- + const holderRef = useRef(null); + useEffect(() => { + let stop = false; + const holder = randomUUID(); + const take = async () => { + if (flow.updatedAt === null || !canCall()) { if (!stop) setLock({ state: "offline" }); return; } + try { + const l = await lockFile(flow.id, holder); + if (stop) return; + holderRef.current = holder; + void l; + setLock({ state: "mine", holder }); + } catch (e) { + if (stop) return; + // Someone else edits it: watch their saves (read again with each renewal). + if (e instanceof ApiError && e.status === 423) { holderRef.current = null; setLock({ state: "theirs", by: ((e.body as { lock?: { by?: string } } | null)?.lock?.by) ?? "Someone" }); void loadFlows(flow.projectId); } + else setLock({ state: "offline" }); + } + }; + void take(); + const h = setInterval(() => void take(), RENEW_MS); + return () => { stop = true; clearInterval(h); if (holderRef.current) void unlockFile(flow.id, holderRef.current).catch(() => undefined); }; + }, [flow.id]); + const locked = lock.state === "theirs" || lock.state === "asking"; + // Read-only, it shows the flow as its editor last saved it. + useEffect(() => { if (lock.state === "theirs") { setBody(flow.body); setName(flow.name); } }, [flow.body, flow.name, lock.state]); + + // ---------- Changes: kept at once, sent by the store ---------- + const latest = useRef({ body, name }); + latest.current = { body, name }; + const change = (fn: (b: FlowBody) => FlowBody) => { + if (locked) return; + const next = fn(latest.current.body); + setBody(next); + saveFlow({ id: flow.id, projectId: flow.projectId, name: latest.current.name, body: next }, holderRef.current ?? undefined); + }; + const rename = (n: string) => { + setName(n); + if (n.trim()) saveFlow({ id: flow.id, projectId: flow.projectId, name: n.trim(), body: latest.current.body }, holderRef.current ?? undefined); + }; + + // ---------- Playing and Live on this device's own connections ---------- + const seq = useMemo(() => ({ id: flow.id, name, updatedAt: flow.updatedAt ?? "", ...body }), [body, name]); + const seqRef = useRef(seq); + seqRef.current = seq; + const send = (id: string, cmd: Parameters[1]) => { hub.send(id, cmd).catch((e) => log("debug", "flow edit: not sent", { device: id, error: e })); }; + const player = useRef(null); + if (!player.current) { + player.current = new FlowPlayer(() => seqRef.current, send, + { now: () => Date.now(), setInterval: (fn, ms) => setInterval(fn, ms), clearInterval: (h) => clearInterval(h as ReturnType) }, + { tick: (t) => setPlayhead(t), end: (t) => { setPlaying(false); setPlayhead(t); } }); + } + useEffect(() => () => player.current?.stop(), []); + const holds = hw.running; + const play = () => { + if (!player.current) return; + if (playing) { player.current.stop(); setPlaying(false); return; } + if (!proxyRunning()) return; + player.current.play(playhead >= body.durationMs ? 0 : playhead); + setPlaying(true); + }; + // Live: while stopped, the lights show the flow at the playhead and follow every edit. + useEffect(() => { if (live && !playing && holds) player.current?.emitter.emit(seq, playhead, false, send); }, [live, playing, holds, seq, playhead]); + useEffect(() => { player.current?.emitter.reset(); }, [holds]); + + // ---------- What is chosen ---------- + const track = pick && (pick.kind === "kf" || pick.kind === "fade" || pick.kind === "track") ? body.tracks.find((t) => t.id === (pick.kind === "track" ? pick.id : pick.track)) : undefined; + const kf = pick && (pick.kind === "kf" || pick.kind === "fade") ? track?.keyframes.find((k) => k.id === pick.id) : undefined; + const marker = pick?.kind === "marker" ? body.markers?.find((m) => m.id === pick.id) : undefined; + const choose = (p: Pick) => { + setPick(p); + if (playing) return; + if (p?.kind === "kf") { const k = body.tracks.find((t) => t.id === p.track)?.keyframes.find((x) => x.id === p.id); if (k) setPlayhead(k.at); } + if (p?.kind === "marker") { const m = body.markers?.find((x) => x.id === p.id); if (m) setPlayhead(m.at); } + }; + const setKf = (k: Keyframe) => track && change((b) => setKeyframe(b, track.id, k)); + const deviceName = (id: string | null) => (id ? devices.find((d) => d.id === id)?.name ?? "Gone" : "No device"); + const camera = track ? modelOf(track.model)?.type === "camera" : false; + + const inspector = locked ? null + : kf && track && pick?.kind === "kf" ? (camera + ? { change((b) => removeKeys(b, new Set([`${track.id}/${kf.id}`]))); setPick(null); }} /> + : { change((b) => removeKeys(b, new Set([`${track.id}/${kf.id}`]))); setPick(null); }} />) + : kf && track && pick?.kind === "fade" ? { const n = { ...kf }; if (curve) n.fadeIn = curve; else delete n.fadeIn; setKf(n); }} onStepped={(st) => setKf({ ...kf, fadeStepped: st || undefined })} /> + : marker ? change((b) => patchMarker(b, marker.id, fn))} onDelete={() => { change((b) => removeKeys(b, new Set([`@m/${marker.id}`]))); setPick(null); }} /> + : track && pick?.kind === "track" ? change((b) => patchTrack(b, track.id, fn))} onDelete={() => { change((b) => removeTrack(b, track.id)); setPick(null); }} /> + : null; + const pickTitle = pick?.kind === "kf" ? `${kf?.id === START_KEYFRAME ? "Start" : "Keyframe"} · ${track?.name ?? ""}` : pick?.kind === "fade" ? `Into ${fmtSeconds(kf?.at ?? 0)} · ${track?.name ?? ""}` : pick?.kind === "marker" ? "Marker" : pick?.kind === "track" ? "Track" : ""; + + const status = lock.state === "theirs" ? `${lock.by} is editing it: read-only here` : lock.state === "offline" ? (unsent ? "Offline · changes kept here" : "Offline · editing here") : unsent ? "Saving…" : "Saved"; + return ( + +
setSheet("flow") }]} /> + + setInsert(v === "insert")} options={[{ id: "select", icon: "cursor" }, { id: "insert", icon: "plus" }]} disabled={locked} /> + setZoom((z) => Math.max(1, z / 1.5))} /> + = ZOOM_MAX} onPress={() => setZoom((z) => Math.min(ZOOM_MAX, z * 1.5))} /> + + {fmtSeconds(playhead)} + { player.current?.stop(); setPlaying(false); setPlayhead(0); }} /> + + + {lock.state === "theirs" && } + {unsent?.error && } + {!holds && Playing and Live drive the lights connected to this device: hold the connections here. : undefined, body: <>{list}{props} }]), - { id: "chosen", title: "Chosen", icon: "cursor", body: <>{hosted && props}{chosen} }, + { id: "flows", title: "Flows", icon: "timeline", actions: onNew ? : undefined, body: <>{list}{props} }, + { id: "chosen", title: "Chosen", icon: "cursor", body: chosen }, ]; return ( -
+
{f.name} {body.tracks.length} tracks diff --git a/apps/studio/src/ext/flows/embed.tsx b/apps/studio/src/ext/flows/embed.tsx deleted file mode 100644 index f658b5e..0000000 --- a/apps/studio/src/ext/flows/embed.tsx +++ /dev/null @@ -1,17 +0,0 @@ -// The flow editor alone, for the phone and tablet app's web view (docs/features/flows.md, "On the device"): -// `#/embed/flow/`. The same editor as the Studio's, without the list of flows. -import { useEffect } from "preact/hooks"; -import { Spinner } from "@openclapper/design"; -import type { FileRec } from "../../api"; -import { useRoot } from "../../files"; -import { loadProjects } from "../../projects"; -import { FlowEditor } from "./FlowsApp"; - -export function EmbedFlow({ file, projectId }: { file: FileRec; projectId: string }) { - const { files } = useRoot({ project: projectId }); - // The project's live setting and its people's names, as in the Studio. - useEffect(() => { void loadProjects(); }, []); - const current = files?.find((f) => f.id === file.id) ?? null; - if (!files || !current) return
; - return ; -} diff --git a/apps/studio/src/ext/flows/flows.css b/apps/studio/src/ext/flows/flows.css index 09ac494..bbc7891 100644 --- a/apps/studio/src/ext/flows/flows.css +++ b/apps/studio/src/ext/flows/flows.css @@ -90,5 +90,4 @@ .fl-inspect .hw-ctl--range { width: 100%; } .fl-chan { display: grid; gap: var(--space-3); } .fl-note { margin: 0; color: var(--text-secondary); font-size: var(--font-size-sm); } -.fl-standalone { height: 100vh; display: flex; flex-direction: column; background: var(--surface); } @media (max-width: 600px) { .fl-row { grid-template-columns: 150px 1fr; } .fl-lanes { padding-inline: var(--space-3); } .fl-label__kind { display: none; } } diff --git a/apps/studio/src/ext/flows/index.ts b/apps/studio/src/ext/flows/index.ts index cca7999..19422e1 100644 --- a/apps/studio/src/ext/flows/index.ts +++ b/apps/studio/src/ext/flows/index.ts @@ -1,10 +1,8 @@ -// The Flows extension in the Studio (docs/features/flows.md): its app, how its files look, its phone tab, and its -// editor for the phone and tablet app's web view. Imported only by src/extensions.ts. +// The Flows extension in the Studio (docs/features/flows.md): its app, how its files look and its phone tab (the +// device has its own native editor). Imported only by src/extensions.ts. import { registerApp } from "../../apps/registry"; import { registerPhoneTab } from "../../devices"; -import { registerEmbed } from "../../embed"; import { registerFileLook } from "../../fileKinds"; -import { EmbedFlow } from "./embed"; import { FlowsApp } from "./FlowsApp"; registerApp({ @@ -14,4 +12,3 @@ registerApp({ }); registerFileLook("flow", { glyph: "timeline", color: 3 }); registerPhoneTab({ id: "flows", label: "Flows", icon: "timeline", extension: "flows" }); -registerEmbed("flow", EmbedFlow); diff --git a/docs/features/flows.md b/docs/features/flows.md index df19dd8..a14d3c9 100644 --- a/docs/features/flows.md +++ b/docs/features/flows.md @@ -38,10 +38,12 @@ The app **Flows** (one window for the project's flows): the list of flows in a p ## On the device (phone or tablet) (`apps/mobile/src/ext/flows/`) -The app **Flows** (a tab like any other while the project has the extension on): +The app **Flows** (a tab like any other while the project has the extension on), with its own **native editor** (#426: no web view; the device that edits or runs a flow is the one connected to the lights, often without a connection to the server): -- **The project's flows** with their length, tracks and whether they loop; **New flow** (needs a connection) opens it in the editor. -- **A flow**: its tracks (model, keyframes, device, muted), **Run on the phone** (from the start, through the phone that holds the connections), and **Edit**: the Studio's flow editor in a web view (`#/embed/flow/`, the session as for the tablet canvas), the one editor for every client. It saves on its own; back closes it. +- **The project's flows** (`store.ts`): kept on the device (`flows.v1`), so they open, change and play offline. **New flow** works offline too. A row says when a change is not on the server yet; **Run** (online, saved flows) runs it on the device that holds the connections, as the Studio's Run on device. +- **Saving** (`store.ts`): every change is kept on the device at once (`flowEdits.v1`) and sent about a second later, or with the next sync. While online the editor holds the **edit lock** (renewed every 30 s) and saves under it; when someone else holds it, the flow is read-only on the device and shows their saves. Offline it edits freely. When the server's flow changed meanwhile, or was deleted, the device's version is saved **beside it as a copy** ("… (from this device)"): nothing made on the device is lost, nothing made elsewhere is overwritten. A change the server refuses stays on the device with the reason, and is tried again after the next change. +- **The editor** (`ui/Editor.tsx`, `ui/Lanes.tsx`, `ui/Inspect.tsx`; the editing rules shared with the Studio in `packages/ext-flows/src/edit.ts`): the ruler (tap: the playhead), the marker strip and one lane per track, with the track labels beside them; zoom in and out (1× to 32×, the lanes scroll sideways). **Select** or **Insert** mode: in Insert a tap on a lane adds a keyframe (with the intensity the track has there) and a tap on the strip a marker. A keyframe is tapped to choose it and dragged sideways to move it; the strip between two keyframes chooses the fade. What is chosen opens in a sheet: a light's keyframe (power, intensity, white or colour, effect, dimming curve), a camera's keyframe (the catalogue controls), the fade (jump or fade, curve, run by the light or in steps), a marker (name, where, a range), a track (name, the device it drives, muted, colour, delete). **Add a track** lists the light and camera models. The flow's name, length and loop are in its settings sheet. +- **Play and Live on this device**: the shared player through this device's own connections; **Hold the connections here** switches the proxy on when it is off. Live (on by default) shows the flow at the playhead on the lights while stopped and follows every edit; recording on a camera starts only while playing. - **The run** (`run.ts`, kept from the first app's `sequenceRun.ts`): the proxy phone fetches the named revision (asked again a few times while the server still has the previous one), plays it with the shared player through its own connections, reports its state, and keeps playing when the Studio closes. A banner shows it with **Stop**, here and in the Studio. It stops when the proxy lets go of its connections: the proxy switched off, or a pairing taking the radio. ## On the server diff --git a/docs/known-issues.md b/docs/known-issues.md index 549ba4d..4437f82 100644 --- a/docs/known-issues.md +++ b/docs/known-issues.md @@ -4,7 +4,8 @@ Things that may go wrong but are not fixed (or not verified on a device) yet. Ad | Since | Area | What can happen | Why it is left | Where | | --- | --- | --- | --- | --- | -| 2026-11-25 (#382) | Flows | The Flows app on the phone (the list, running a flow on the phone, the editor in the web view) and the flow editor on a touch screen never ran on a device; the run reuses the first app's runner and player, the web view the tablet canvas's way. In the Studio, playing (not only Live and running), the box selection, markers, reordering tracks and their heights were not clicked through. A camera track sends each control as a whole command: a white balance and a tint on the same keyframe go as two writes, the second one starting from the camera's defaults for the other value. Flows of the first app (light sequences) are not carried over. | Owner tries the flows on the phone, tablet and Studio with real devices. | `apps/studio/src/ext/flows/`, `apps/mobile/src/ext/flows/`, `packages/ext-flows/` | +| 2026-11-25 (#426) | Flows · device | The native Flows editor on the phone and tablet (lanes, keyframe drag, the inspectors, the offline store with the copy-on-conflict rule, the edit lock, Play and Live through this device's connections) was typechecked and its editing rules tested (`edit.test.ts`), but never ran on a device. Not handled: two devices editing the same flow offline both end up as copies beside it; a keyframe drag on a very long flow at 1× moves in coarse steps (zoom in first); the marker strip shows only markers across the whole flow, not a track's own. | Owner tries it on a phone and a tablet with lights, online and in flight mode. | `apps/mobile/src/ext/flows/`, `packages/ext-flows/src/edit.ts` | +| 2026-11-25 (#382) | Flows | The Flows app on the phone (the list, running a flow on the phone) and the flow editor on a touch screen never ran on a device; the run reuses the first app's runner and player, the web view the tablet canvas's way. In the Studio, playing (not only Live and running), the box selection, markers, reordering tracks and their heights were not clicked through. A camera track sends each control as a whole command: a white balance and a tint on the same keyframe go as two writes, the second one starting from the camera's defaults for the other value. Flows of the first app (light sequences) are not carried over. | Owner tries the flows on the phone, tablet and Studio with real devices. | `apps/studio/src/ext/flows/`, `apps/mobile/src/ext/flows/`, `packages/ext-flows/` | | 2026-11-24 (#381) | Phone · hardware | The Hardware extension on the phone (the proxy on the `hardware` channel, pairing and mesh provisioning on the new device files, the key backup on the new routes, the Hardware app, the device screen drawn from the catalogue, the transmitter's picture, the camera control's sheet) passed typecheck, lint and the Expo bundle but never ran on a phone with real hardware. The drivers, codecs and the mesh stack are unchanged from v0.16.0; their wiring is new. Lights paired in v0.16.0 are not carried over: an Aputure light has to be reset and paired again. | Owner tries it with a new dev client build and the lights. | `apps/mobile/src/ext/hardware/` | | 2026-11-24 (#381) | Hardware · proxy | Two phones with the proxy switch on both run what the Studio sends (the Studio shows the last that reported). Only one phone may send in a mesh network (its holder), so the other's Aputure commands are refused there; NEEWER lights accept a connection from one phone at a time. A battery moved to the bin leaves its light pointing at it (shown as on a socket). Removing a device does not take an Aputure light out of the mesh: it keeps the keys until it is reset on the light. | One proxy at a time is how it is used; the rest is as in v0.16.0. | `apps/mobile/src/ext/hardware/proxy.ts`, `apps/worker/src/ext/hardware/routes.ts` | | 2026-11-24 (#380) | Phone · camera | The camera on layouts (bars, every control, frames and their math, readouts, collection mode, the folder, the Studio's live preview, the camera area it reports) and Setup, Camera passed typecheck, lint and the Expo bundle but never ran on a phone. A layout previewed in an orientation the phone is not held in is drawn in that orientation without turning the screen. Collection mode and a new folder need a connection to start. | Owner tries it on the phone with a new dev client build. | `apps/mobile/src/apps/Camera.tsx`, `src/camera/`, `src/link.ts` | diff --git a/packages/ext-flows/src/edit.test.ts b/packages/ext-flows/src/edit.test.ts new file mode 100644 index 0000000..3a7f2fd --- /dev/null +++ b/packages/ext-flows/src/edit.test.ts @@ -0,0 +1,52 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { CATALOGUE } from "@openclapper/ext-hardware"; +import { addKeyframe, addMarker, addTrack, removeKeys, setDuration, setKeyframe } from "./edit.ts"; +import { START_KEYFRAME } from "./flow.ts"; +import { emptyFlow, flowError } from "./index.ts"; + +const light = CATALOGUE.find((m) => m.type === "light")!.id; +const camera = CATALOGUE.find((m) => m.type === "camera")!.id; + +test("a new track has a start keyframe and a free colour, and the body stays valid", () => { + let b = addTrack(emptyFlow(), light, "t1"); + b = addTrack(b, light, "t2"); + assert.equal(b.tracks[0].keyframes[0].id, START_KEYFRAME); + assert.notEqual(b.tracks[0].color, b.tracks[1].color); + assert.match(b.tracks[1].name, / 2$/); + assert.equal(flowError(b as unknown as Record), null); +}); + +test("a keyframe snaps, carries the intensity there, and is not added twice at one time", () => { + const b = addTrack(emptyFlow(), light, "t"); + const one = addKeyframe(b, "t", 1234, "k1"); + assert.equal(one.keyframe!.at, 1200); + assert.equal(typeof one.keyframe!.intensity, "number"); + assert.equal(addKeyframe(one.body, "t", 1190, "k2").keyframe, null); + const cam = addKeyframe(addTrack(emptyFlow(), camera, "c"), "c", 500, "k"); + assert.deepEqual(cam.keyframe!.controls, {}); +}); + +test("a keyframe moved stays off another's time; the start keyframe stays at 0 and is never removed", () => { + let b = addKeyframe(addTrack(emptyFlow(), light, "t"), "t", 1000, "a").body; + b = addKeyframe(b, "t", 2000, "b").body; + const k = b.tracks[0].keyframes.find((x) => x.id === "b")!; + assert.equal(setKeyframe(b, "t", { ...k, at: 1000 }).tracks[0].keyframes.find((x) => x.id === "b")!.at, 2000); + assert.equal(setKeyframe(b, "t", { ...k, at: 3049 }).tracks[0].keyframes.find((x) => x.id === "b")!.at, 3000); + const start = b.tracks[0].keyframes[0]; + assert.equal(setKeyframe(b, "t", { ...start, at: 900 }).tracks[0].keyframes[0].at, 0); + const gone = removeKeys(b, new Set(["t/a", `t/${START_KEYFRAME}`])); + assert.deepEqual(gone.tracks[0].keyframes.map((x) => x.id), [START_KEYFRAME, "b"]); +}); + +test("markers are named in order; a shorter flow brings keyframes and ranges in", () => { + let b = addTrack(emptyFlow(), light, "t"); + b = addMarker(b, 1000, "m1").body; + b = addMarker(b, 5000, "m2", { end: 20_000 }).body; + assert.deepEqual(b.markers!.map((m) => m.name), ["Marker 1", "Section 2"]); + b = addKeyframe(b, "t", 15_000, "k").body; + const short = setDuration(b, 10_000); + assert.equal(short.tracks[0].keyframes.length, 1); + assert.equal(short.markers![1].end, 10_000); + assert.equal(flowError(short as unknown as Record), null); +}); diff --git a/packages/ext-flows/src/edit.ts b/packages/ext-flows/src/edit.ts new file mode 100644 index 0000000..8fa13e5 --- /dev/null +++ b/packages/ext-flows/src/edit.ts @@ -0,0 +1,74 @@ +// Editing a flow (docs/features/flows.md): the changes both editors make, as pure functions on the body, so the +// Studio's and the phone's editors follow the same rules. Ids come from the caller (each client has its own UUIDs). +import { fixtureKind, modelOf } from "@openclapper/ext-hardware"; +import { sampleTrack, START_KEYFRAME, startKeyframe, TRACK_COLORS, type FlowMarker, type FlowTrack, type Keyframe } from "./flow.ts"; +import type { FlowBody } from "./index.ts"; + +/** Times snap to a tenth of a second, the player's tick. */ +export const SNAP_MS = 100; +export const snap = (ms: number) => Math.round(ms / SNAP_MS) * SNAP_MS; +export const fmtSeconds = (ms: number) => `${(ms / 1000).toFixed(1)} s`; + +/** A new track for a light or camera model: named after it, a colour no track uses yet, its start keyframe. */ +export function addTrack(b: FlowBody, modelId: string, id: string): FlowBody { + const m = modelOf(modelId); + if (!m) return b; + const n = b.tracks.filter((t) => t.model === modelId).length + 1; + const used = new Set(b.tracks.map((t) => t.color)); + const color = Array.from({ length: TRACK_COLORS }, (_, i) => i).find((i) => !used.has(i)) ?? b.tracks.length % TRACK_COLORS; + return { ...b, tracks: [...b.tracks, { id, name: `${m.model} ${n}`, model: modelId, device: null, color, keyframes: [startKeyframe(fixtureKind(modelId))] }] }; +} + +export const patchTrack = (b: FlowBody, trackId: string, fn: (t: FlowTrack) => FlowTrack): FlowBody => ({ ...b, tracks: b.tracks.map((t) => (t.id === trackId ? fn(t) : t)) }); +export const removeTrack = (b: FlowBody, trackId: string): FlowBody => ({ ...b, tracks: b.tracks.filter((t) => t.id !== trackId), markers: (b.markers ?? []).filter((m) => m.trackId !== trackId) }); + +/** + * A keyframe at a time on a track (snapped; none when one is there already): a light's carries the intensity the + * track has there, so adding one changes nothing until it is edited; a camera's sets nothing yet. + */ +export function addKeyframe(b: FlowBody, trackId: string, at: number, id: string): { body: FlowBody; keyframe: Keyframe | null } { + const tr = b.tracks.find((t) => t.id === trackId); + const t = Math.min(b.durationMs, Math.max(SNAP_MS, snap(at))); + if (!tr || tr.keyframes.some((k) => k.at === t)) return { body: b, keyframe: null }; + const camera = modelOf(tr.model)?.type === "camera"; + const k: Keyframe = camera ? { id, at: t, controls: {} } : { id, at: t, intensity: sampleTrack(tr.keyframes, t).intensity ?? 0.5 }; + return { body: patchTrack(b, trackId, (x) => ({ ...x, keyframes: [...x.keyframes, k] })), keyframe: k }; +} + +/** A keyframe replaced (the start keyframe stays at 0); its time snapped within the flow and kept off another's. */ +export function setKeyframe(b: FlowBody, trackId: string, k: Keyframe): FlowBody { + return patchTrack(b, trackId, (t) => { + const at = k.id === START_KEYFRAME ? 0 : Math.min(b.durationMs, Math.max(SNAP_MS, snap(k.at))); + if (t.keyframes.some((x) => x.id !== k.id && x.at === at)) return t; + return { ...t, keyframes: t.keyframes.map((x) => (x.id === k.id ? { ...k, at } : x)) }; + }); +} + +/** Keyframes ("track/keyframe") and markers ("@m/id") removed; a start keyframe never is. */ +export function removeKeys(b: FlowBody, keys: ReadonlySet): FlowBody { + return { + ...b, + markers: (b.markers ?? []).filter((m) => !keys.has(`@m/${m.id}`)), + tracks: b.tracks.map((t) => ({ ...t, keyframes: t.keyframes.filter((k) => k.id === START_KEYFRAME || !keys.has(`${t.id}/${k.id}`)) })), + }; +} + +/** A marker at a time (a range with `end`), across the flow or on one track; named in order. */ +export function addMarker(b: FlowBody, at: number, id: string, opts: { end?: number; trackId?: string } = {}): { body: FlowBody; marker: FlowMarker } { + const n = (b.markers ?? []).length + 1; + const from = Math.min(b.durationMs, Math.max(0, snap(at))); + const end = opts.end !== undefined && snap(opts.end) > from ? Math.min(b.durationMs, snap(opts.end)) : undefined; + const m: FlowMarker = { id, at: from, name: end !== undefined ? `Section ${n}` : `Marker ${n}`, ...(end !== undefined ? { end } : {}), ...(opts.trackId ? { trackId: opts.trackId } : {}) }; + return { body: { ...b, markers: [...(b.markers ?? []), m] }, marker: m }; +} +export const patchMarker = (b: FlowBody, id: string, fn: (m: FlowMarker) => FlowMarker): FlowBody => ({ ...b, markers: (b.markers ?? []).map((m) => (m.id === id ? fn(m) : m)) }); + +/** The flow's length changed: keyframes and markers past the end come in to it. */ +export function setDuration(b: FlowBody, ms: number): FlowBody { + const d = Math.max(1000, snap(ms)); + return { + ...b, durationMs: d, + tracks: b.tracks.map((t) => ({ ...t, keyframes: t.keyframes.filter((k) => k.at <= d) })), + markers: (b.markers ?? []).filter((m) => m.at <= d).map((m) => (m.end !== undefined && m.end > d ? { ...m, end: d } : m)), + }; +} diff --git a/packages/ext-flows/src/index.ts b/packages/ext-flows/src/index.ts index 7611d96..963f7f6 100644 --- a/packages/ext-flows/src/index.ts +++ b/packages/ext-flows/src/index.ts @@ -48,3 +48,4 @@ registerFileType(FLOW); export * from "./flow.ts"; export * from "./player.ts"; export * from "./protocol.ts"; +export * from "./edit.ts";