From fc3c689b4b4f14353450c7d886d6233e6b225965 Mon Sep 17 00:00:00 2001 From: bubulux Date: Thu, 3 Dec 2026 14:01:49 +0100 Subject: [PATCH 01/11] Timeline: an empty cut takes dropped files (#550) The strip kept no track element while the cut was empty, so a drag found no place to drop. It is now a drop zone that lights up under a drag. Co-Authored-By: Claude Opus 5.5 --- apps/studio/src/apps/TimelineApp.tsx | 9 ++++++++- apps/studio/src/timeline/timeline.css | 2 ++ docs/features/timeline.md | 2 +- 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/apps/studio/src/apps/TimelineApp.tsx b/apps/studio/src/apps/TimelineApp.tsx index 8903d3af..73b4bd67 100644 --- a/apps/studio/src/apps/TimelineApp.tsx +++ b/apps/studio/src/apps/TimelineApp.tsx @@ -376,7 +376,14 @@ function Cut({ f, files, bin, projectId, active, startAt, setRoute }: { f: FileR const scrub = useTimeScrub(scale, seek); const fit = () => { const w = view.current?.clientWidth; if (w && total) setScale(Math.max(2, (w - 34) / (total / 1000))); }; const px = (ms: number) => (ms / 1000) * scale; - const strip = !blocks.length ?

Nothing in this cut yet. Drag files here from the Files panel or press a file's plus, or add a placeholder.

: ( + // An empty cut is a drop zone too: the drag measures the track, so it stays mounted (#550). + const strip = !blocks.length ? ( +
+
+

Nothing in this cut yet. Drag files here from the Files panel or press a file's plus, or add a placeholder.

+
+
+ ) : (
{ if (e.ctrlKey) { e.preventDefault(); setScale((s) => Math.min(240, Math.max(2, s * (e.deltaY < 0 ? 1.15 : 1 / 1.15)))); } }}>
diff --git a/apps/studio/src/timeline/timeline.css b/apps/studio/src/timeline/timeline.css index 2bc47450..5f39c198 100644 --- a/apps/studio/src/timeline/timeline.css +++ b/apps/studio/src/timeline/timeline.css @@ -20,6 +20,8 @@ .tl-chapters > button { position: absolute; top: 0; bottom: 0; display: flex; align-items: center; gap: 4px; padding: 0 6px; box-sizing: border-box; overflow: hidden; border: 0; border-left: 3px solid var(--c); border-radius: 3px; background: color-mix(in srgb, var(--c) 26%, var(--surface)); color: var(--text); font: var(--weight-bold) var(--font-size-2xs)/1 var(--font-sans); white-space: nowrap; cursor: pointer; } .tl-chapters > button:hover { background: color-mix(in srgb, var(--c) 42%, var(--surface)); } .tl-track { display: flex; height: 104px; } +.tl-track--empty { align-items: center; justify-content: center; margin: var(--space-3) 16px; border: 2px dashed var(--border-control); border-radius: 4px; } +.tl-track--empty.is-target { border-color: var(--accent); background: var(--selection); } .tl-clip { position: relative; flex: none; display: flex; flex-direction: column; box-sizing: border-box; border-radius: 4px; overflow: hidden; background: var(--surface-sunken); outline: var(--border-w) solid var(--border-control); outline-offset: -1px; cursor: pointer; user-select: none; touch-action: none; } .tl-clip:hover { outline-color: var(--text); } .tl-clip.is-current { outline: 2px solid var(--accent); outline-offset: -2px; z-index: 1; } diff --git a/docs/features/timeline.md b/docs/features/timeline.md index e76e8b38..837f0c0b 100644 --- a/docs/features/timeline.md +++ b/docs/features/timeline.md @@ -36,7 +36,7 @@ One window per timeline (Files: New, Timeline; a double-click on one). The U4 la - **The transport** opens the Cut's row, since it moves the playhead: to the start, previous and next clip, play and pause (on the clock; at the end it stops and goes back to the start), the time. It goes where the Cut panel goes; the keys work either way. - **The strip**: a ruler (click or drag to move the playhead; the knob scrubs), a lane of chapters (each from its marker to the next), the clips, each as wide as it lasts. Zoom with the slider or Ctrl + wheel; **Fit** shows the whole cut. A shot with a progression is **Spread** (a cell per picture; a click on a cell goes to that picture) or **Collapsed** (its first picture); its length is the progression's in both, and it has no edge to pull. Others: pull the right edge to change the time, drag to reorder. - **Choosing**: a click chooses a clip and puts the playhead at its start; Shift adds a range, Ctrl one more. With several chosen, the Clip panel sets one hold time for all, ± 0.5 s, moves them together (Alt + arrows) or removes them. -- **Files**: the project's shots, photos, canvases and collections, with a search and a type filter, as a **List** or as **Cards** (bigger pictures; remembered per browser). The panel's ⋯ menu sets how many cards go across: as many as fit (the default), one (each picture as wide as the panel) or two; also remembered per browser. In the list a collection opens to its photos and a canvas with frames to its frames; as cards a collection is one card to scrub through (as in Files), and a canvas's frames are looked through in Source. **A click looks at a file in Source** (when the pane shows; nothing else happens otherwise); **a double-click opens it in its own app** (a canvas in Canvas, a photo in Photo, a shot in Shot, a collection as its folder). Drag a row or a card into the strip (a line shows where it lands; over a **placeholder** it fills it, keeping its time and chapter), or press its plus to add it after the chosen clips. **A collection is never a clip itself: dragged in (or its plus), it puts its photos in, one clip each, in the collection's order**; it does not fill a placeholder. A new clip holds the timeline's value, else the account's ("New clips … s": "This timeline has its own value"; the account's value is the `clipHoldMs` preference, 2 s to start with). +- **Files**: the project's shots, photos, canvases and collections, with a search and a type filter, as a **List** or as **Cards** (bigger pictures; remembered per browser). The panel's ⋯ menu sets how many cards go across: as many as fit (the default), one (each picture as wide as the panel) or two; also remembered per browser. In the list a collection opens to its photos and a canvas with frames to its frames; as cards a collection is one card to scrub through (as in Files), and a canvas's frames are looked through in Source. **A click looks at a file in Source** (when the pane shows; nothing else happens otherwise); **a double-click opens it in its own app** (a canvas in Canvas, a photo in Photo, a shot in Shot, a collection as its folder). Drag a row or a card into the strip, an empty one too (a line shows where it lands; over a **placeholder** it fills it, keeping its time and chapter), or press its plus to add it after the chosen clips. **A collection is never a clip itself: dragged in (or its plus), it puts its photos in, one clip each, in the collection's order**; it does not fill a placeholder. A new clip holds the timeline's value, else the account's ("New clips … s": "This timeline has its own value"; the account's value is the `clipHoldMs` preference, 2 s to start with). - **In use**: the files this cut uses, with how often, and the placeholders; a click goes to the next clip that uses it. - **Chapters**: each with its start and length; a click goes there. "Chapter" (C) starts one at the chosen clip, or ends it; its title and colour are set in the Clip panel. - **The Clip panel**: the picture, the file's name (a placeholder's title is typed here), the hold time with ± 0.5 s (D focuses it), where it starts; a shot whose thumbnail is a progression says it plays it. **Open in …** (or a double-click on the clip) opens the file's app in a window of its own; **Make a canvas from it** (a photo) makes a canvas on the photo next to it and points the clip at it; **Fill it** (a placeholder); **Remove**. Then where else the file is used, and its properties. From e5a3b2b2f30b73c10b384419134383b582778dfc Mon Sep 17 00:00:00 2001 From: bubulux Date: Thu, 3 Dec 2026 14:01:49 +0100 Subject: [PATCH 02/11] Names from the pattern for new collections, folders and flows (#548) GET /api/projects/:id/next-name shows the next name without raising the counter. The Studio's prompts for a collection and a folder are prefilled with it; kept as it is, the server names the file. The phone and Flows send no name and use the server's. Co-Authored-By: Claude Opus 5.5 --- apps/mobile/src/media/library.ts | 7 +++--- apps/studio/src/api.ts | 3 +++ apps/studio/src/collections.tsx | 9 +++++--- apps/studio/src/ext/flows/FlowsApp.tsx | 2 +- apps/studio/src/fileOps.tsx | 9 +++++--- apps/worker/src/projects.ts | 12 +++++++++- apps/worker/src/properties.ts | 27 ++++++++++++++++------ apps/worker/test/routes/properties.test.ts | 11 +++++++++ apps/worker/test/routes/tenancy.test.ts | 1 + docs/api.md | 1 + docs/features/media.md | 2 +- 11 files changed, 65 insertions(+), 19 deletions(-) diff --git a/apps/mobile/src/media/library.ts b/apps/mobile/src/media/library.ts index 85417c24..515fcbe4 100644 --- a/apps/mobile/src/media/library.ts +++ b/apps/mobile/src/media/library.ts @@ -162,14 +162,15 @@ export async function placePhotos(ids: string[], container: string | null) { } /** A new collection of these photos, in a random one of the eight colours, where they are. */ -export async function makeCollection(ids: string[], name: string, container: string | null): Promise { +/** Makes a collection of these photos; the server names it from the project's pattern (#548). Returns its name. */ +export async function makeCollection(ids: string[], container: string | null): Promise { const project = currentProject(); if (!project) throw new Error("no project"); const id = randomUUID(); - const file = await putFile(id, { type: "collection", project_id: project.id, name, container, body: { color: 1 + Math.floor(Math.random() * 8), order: "time" } }); + const file = await putFile(id, { type: "collection", project_id: project.id, container, body: { color: 1 + Math.floor(Math.random() * 8), order: "time" } }); store.set((l) => (l ? { ...l, files: [file, ...l.files] } : l)); await placePhotos(ids, id); - return id; + return file.name; } export async function binPhoto(id: string) { diff --git a/apps/studio/src/api.ts b/apps/studio/src/api.ts index 583a8f18..fe3ce48e 100644 --- a/apps/studio/src/api.ts +++ b/apps/studio/src/api.ts @@ -47,6 +47,9 @@ export const send = (method: string, path: string, body?: unknown) => export const fetchServerBuild = () => get("/api/ping"); +/** The name the project's naming pattern would give the next file of a type; looking uses up no number. */ +export const nextName = (projectId: string, type: string) => get<{ name: string }>(`/api/projects/${projectId}/next-name?type=${encodeURIComponent(type)}`).then((r) => r.name); + /** Who this browser is, or null when nobody is signed in. */ export async function fetchMe(): Promise { const res = await fetch("/api/me", { credentials: "same-origin" }).catch(() => null); diff --git a/apps/studio/src/collections.tsx b/apps/studio/src/collections.tsx index af2f1543..518aedcf 100644 --- a/apps/studio/src/collections.tsx +++ b/apps/studio/src/collections.tsx @@ -1,6 +1,6 @@ import { useState } from "preact/hooks"; import { AppIcon, Button, Dialog, List, ListRow, colorCss, type ChosenColor } from "@openclapper/design"; -import type { FileRec, Root } from "./api"; +import { nextName, type FileRec, type Root } from "./api"; import { moveFiles } from "./fileOps"; import * as store from "./files"; import { openDialog, prompt, toast, toastError } from "./hosts"; @@ -34,8 +34,11 @@ export function photosOf(c: FileRec, files: readonly FileRec[]): FileRec[] { export async function groupInto(root: Root, files: readonly FileRec[], photos: FileRec[]): Promise { const list = photos.filter((f) => f.type === "photo"); if (!list.length) return; - const name = await prompt({ title: "New collection", label: "Name", value: "Collection", confirmLabel: "Make collection" }); - if (!name) return; + // Prefilled with the name the pattern gives next (#548); kept as it is, the server names it, so the counter moves only when one is made. + const suggested = root === "home" ? "Collection" : await nextName(root.project, "collection").catch(() => "Collection"); + const typed = await prompt({ title: "New collection", label: "Name", value: suggested, confirmLabel: "Make collection" }); + if (!typed?.trim()) return; + const name = root !== "home" && typed.trim() === suggested ? undefined : typed.trim(); const map = store.byId(files); const places = new Set(list.map((f) => { const c = f.container ? map.get(f.container) : undefined; return c?.type === "collection" ? c.container : f.container; })); const container = places.size === 1 ? [...places][0] : null; diff --git a/apps/studio/src/ext/flows/FlowsApp.tsx b/apps/studio/src/ext/flows/FlowsApp.tsx index ede67c58..34c29f16 100644 --- a/apps/studio/src/ext/flows/FlowsApp.tsx +++ b/apps/studio/src/ext/flows/FlowsApp.tsx @@ -45,7 +45,7 @@ export function FlowsApp({ projectId, setTitle, setRoute, resource, focused }: A const f = flows.find((x) => x.id === chosen) ?? null; useEffect(() => { setTitle(f ? `Flows · ${f.name}` : "Flows"); setRoute(f ? f.id : ""); }, [f?.id, f?.name]); const create = async () => { - try { const made = await store.create({ project: projectId }, "flow", { name: `Flow ${flows.length + 1}` }); setChosen((made as FileRec).id); } catch (e) { toastError(e); } + try { const made = await store.create({ project: projectId }, "flow"); setChosen((made as FileRec).id); } catch (e) { toastError(e); } }; if (!files) return
; const list = ( diff --git a/apps/studio/src/fileOps.tsx b/apps/studio/src/fileOps.tsx index 524e7258..a68c6841 100644 --- a/apps/studio/src/fileOps.tsx +++ b/apps/studio/src/fileOps.tsx @@ -3,7 +3,7 @@ import { takenFrame } from "./canvas/geometry"; import { getPrefs } from "./prefs"; import { Button, Dialog, Tree, type TreeNodeData } from "@openclapper/design"; import { MAX_FILE_NAME, emptyCanvas, fileType, placementError } from "@openclapper/model"; -import type { FileRec, Root } from "./api"; +import { nextName, type FileRec, type Root } from "./api"; import { appDef, appFor, launch } from "./apps/registry"; import { fixedGlyph, kindOf, targetOf } from "./fileKinds"; import * as store from "./files"; @@ -59,8 +59,11 @@ export function openFile(f: FileRec, files: ReadonlyMap) { } export async function newFolder(root: Root, container: string | null): Promise { - const name = await prompt({ title: "New folder", label: "Name", value: "New folder", confirmLabel: "Create", check: nameCheck }); - if (!name) return null; + // Prefilled with the pattern's next name (#548); kept as it is, the server names it, so a cancel uses up no number. + const suggested = root === "home" ? "New folder" : await nextName(root.project, "folder").catch(() => "New folder"); + const typed = await prompt({ title: "New folder", label: "Name", value: suggested, confirmLabel: "Create", check: nameCheck }); + if (!typed?.trim()) return null; + const name = root !== "home" && typed.trim() === suggested ? undefined : typed.trim(); try { return await store.create(root, "folder", { name, container }); } catch (e) { toastError(e); return null; } } diff --git a/apps/worker/src/projects.ts b/apps/worker/src/projects.ts index 0395aca2..266c1e7d 100644 --- a/apps/worker/src/projects.ts +++ b/apps/worker/src/projects.ts @@ -1,6 +1,7 @@ import { assertString, assertUuid, HttpError, json, readJson, type Router } from "@openclapper/service-kit"; import { clearProject, fixedFolders, liveFiles, NOT_SETTINGS } from "./files.ts"; -import { extensionsError, masterError } from "@openclapper/model"; +import { extensionsError, fileType, masterError } from "@openclapper/model"; +import { peekName } from "./properties.ts"; import type { Ctx } from "./index.ts"; import { assertBodySize, imageSize, sniffImageType } from "./images.ts"; import { accessIfExists, assertAccess, assertRank, defaultWorkspace, inWorkspaces } from "./tenancy.ts"; @@ -117,6 +118,15 @@ export function registerProjectRoutes(r: Router) { if (!obj) throw new HttpError(404, "the project has no picture"); return new Response(obj.body, { headers: { "content-type": obj.httpMetadata?.contentType ?? "image/jpeg", "cache-control": "private, max-age=31536000, immutable" } }); }); + + /** The name a new file of `?type=` would get from the project's naming pattern, without using up a number (#548). */ + r.on("GET", "/api/projects/:id/next-name", async (ctx, { id }) => { + const pid = assertUuid(id, "id"); + await assertAccess(ctx, "project", pid, "editor"); + const type = new URL(ctx.request.url).searchParams.get("type") ?? ""; + if (!fileType(type)) throw new HttpError(400, "type must be a file type"); + return json({ name: await peekName(ctx.env, pid, type) }); + }); } const DESCRIPTION_MAX = 2000; diff --git a/apps/worker/src/properties.ts b/apps/worker/src/properties.ts index a8f31e24..70da9801 100644 --- a/apps/worker/src/properties.ts +++ b/apps/worker/src/properties.ts @@ -54,15 +54,28 @@ export const propertyRefs = (env: Env, fileId: string): D1PreparedStatement[] => * counter is raised in the same statement that reads it. */ export async function nextName(env: Env, projectId: string, type: string, facts: { device?: string | null; focal?: number | null } = {}): Promise { - const t = fileType(type); - const label = t?.label ?? type; - const row = await env.DB.prepare("SELECT body FROM files WHERE project_id = ?1 AND type = 'naming' AND deleted_at IS NULL AND json_extract(body, '$.for') = ?2 ORDER BY created_at, id LIMIT 1") - .bind(projectId, type).first<{ body: string }>(); - let p = defaultPattern(type); - if (row) { const b = JSON.parse(row.body) as { pattern: string; digits: number }; if (!patternProblems(b.pattern, type).length) p = b; } + const p = await patternOf(env, projectId, type); const counter = (await env.DB.prepare("INSERT INTO name_counters (project_id, type, next) VALUES (?1, ?2, 1) ON CONFLICT (project_id, type) DO UPDATE SET next = next + 1 RETURNING next") .bind(projectId, type).first<{ next: number }>())!.next; - return renderName(p.pattern, p.digits, { type, label, counter, at: new Date(), ...facts }); + return renderName(p.pattern, p.digits, { type, label: fileType(type)?.label ?? type, counter, at: new Date(), ...facts }); +} + +/** + * The name the next file of the type would get, without raising the counter: a prompt shows it, and a + * cancelled prompt uses up no number. Another file made meanwhile can take it; the file then gets the next one. + */ +export async function peekName(env: Env, projectId: string, type: string): Promise { + const p = await patternOf(env, projectId, type); + const row = await env.DB.prepare("SELECT next FROM name_counters WHERE project_id = ?1 AND type = ?2").bind(projectId, type).first<{ next: number }>(); + return renderName(p.pattern, p.digits, { type, label: fileType(type)?.label ?? type, counter: (row?.next ?? 0) + 1, at: new Date() }); +} + +/** The project's pattern for the type, else the default; a pattern with a problem is not used. */ +async function patternOf(env: Env, projectId: string, type: string): Promise<{ pattern: string; digits: number }> { + const row = await env.DB.prepare("SELECT body FROM files WHERE project_id = ?1 AND type = 'naming' AND deleted_at IS NULL AND json_extract(body, '$.for') = ?2 ORDER BY created_at, id LIMIT 1") + .bind(projectId, type).first<{ body: string }>(); + if (row) { const b = JSON.parse(row.body) as { pattern: string; digits: number }; if (!patternProblems(b.pattern, type).length) return b; } + return defaultPattern(type); } // ---------- Search ---------- diff --git a/apps/worker/test/routes/properties.test.ts b/apps/worker/test/routes/properties.test.ts index 3ce8689b..d6e125ee 100644 --- a/apps/worker/test/routes/properties.test.ts +++ b/apps/worker/test/routes/properties.test.ts @@ -173,6 +173,17 @@ describe("names", () => { expect((await list("&type=photo")).find((f) => f.id === p)!.name).toBe("Photo 0001"); void a; void b; }); + test("the next one can be looked at without using up a number (#548)", async () => { + await newProject(); + const peek = async (type: string) => (await ok<{ name: string }>(api(u.token, "GET", `/api/projects/${project}/next-name?type=${type}`))).name; + expect(await peek("collection")).toBe("Collection 001"); + expect(await peek("collection")).toBe("Collection 001"); + const id = uuid(); + await put(id, { type: "collection", project_id: project }, 201); + expect((await list("&type=collection")).find((f) => f.id === id)!.name).toBe("Collection 001"); + expect(await peek("collection")).toBe("Collection 002"); + await ok(api(u.token, "GET", `/api/projects/${project}/next-name?type=nope`), 400); + }); }); describe("a copy", () => { diff --git a/apps/worker/test/routes/tenancy.test.ts b/apps/worker/test/routes/tenancy.test.ts index 23c208d5..8421a866 100644 --- a/apps/worker/test/routes/tenancy.test.ts +++ b/apps/worker/test/routes/tenancy.test.ts @@ -43,6 +43,7 @@ const ROUTES: Record = { "PUT /api/projects/:id/picture": { kind: "exempt", why: "the body is raw bytes, which the generic case cannot send; projects.test.ts checks another workspace's upload is refused" }, "GET /api/projects/:id/picture": { kind: "exempt", why: "the owner's project has no picture here (404 like a refusal); projects.test.ts checks another workspace gets 404 for one that has" }, "DELETE /api/projects/:id/picture": { kind: "id", path: (a) => `/api/projects/${a.project}/picture` }, + "GET /api/projects/:id/next-name": { kind: "id", path: (a) => `/api/projects/${a.project}/next-name?type=shot` }, "GET /api/files": { kind: "id", path: (a) => `/api/files?project_id=${a.project}` }, "GET /api/files/:id": { kind: "id", path: (a) => `/api/files/${a.folder}` }, diff --git a/docs/api.md b/docs/api.md index 1bff0ea6..b2bc9009 100644 --- a/docs/api.md +++ b/docs/api.md @@ -35,6 +35,7 @@ Who a request is (`index.ts` `identify`): a session (bearer header, else cookie; | PUT | `/api/projects/:id/picture` | The project's picture (#426): the image bytes, JPEG, PNG or WebP, at most 5 MB and 2048² pixels (read from the header; `413` above, `415` another type) → `{ project }`. Stored in R2 at `projects//picture`; not a file of the project | | GET | `/api/projects/:id/picture` | The picture (`404` without one), cacheable for good: the Studio versions its URL with `picture_at` | | DELETE | `/api/projects/:id/picture` | Removes it → `{ project }` | +| GET | `/api/projects/:id/next-name?type=` | The name the project's naming pattern would give the next file of that type → `{ name }`, without raising the counter (#548: a prompt shows it, a cancel uses up no number). Editors; `400` for an unknown type | ## Files (`files.ts`) diff --git a/docs/features/media.md b/docs/features/media.md index 8fa926bf..d25e6e56 100644 --- a/docs/features/media.md +++ b/docs/features/media.md @@ -32,7 +32,7 @@ The one file browser, set to photos ([09 · shells](../rewrite/09-shells.md)). E - **A collection is one stacked tile** that can be **scrubbed**: moving the pointer across it shows each photo in turn under a red line, with "n / count" in the corner. The switch next to the views spreads collections out into their photos. - **The collection mark:** a photo of a collection carries its colour, drawn as a bar below (the default), a bar to the left, a dot or a thin frame (a stack's tiles behind take the colour too). How it is drawn is a preference of the account (Settings › Appearance › Media). The list shows the collection as a coloured tag. - **Open** a collection (double-click) to see its photos; open a photo for the Photo app. -- **Collections from the menu or the panel:** Group into a collection… (the ticked photos; a name, a random colour, in the place they share), Add to collection…, Take out of the collection (back to where the collection is), Ungroup (the photos stay; the empty collection goes to the bin). Nothing of this deletes a photo. +- **Collections from the menu or the panel:** Group into a collection… (the ticked photos; a name, prefilled with the one the naming pattern gives next: kept as it is, the server names it, so a cancel uses up no number (#548); a random colour, in the place they share), Add to collection…, Take out of the collection (back to where the collection is), Ungroup (the photos stay; the empty collection goes to the bin). Nothing of this deletes a photo. - **A collection's panel:** its count, its order (by time, or by hand: then its photos are reordered by dragging them in its grid), and its colour: the eight colours and "+" for any other (the design system's `ColorChooser`). The colour is stored with the collection, so everyone sees the same. - **A photo's panel:** the preview, the name, and its facts (Photo, Device; Stored and EXIF folded). - Download the original from a photo's menu. From 257b61e1bd6b53c5163fee75a56364ae1dbde8e2 Mon Sep 17 00:00:00 2001 From: bubulux Date: Thu, 3 Dec 2026 14:01:49 +0100 Subject: [PATCH 03/11] Media (phone): upload icon for import, stacked/spread switch, no tick (#547) Choosing photos for a collection now starts with a long-press on a photo. Co-Authored-By: Claude Opus 5.5 --- apps/mobile/src/apps/Media.tsx | 29 ++++++++++++++++++----------- docs/features/phone-app.md | 6 +++--- 2 files changed, 21 insertions(+), 14 deletions(-) diff --git a/apps/mobile/src/apps/Media.tsx b/apps/mobile/src/apps/Media.tsx index 3a5d572d..13dc3b5c 100644 --- a/apps/mobile/src/apps/Media.tsx +++ b/apps/mobile/src/apps/Media.tsx @@ -24,7 +24,7 @@ import { registerApp } from "./registry"; * the photos at the top level below them. Collections as stacks in their colour, or spread out with * each photo carrying its collection's mark (the account's preference, as in the Studio). A badge on * what is still uploading or stuck. Import from the phone runs through the camera's pipeline; the - * tick chooses photos to make a collection. + * long-press on a photo starts choosing photos to make a collection. */ const view = persisted<"photos" | "folders">("mediaView.v1", "photos"); const spreadOut = persisted("mediaSpread.v1", false); @@ -90,31 +90,37 @@ function Browser({ holder, lib, canvases, picked, setPicked, open, back }: { hol toast(failed.length ? `${added} imported; ${failed.length} could not be read` : `${added} imported`, failed.length ? "danger" : "ok"); } catch (e) { log("warn", "import picker failed", e); toast("The pictures could not be imported", "danger"); } }; + // The server names it from the project's pattern (#548): unique, whatever was renamed or deleted. const make = async () => { if (!picked?.length) return; - const n = colls.length + 1; - try { await makeCollection(picked, `Collection ${n}`, holder?.type === "folder" ? holder.id : null); setPicked(null); toast(`Collection ${n} made`); } + try { const name = await makeCollection(picked, holder?.type === "folder" ? holder.id : null); setPicked(null); toast(`${name} made`); } catch (e) { toast(`No collection: ${(e as Error).message}`, "danger"); } }; const title = picked ? `${picked.length} chosen` : holder?.name ?? "Media"; const sub = picked ? "Tap photos to choose them" : holder ? (inColl ? `Collection · ${photos.length} photos` : "Folder") : project?.name; + const stackSwitch = spreadOut.set(v === "spread")} accessibilityLabel="Collections stacked or spread out" />; return ( setPicked(null) : back} - actions={picked ? [] : [!inColl && { icon: spread ? "layers" : "grid", label: spread ? "Collections as stacks" : "Collections spread out", onPress: () => spreadOut.set(!spread) }, { icon: "download", label: "Import from the phone", onPress: () => void importPictures() }, { icon: "check", label: "Choose several", onPress: () => setPicked([]) }]} />} + actions={picked ? [] : [{ icon: "upload", label: "Import from the phone", onPress: () => void importPictures() }]} />} footer={picked ? <> - : {lock.by === "You" ? "Editing in another window of yours" : lock.by ? `${lock.by} is editing` : "Nobody is editing"})} + : {lock.by === "You" ? "Editing in another window of yours" : lock.by ? `${lock.by} is editing` : "Nobody is editing"}{lock.by === "You" ? : })} {!editing && setMode(v as Mode)} options={[{ value: "outline", label: "Outline" }, { value: "mask", label: "Mask" }, { value: "crop", label: "Crop" }, { value: "full", label: "Full" }]} />} launch({ app: "timeline", resource: MASTER, title: "Master timeline" })}>{master.includes(f.id) ? `No. ${master.indexOf(f.id) + 1} in the master` : "Not in the master"} {lock.editing ? - : {lock.by === "You" ? "Editing in another window of yours" : lock.by ? `${lock.by} is editing` : "Nobody is editing"}} + : {lock.by === "You" ? "Editing in another window of yours" : lock.by ? `${lock.by} is editing` : "Nobody is editing"}{lock.by === "You" ? : }} setMode(v as Mode)} options={[{ value: "outline", label: "Outline" }, { value: "mask", label: "Mask" }, { value: "crop", label: "Crop" }, { value: "full", label: "Full" }]} /> setStageView(v as StageView)} options={[{ value: "source", label: "Source", title: "Only the file you look at" }, { value: "both", label: "Both", title: "The file you look at beside the cut" }, { value: "master", label: "Master", title: "Only the cut" }]} /> diff --git a/apps/studio/src/canvas/CanvasEditor.tsx b/apps/studio/src/canvas/CanvasEditor.tsx index 37eb282d..46c87320 100644 --- a/apps/studio/src/canvas/CanvasEditor.tsx +++ b/apps/studio/src/canvas/CanvasEditor.tsx @@ -67,7 +67,7 @@ export interface CanvasEditorProps { * Who edits. This window (onStop saves, lets the canvas go and turns the window into a viewer), or not: * then the canvas is shown read-only as it changes; by is who edits it (null: nobody, onEdit takes it). */ - access: { editing: true; onStop: () => void } | { editing: false; by: string | null; onEdit: () => void }; + access: { editing: true; onStop: () => void } | { editing: false; by: string | null; onEdit: () => void; onTakeOver?: () => void }; undo?: { can: boolean; run: () => void }; redo?: { can: boolean; run: () => void }; /** The stroke or box being drawn, as it grows (null when it ends): the editor hands it on for viewers. */ onDraft?: (d: Draft | null) => void; @@ -589,7 +589,8 @@ export function CanvasEditor(props: CanvasEditorProps) { {access.editing ? : {access.by === "You" ? "Editing in another window of yours" : access.by ? `${access.by} is editing` : "Nobody is editing"} - } + {access.by === "You" && access.onTakeOver ? + : }} - : {lock.by === "You" ? "Editing in another window of yours" : lock.by ? `${lock.by} is editing` : "Nobody is editing"}} + : {lock.by === "You" ? "Editing in another window of yours" : lock.by ? `${lock.by} is editing` : "Nobody is editing"}{lock.by === "You" ? : }} {centre} {body.tracks.length} tracks · {body.tracks.reduce((n, t) => n + t.keyframes.length, 0)} keyframes · {(body.markers ?? []).length} markers{body.loop ? " · loops" : ""}{playing ? " · playing" : ""} · {!lock.editing ? (lock.live ? "Read-only, live" : "Read-only, read again every 5 s") : status === "saving" ? "Saving…" : status === "waiting" ? "Changed" : status === "failed" ? Not saved : "Saved"} diff --git a/apps/studio/src/lock.ts b/apps/studio/src/lock.ts index adad9379..5d6a11af 100644 --- a/apps/studio/src/lock.ts +++ b/apps/studio/src/lock.ts @@ -10,6 +10,8 @@ import type { FileRec } from "./api"; import { toastError } from "./hosts"; const RENEW_MS = 20_000; +/** How long a lock holds without a renewal (the Worker's LOCK_MS). */ +const LOCK_MS = 60_000; const LOOK_MS = 5_000; const SEND_MS = 150; const MAX_SEND = 1_000_000; @@ -27,6 +29,8 @@ export interface EditLock { held: () => boolean; /** Take the lock (Edit); starts from the file as the server has it. */ edit: () => Promise; + /** Take it from another window of this person (#556): that window becomes a viewer and loses what it had not saved. */ + takeOver: () => Promise; /** Let it go (Stop editing); `flush` saves what is pending first. */ stop: (flush?: () => Promise) => Promise; /** A save was refused with 423: someone else has it now. */ @@ -45,6 +49,8 @@ export function useEditLock(file: FileRec, nameOf: (userId: string) => string, o const holder = useMemo(() => `w${crypto.randomUUID().replace(/-/g, "").slice(0, 24)}`, []); const [editing, setEditing] = useState(false); const [by, setBy] = useState(null); + // When the shown lock ends (null: not known): a viewer reads it again then, so a missed message cannot keep it stale (#556). + const [until, setUntil] = useState(null); const held = useRef(false); const seen = useRef(file.updated_at); const fresh = useRef(onFresh); @@ -61,17 +67,18 @@ export function useEditLock(file: FileRec, nameOf: (userId: string) => string, o const reread = async (always: boolean) => { const f = (await api.get<{ file: FileRec }>(`/api/files/${file.id}`)).file; - if (!held.current) setBy(f.lock?.by ? nameOf(f.lock.by) : null); + if (!held.current) { setBy(f.lock?.by ? nameOf(f.lock.by) : null); setUntil(f.lock?.until ?? null); } if (always || f.updated_at !== seen.current) { seen.current = f.updated_at; fresh.current(f); } }; - const take = async () => { + const take = async (takeOver = false) => { try { - const r = await api.takeLock(file.id, holder); + const r = await api.takeLock(file.id, holder, takeOver); const was = held.current; held.current = r.ok; if (r.ok && was && sock.current?.readyState === WebSocket.OPEN) sock.current.send(JSON.stringify({ type: "held" })); setEditing(r.ok); setBy(r.ok ? null : nameOf(r.lock.by ?? "")); + setUntil(r.ok ? null : r.lock.until); if (r.ok && !was) await reread(true); } catch (e) { toastError(e); } }; @@ -80,6 +87,7 @@ export function useEditLock(file: FileRec, nameOf: (userId: string) => string, o if (opts.off) { held.current = true; setEditing(true); return; } void take(); const renew = setInterval(() => { if (held.current) void take(); }, RENEW_MS); + // (Editors renew; a window open somewhere keeps its lock as long as it is open: "Take over" ends that, #556.) const look = setInterval(() => { if (!held.current && !liveRef.current && !document.hidden) void reread(false).catch(() => {}); }, LOOK_MS); const bye = () => { leaving.current?.(); if (held.current) void api.releaseLock(file.id, holder); }; window.addEventListener("pagehide", bye); @@ -98,19 +106,27 @@ export function useEditLock(file: FileRec, nameOf: (userId: string) => string, o ws = s; sock.current = s; s.onopen = () => { setLive(true); if (!held.current) void reread(false).catch(() => {}); }; s.onmessage = (e) => { - if (held.current) return; - let m: { type?: string; body?: Record; refs?: LiveDoc["refs"]; by?: string | null }; + let m: { type?: string; body?: Record; refs?: LiveDoc["refs"]; by?: string | null; until?: string; holder?: string }; try { m = JSON.parse(String(e.data)) as typeof m; } catch { return; } + // Another window of this person took the lock over: this one watches from now on. + if (held.current) { if (m.type === "editor" && m.holder && m.holder !== holder) { held.current = false; setEditing(false); setBy(m.by ? nameOf(m.by) : null); setUntil(m.until ?? null); } return; } if (m.type === "doc" && m.body) { if (realtime.current) remote.current?.({ body: m.body, refs: m.refs }); } else if (m.type === "saved") void reread(false).catch(() => {}); // Let go or run out: free to edit now, and the last save is read. - else if (m.type === "editor") { setBy(m.by ? nameOf(m.by) : null); if (!m.by) void reread(false).catch(() => {}); } + else if (m.type === "editor") { setBy(m.by ? nameOf(m.by) : null); setUntil(m.until ?? null); if (!m.by) void reread(false).catch(() => {}); } }; s.onclose = () => { if (sock.current === s) { sock.current = null; setLive(false); } if (!done) retry = setTimeout(open, 3000); }; }; open(); return () => { done = true; clearTimeout(retry); if (sock.current === ws) { sock.current = null; setLive(false); } ws?.close(); }; }, [opts.off, editing, file.id]); + // Someone is shown editing: read the lock again when it would have run out (or after a lock's time, end unknown). + useEffect(() => { + if (opts.off || editing || !by) return; + const wait = until ? Math.max(1000, new Date(until).getTime() - Date.now() + 1500) : LOCK_MS + 5000; + const t = setTimeout(() => void reread(false).catch(() => {}), wait); + return () => clearTimeout(t); + }, [opts.off, editing, by, until]); const send = (doc: () => LiveDoc) => { if (!realtime.current) return; const st = sending.current; @@ -130,7 +146,8 @@ export function useEditLock(file: FileRec, nameOf: (userId: string) => string, o return { holder, editing, by, send, live, held: () => held.current, - edit: take, + edit: () => take(), + takeOver: () => take(true), stop: async (flush) => { if (flush) await flush(); held.current = false; diff --git a/apps/worker/src/canvas.ts b/apps/worker/src/canvas.ts index 55850813..c41823ec 100644 --- a/apps/worker/src/canvas.ts +++ b/apps/worker/src/canvas.ts @@ -115,24 +115,27 @@ export async function copyRenders(env: Env, ids: ReadonlyMap): P export function registerCanvasRoutes(r: Router) { /** - * Take or renew the edit lock: JSON { holder } → { lock: { by, until } }. Taken when nobody holds - * it, it ran out, or the same window holds it; else `423` with who has it. + * Take or renew the edit lock: JSON { holder, take_over? } → { lock: { by, until } }. Taken when nobody holds + * it, it ran out, or the same window holds it; else `423` with who has it. `take_over` also takes it from + * another window of the same person (#556: one left open somewhere); never from someone else. */ r.on("POST", "/api/files/:id/lock", async (ctx, { id }) => { const { env, tenant } = ctx; const f = await accessFile(ctx, assertUuid(id, "id"), "editor"); if (!fileType(f.type)?.lockable) throw new HttpError(400, `a ${fileType(f.type)?.label.toLowerCase() ?? "file"} is not edited under a lock`); if (f.deleted_at) throw new HttpError(409, "the file is in the recycle bin; restore it first"); - const holder = readHolder((await readJson>(ctx.request)).holder); + const b = await readJson>(ctx.request); + const holder = readHolder(b.holder); + const takeOver = b.take_over === true ? 1 : 0; const until = new Date(Date.now() + LOCK_MS).toISOString(); // One statement takes it only if free, run out or ours: two windows asking at once cannot both win. const took = await env.DB.prepare( `UPDATE files SET lock_by = ?2, lock_holder = ?3, lock_until = ?4 - WHERE id = ?1 AND (lock_until IS NULL OR lock_until <= ?5 OR (lock_by = ?2 AND lock_holder = ?3))`, - ).bind(f.id, tenant.userId, holder, until, now()).run(); + WHERE id = ?1 AND (lock_until IS NULL OR lock_until <= ?5 OR (lock_by = ?2 AND (lock_holder = ?3 OR ?6 = 1)))`, + ).bind(f.id, tenant.userId, holder, until, now(), takeOver).run(); const row = await env.DB.prepare("SELECT lock_by, lock_until FROM files WHERE id = ?1").bind(f.id).first<{ lock_by: string; lock_until: string }>(); if (!took.meta.changes) return json({ error: "someone else is editing this file", lock: { by: row!.lock_by, until: row!.lock_until } }, 423); - await tellRoom(env, f.id, { type: "lock", by: row!.lock_by, until: row!.lock_until }); + await tellRoom(env, f.id, { type: "lock", by: row!.lock_by, until: row!.lock_until, holder }); return json({ lock: { by: row!.lock_by, until: row!.lock_until } }); }); diff --git a/apps/worker/src/live.ts b/apps/worker/src/live.ts index b860d9bc..0439f89d 100644 --- a/apps/worker/src/live.ts +++ b/apps/worker/src/live.ts @@ -16,8 +16,9 @@ import type { Ctx, Env } from "./index.ts"; * Editor → room: `{ type: "doc", body, base?, refs? }` (the file after a change, throttled by the editor), * `{ type: "draft", draft }` (a stroke being drawn; null when it ends), `{ type: "held" }` (after each renewal), * `{ type: "saved" }` (after a save, when the canvas was too large to send). - * Room → viewers: the same `doc`, `draft` and `saved`, and `{ type: "editor", by }` when an editor connects, renews - * or leaves (by: a user id, or null). + * Room → viewers: the same `doc`, `draft` and `saved`, and `{ type: "editor", by, until?, holder? }` when an editor + * connects, renews or leaves (by: a user id, or null; until: the lock's end when known; holder: the window's token, so + * a window whose lock another window of the same person took over learns it at once, #556). * * The lock itself is live in every project (#426): the lock routes tell the room when it is taken, renewed or let * go, a save tells it `saved`, and an alarm at the lock's end says when it ran out, so who edits is never stale on @@ -71,7 +72,7 @@ export function registerLiveRoutes(r: Router) { * Tells a file's room what changed outside it: the lock (who holds it now, and until when) or a save. Never fails * the request that changed it: the room is a convenience, the database is the truth. */ -export async function tellRoom(env: Env, fileId: string, msg: { type: "lock"; by: string | null; until: string | null } | { type: "saved" }) { +export async function tellRoom(env: Env, fileId: string, msg: { type: "lock"; by: string | null; until: string | null; holder?: string } | { type: "saved" }) { try { await env.CANVAS_LIVE.get(env.CANVAS_LIVE.idFromName(fileId)).fetch(new Request("https://room/notify", { method: "POST", body: JSON.stringify({ file: fileId, ...msg }) })); } catch (e) { console.warn("live: room not told", fileId, e); } @@ -105,7 +106,7 @@ export class CanvasRoom extends DurableObject { const ed = this.open("editor")[0]; const lock = await this.ctx.storage.get<{ by: string; until: string }>("lock"); const held = lock && new Date(lock.until).getTime() > Date.now() ? lock.by : null; - server.send(JSON.stringify({ type: "editor", by: ed ? (ed.deserializeAttachment() as Who).user : held })); + server.send(JSON.stringify({ type: "editor", by: ed ? (ed.deserializeAttachment() as Who).user : held, ...(held ? { until: lock!.until } : {}) })); } return new Response(null, { status: 101, webSocket: client }); } @@ -131,10 +132,10 @@ export class CanvasRoom extends DurableObject { } /** From the lock routes and saves: every socket hears who edits now; a lock's end is watched with an alarm. */ - private async notify(m: { file: string; type: string; by?: string | null; until?: string | null }): Promise { + private async notify(m: { file: string; type: string; by?: string | null; until?: string | null; holder?: string }): Promise { if (m.type === "saved" || m.type === "changed") { this.sendAll({ type: m.type }); return new Response(null, { status: 204 }); } await this.ctx.storage.put("file", m.file); - this.sendAll({ type: "editor", by: m.by ?? null }); + this.sendAll({ type: "editor", by: m.by ?? null, ...(m.by && m.until ? { until: m.until } : {}), ...(m.by && m.holder ? { holder: m.holder } : {}) }); if (m.by && m.until) { await this.ctx.storage.put("lock", { by: m.by, until: m.until }); await this.ctx.storage.setAlarm(new Date(m.until).getTime() + 1000); } else { await this.ctx.storage.delete("lock"); await this.ctx.storage.deleteAlarm(); } return new Response(null, { status: 204 }); diff --git a/apps/worker/test/routes/canvas.test.ts b/apps/worker/test/routes/canvas.test.ts index 618ef8fd..e905a5be 100644 --- a/apps/worker/test/routes/canvas.test.ts +++ b/apps/worker/test/routes/canvas.test.ts @@ -73,6 +73,19 @@ describe("the edit lock", () => { await ok(api(u.token, "POST", `/api/files/${c}/lock`, { holder: "window-cccc" }), 200); }); + test("take over: from another window of the same person (#556)", async () => { + await newProject(); + const c = uuid(); + await put(c, { type: "canvas", project_id: project }, 201); + await ok(api(u.token, "POST", `/api/files/${c}/lock`, { holder: "window-left-open" })); + await ok(api(u.token, "POST", `/api/files/${c}/lock`, { holder: "window-here-01" }), 423); + await ok(api(u.token, "POST", `/api/files/${c}/lock`, { holder: "window-here-01", take_over: true })); + await put(c, { name: "Taken" }, 423, { "x-lock-holder": "window-left-open" }); + await put(c, { name: "Taken" }, 200, { "x-lock-holder": "window-here-01" }); + // The other window's renewal is refused: it learns it lost the lock. + await ok(api(u.token, "POST", `/api/files/${c}/lock`, { holder: "window-left-open" }), 423); + }); + test("only lockable types take a lock", async () => { await newProject(); const f = uuid(); @@ -113,7 +126,7 @@ describe("live updates", () => { editor.send(JSON.stringify({ type: "draft", draft: null })); await new Promise((r) => setTimeout(r, 200)); // The lock was taken before the viewer came: it hears who holds it at once (#426). - expect(inbox).toEqual([{ type: "editor", by: u.id }, { type: "editor", by: u.id }, { type: "doc", body, base: null }, { type: "draft", draft: null }]); + expect(inbox).toMatchObject([{ type: "editor", by: u.id, until: expect.any(String) }, { type: "editor", by: u.id }, { type: "doc", body, base: null }, { type: "draft", draft: null }]); editor.close(1000); viewer.close(1000); // A project that watches the content every 5 seconds still gets the lock live. await ok(api(u.token, "PUT", `/api/projects/${project}`, { name: `P ${project}`, canvas_live: "gradual" })); @@ -133,7 +146,7 @@ describe("live updates", () => { await ok(api(u.token, "PUT", `/api/files/${c}`, { body }, { "x-lock-holder": "wdevice000001" })); expect((await api(u.token, "DELETE", `/api/files/${c}/lock?holder=wdevice000001`)).status).toBe(204); await new Promise((r) => setTimeout(r, 200)); - expect(inbox).toEqual([{ type: "editor", by: null }, { type: "editor", by: u.id }, { type: "saved" }, { type: "editor", by: null }]); + expect(inbox).toEqual([{ type: "editor", by: null }, { type: "editor", by: u.id, until: expect.any(String), holder: "wdevice000001" }, { type: "saved" }, { type: "editor", by: null }]); viewer.close(1000); }); }); diff --git a/docs/api.md b/docs/api.md index 3c761caa..f5ce1e8a 100644 --- a/docs/api.md +++ b/docs/api.md @@ -88,7 +88,7 @@ A new project (`PUT /api/projects/:id`) starts without property definitions (#42 | Method | Path | Notes | | --- | --- | --- | -| POST | `/api/files/:id/lock` | `{ holder }` (the editing window's token) → `{ lock: { by, until } }`: taken when free, run out or this window's; renewed the same way (it holds 60 s). `423` with `lock` when someone else holds it. Lockable types only (a canvas) | +| POST | `/api/files/:id/lock` | `{ holder, take_over? }` (the editing window's token) → `{ lock: { by, until } }`: taken when free, run out or this window's (`take_over: true`: also from another window of the same person, #556); renewed the same way (it holds 60 s). `423` with `lock` when someone else holds it. Lockable types only (a canvas) | | DELETE | `/api/files/:id/lock?holder=` | Lets go; only the holder's call changes anything. `204` | | GET | `/api/canvases/:id/live?holder=` | WebSocket (`426` without the upgrade) to the file's `CanvasRoom` (`live.ts`; any lockable file: canvas, shot, timeline, else `400`): the editor when the window `holder` holds the lock, else a viewer (viewer access is enough), in every project (#426; `canvas_live` only decides whether clients stream the content). Editor sends `doc { body, base?, refs? }`, `draft { draft }`, `saved`, `held`; viewers get those and `editor { by }` (a user id or null). The room also hears the lock routes (taken, renewed, let go: `editor` to every socket, and to a viewer that joins), every save of the file (`saved`), and the lock running out (an alarm at its end: `editor { by: null }`). Other messages, and anything a viewer sends, are dropped | | GET | `/api/live/root?project_id=` or `?home=1` | WebSocket to the root's room (#426; the `CanvasRoom` class under the name `root:` or `root:home:`): it hears `{ type: "changed" }` after every write that changed a file of the root, from any client, noted by the access checks (`touched`); taking or renewing an edit lock does not count. Viewer access is enough | diff --git a/docs/features/canvas.md b/docs/features/canvas.md index d771d57d..b21aa660 100644 --- a/docs/features/canvas.md +++ b/docs/features/canvas.md @@ -45,8 +45,8 @@ One window per canvas (`#/canvas/`), opened from Files (double-click), made - **The editor** (`canvas/CanvasEditor.tsx`, U2's tool on the real model): tools Move (V), Pen (P; pen, marker, highlighter, brush, dashed), Eraser (E; Cuts strokes: the parts of pen strokes under it go and the stroke splits, anything else it touches goes whole; or Whole objects; its size in screen pixels; locked, hidden and grouped objects are left alone; `canvas/erase.ts`), Line (L), Arrow (A), Rectangle (R), Ellipse (O), Text (T, edited in place), Stencil (S), Place a photo (I, a photo of the project), Comment (C). Objects in one stack: select, Shift-select, move, resize from a corner, rotate just outside a corner (Shift: 15°), end points of lines, Alt-drag copies, Ctrl+D duplicates, Delete, Group (Ctrl+G) and Ungroup (Ctrl+Shift+G), the layer list reordered by dragging, hide and lock. Properties of the selection (stroke, fill, width, opacity, rotation, pen, stencil, photo and its look). The surface: a base photo (with its look, and a photo to choose) or paper (shape and colour, or transparent: a checkerboard in the editor, a PNG with transparency as its render; a shot's overlay starts that way); a blank canvas gets a photo underneath from the surface's row. Frames (only with a base photo): from a preset with its focal lengths (buttons for primes, a slider for a zoom), free-form (format, focal length with the prime stops, multiplier, squeeze, delivery; "Create a preset from it"), or an aspect ratio; orientation, colour, name, the picture, Link centres, what it sees. A photo without an angle of view takes aspect frames only. View modes Outline, Mask, Crop, Full (the window's choice, never stored), Compare (two frames side by side), zoom and pan (Ctrl + wheel, wheel, Space-drag, 0 fits), snapping with a switch (Ctrl suspends it), comments (point or region, replies, resolve, move, redraw the region, list with resolved too). - **Saving**: automatic, 0.7 s after the last change, with the body and its references (base and placed); then the render (2048 px on the long side) and the thumbnail (400 px) are drawn in the browser (`canvas/render.ts`, the editor's geometry on a 2D canvas) and uploaded. The status bar says Changed, Saving…, Saved or Not saved. Pen strokes keep a point every few pixels and coordinates are rounded to four decimals, so a body stays small. - **Undo and redo** (Ctrl+Z, Ctrl+Shift+Z or Ctrl+Y): the window's own history of bodies, a drag being one step, up to 100. -- **The lock, editing and watching**: the window takes the lock when it opens (its own token, so a second window of the same person is someone else), renews it every 20 s and lets it go when it closes. **Stop editing** (in the toolbar) saves, lets the lock go and keeps the window open as a viewer. A viewer shows the canvas read-only: zoom, pan, view modes and Compare work; the tools, the Layers and Frames panels, undo, redo and Snap cannot be used and look disabled (muted text, dashed controls); comments can be read, opened on the canvas and listed, but not written, answered or resolved with who edits it, **Edit** (when nobody does: takes the lock and starts from the canvas as the server has it now). A viewer never takes the lock on its own: watching the Studio while drawing on the tablet stays that way. -- **Who edits is always live** (#426): in every project, every window of a lockable file (canvas, shot, timeline, flow; the device's Flows editor too) opens its room's socket (`GET /api/canvases/:id/live`). The lock routes tell the room when the lock is taken, renewed or let go, every save of the file tells it `saved`, and an alarm at the lock's end says when it ran out; a viewer that joins hears who holds it at once. So a window shows at once who edits, that it is free (and reads the last save), and every save, without a reload. +- **The lock, editing and watching**: the window takes the lock when it opens (its own token, so a second window of the same person is someone else), renews it every 20 s and lets it go when it closes. **Stop editing** (in the toolbar) saves, lets the lock go and keeps the window open as a viewer. A viewer shows the canvas read-only: zoom, pan, view modes and Compare work; the tools, the Layers and Frames panels, undo, redo and Snap cannot be used and look disabled (muted text, dashed controls); comments can be read, opened on the canvas and listed, but not written, answered or resolved with who edits it, **Edit** (when nobody does: takes the lock and starts from the canvas as the server has it now). A viewer never takes the lock on its own: watching the Studio while drawing on the tablet stays that way. **Take over** (#556) replaces Edit when the lock is held by another window of the same person ("Editing in another window of yours", perhaps one left open, minimised or in another workspace): this window takes the lock (`take_over`), the other hears it through the room at once and becomes a viewer; what it had not saved yet is lost. Someone else's lock is never taken over. +- **Who edits is always live** (#426): in every project, every window of a lockable file (canvas, shot, timeline, flow; the device's Flows editor too) opens its room's socket (`GET /api/canvases/:id/live`). The lock routes tell the room when the lock is taken, renewed or let go, every save of the file tells it `saved`, and an alarm at the lock's end says when it ran out; a viewer that joins hears who holds it at once, with the lock's end. A viewer that shows someone editing also reads the file again when that lock would have run out (a minute when the end is not known), so a missed message (a socket down, an alarm late) cannot keep "being edited" on screen (#556). So a window shows at once who edits, that it is free (and reads the last save), and every save, without a reload. - **Live content** (Project, General, "Canvases while someone edits them"; `projects.canvas_live`): **Realtime** or **Every 5 seconds**. Every 5 seconds: no content streams; a viewer reads the file again after each save (the room's `saved`) and every 5 s while its socket is down. Realtime (`apps/worker/src/live.ts`): every window of the canvas opens a live socket (`GET /api/canvases/:id/live`) to one Durable Object per canvas, `CanvasRoom` (the same room serves every lockable file: shots and timelines send their body and references, `lock.ts` in the Studio); the window that holds the lock is its editor, every other one a viewer. The editor sends the canvas after each change and the stroke or box being drawn, at most every 120 ms; viewers show both at once, and who edits (also when the editor leaves). Nothing is stored in the room: saves still go to D1 under the lock. A canvas over 1 MB of JSON is not sent whole: viewers read it again after each save. A viewer whose socket dropped reads every 5 s until it is back (it retries every 3 s). The status bar says "live" while the socket is open. - Thumbnails of canvases show in Files once a canvas was saved. A canvas with a picture has its thumbnail cropped to the picture (Crop); the render is always the whole surface. diff --git a/docs/known-issues.md b/docs/known-issues.md index 841f1895..7e79a581 100644 --- a/docs/known-issues.md +++ b/docs/known-issues.md @@ -4,6 +4,7 @@ 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-12-03 (#556) | Studio · Edit lock | A canvas stayed "being edited" until the Studio restarted (project on Every 5 seconds). Not reproduced; two likely causes are covered: a Studio window left open keeps renewing its lock (now: **Take over** from another window of the same person), and a missed let-go/ran-out message (now: a viewer reads the lock again when it would have run out). If it happens again, ask for the phone's debug log and check the file's `lock_by`, `lock_holder`, `lock_until`. | Owner reproduces with Every 5 seconds and Realtime. | `apps/studio/src/lock.ts`, `apps/studio/src/apps/CanvasApp.tsx`, `apps/worker/src/live.ts` | | 2026-12-01 (#518) | Flows · Lights | Groups declared in the flow: tested against the simulated mesh and in unit tests only, not on the 12 MC. From the Studio (Live or Play through the proxy) each command is thinned per light and op on its own (`hardware/link.ts`), so a group's commands may reach the phone more than the queue's 10 ms apart and go one by one; the phone's own Play and Run do not have that step. A light in two groups of flows held at once whose list is full makes the groups give way to each other on every change of the held flows. Not clicked through on the phone or tablet (bracket, links, the track sheet). | The owner tests on the lights before a release (debug log: `mesh groups: declared`, `mesh groups: new group`, subscriptions). | `packages/ext-flows/src/groups.ts`, `player.ts`, `apps/mobile/src/ext/hardware/bt/mesh/groups.ts`, `bt/drivers/sidusMesh.ts`, `proxy.ts` | | 2026-11-28 (#426) | Phone · Lights | Aputure lights that change together now get one message to a mesh group (subscriptions, the shared write, the brightness sent alone or split from the colour, the flow's pre-roll). All of it is tested against a simulated mesh only, never on lights. Not known: whether the MC acts on the `0x26` command sent to a group once its on/off server is subscribed (the maker's app does exactly this, but on the lights as it paired them); how many group addresses one MC keeps (8 groups per network are made; a light that says its list is full makes its oldest group give way); whether the intensity message keeps the colour in colour mode on the MC as it does from the maker's app; whether an MC at 0 % takes a colour (the pre-roll relies on it). A light that for any reason no longer listens to a group the phone's table says it does would miss that group's messages until the table is made again. | The owner tests on the lights; the debug log shows every group made and every subscription (`mesh groups: …`). **Reconnect all** starts the groups afresh (every light's list is emptied and made again). | `apps/mobile/src/ext/hardware/bt/mesh/groups.ts`, `bt/drivers/sidusMesh.ts`, `bt/queue.ts`, `packages/ext-flows/src/flow.ts` | | 2026-11-27 (#426) | Studio · shots | A progression's edits reach watchers of its shot only after each save (0.4 s), not stroke by stroke through the live room as the shot's content does: the progression is a file of its own and the room streams the shot. Migration 0013 ran on a copy of a local database and in a route test, not on staging data. | The room carries one file's body; a progression save tells it `saved` and the watchers read again | `apps/worker/src/files.ts`, `apps/studio/src/shots/doc.ts`, `apps/worker/migrations/0013_progression_files.sql` | From a118aa7091949afb7aac770125c6c226c87d24ea Mon Sep 17 00:00:00 2001 From: bubulux Date: Thu, 3 Dec 2026 14:14:17 +0100 Subject: [PATCH 06/11] Colour chooser: colours used before, removable (#551) Co-Authored-By: Claude Opus 5.5 --- apps/specimen/src/cards/components/data.tsx | 3 +++ packages/design/src/forms/ColorChooser.tsx | 12 +++++++++++- packages/design/src/forms/forms.css | 1 + 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/apps/specimen/src/cards/components/data.tsx b/apps/specimen/src/cards/components/data.tsx index 7f7c6bb5..686a7eea 100644 --- a/apps/specimen/src/cards/components/data.tsx +++ b/apps/specimen/src/cards/components/data.tsx @@ -14,6 +14,7 @@ const pic = (hue: number, label: string) => `data:image/svg+xml,${encodeURICompo function Media() { const [mark, setMark] = useState("bar"); const [color, setColor] = useState(6); + const [kept, setKept] = useState(["#ff7a00", "#2f9e44", "#1c7ed6"]); const tint = colorCss(color); const srcs = [pic(20, "24"), pic(120, "35"), pic(220, "50"), pic(300, "85")]; return ( @@ -28,6 +29,8 @@ function Media() { colour chooser · eight colours and one of your own · Morning walk
+ with colours used before (a canvas keeps them) · right-click one to remove it +
setKept(kept.filter((x) => x !== c))} />
); } diff --git a/packages/design/src/forms/ColorChooser.tsx b/packages/design/src/forms/ColorChooser.tsx index 751f5418..dfdfcdc3 100644 --- a/packages/design/src/forms/ColorChooser.tsx +++ b/packages/design/src/forms/ColorChooser.tsx @@ -18,9 +18,13 @@ export interface ColorChooserProps extends Omit void; label: string; + /** Colours of one's own used before (a canvas keeps them, #551): a second row after the eight, newest first. */ + kept?: readonly string[]; + /** Takes a kept colour out of the row (right-click, or a long press on a touch screen). */ + onForget?: (c: string) => void; } -export function ColorChooser({ value, onChange, label, className, ...rest }: ColorChooserProps) { +export function ColorChooser({ value, onChange, label, kept, onForget, className, ...rest }: ColorChooserProps) { const own = typeof value === "string"; const [open, setOpen] = useState(own); return ( @@ -29,6 +33,12 @@ export function ColorChooser({ value, onChange, label, className, ...rest }: Col {[1, 2, 3, 4, 5, 6, 7, 8].map((n) =>
+ {!!kept?.length && ( +
+ {kept.map((c) =>
+ )} {open && }
); diff --git a/packages/design/src/forms/forms.css b/packages/design/src/forms/forms.css index d2345aee..bbd6ad4b 100644 --- a/packages/design/src/forms/forms.css +++ b/packages/design/src/forms/forms.css @@ -104,4 +104,5 @@ button.oc-chip:hover,.oc-chip.is-hover{background:var(--surface-hover)} .oc-swatches>*{position:relative;display:grid;place-items:center;width:22px;height:22px;padding:0;border:0;border-radius:50%;color:var(--text-secondary);cursor:pointer} .oc-swatches>.is-on{box-shadow:0 0 0 2px var(--surface),0 0 0 4px var(--text)} .oc-swatches>:focus-visible{outline:0;box-shadow:0 0 0 2px var(--surface),0 0 0 4px var(--focus)} +.oc-swatches--kept{padding-top:0} .oc-swatches__own{border:var(--border-w) dashed var(--border-control)!important} From c33c0f590b69693bbdf82fb55907e9ac030a27e6 Mon Sep 17 00:00:00 2001 From: bubulux Date: Thu, 3 Dec 2026 14:14:17 +0100 Subject: [PATCH 07/11] Canvas: a Properties panel, a paper grid, paper of any ratio, kept colours (#552, #554, #551) - Properties of its own above Layers/Frames/Comments: the selection, or the paper with nothing selected; the toolbar's colour and width change the selection too. - A grid on blank paper (stored, editor only, snapped to); not shared with the Flows stage. - Paper of one's own ratio; objects and comments keep their size and place (reshapePaper). - Kept colours per canvas in the body (at most 12), removable; the highlighter without a blend so it shows on white. - A click on a layer row selects again: the row was captured on press for the reorder drag, so the click went to its block. Co-Authored-By: Claude Opus 5.5 --- apps/studio/src/canvas/CanvasEditor.tsx | 95 ++++++++++++++++++------- apps/studio/src/canvas/canvas.css | 5 ++ docs/features/canvas.md | 7 +- packages/model/src/canvas.test.ts | 24 ++++++- packages/model/src/canvas.ts | 43 +++++++++-- packages/model/src/drawing.ts | 3 +- 6 files changed, 141 insertions(+), 36 deletions(-) diff --git a/apps/studio/src/canvas/CanvasEditor.tsx b/apps/studio/src/canvas/CanvasEditor.tsx index 46c87320..b5874ec5 100644 --- a/apps/studio/src/canvas/CanvasEditor.tsx +++ b/apps/studio/src/canvas/CanvasEditor.tsx @@ -12,7 +12,7 @@ import { type IconName, type MenuItemData, } from "@openclapper/design"; import { DELIVERIES, FORMATS, PRIMES, SQUEEZES } from "@openclapper/fov-math"; -import { focalsOf, type CanvasBody, type CanvasComment as Comment, type CanvasFrame as Frame, type Colour, type Look, type PenType, type PresetBody } from "@openclapper/model"; +import { focalsOf, GRID_COLS, keepColour, reshapePaper, type CanvasBody, type CanvasComment as Comment, type CanvasFrame as Frame, type Colour, type Look, type PenType, type PresetBody } from "@openclapper/model"; import { eraseAt, type EraseMode } from "./erase"; import { clampCentre, lookFilter, NO_LOOK, PENS, rectOf as rectIn, toEdit, toStore, type BasePhoto, type Obj, type P } from "./geometry"; import { DraftView, KIND, objectFromDraft, ObjectView, STENCILS, type Draft } from "./objects"; @@ -35,14 +35,25 @@ type Act = | { type: "pinch"; d: number; mid: P; z: number; x: number; y: number } | { type: "erase"; last: P }; +/** An aspect as small whole numbers (16 × 9, 297 × 210): the closest with a height up to 300. */ +const ratioOf = (a: number): [number, number] => { let best: [number, number] = [Math.round(a * 100), 100]; for (let q = 1; q <= 300; q++) { const w = Math.round(a * q); if (w > 0 && Math.abs(w / q - a) < 0.0005) { best = [w, q]; break; } } return best; }; const turn = (v: P, deg: number): P => { const r = (deg * Math.PI) / 180, c = Math.cos(r), n = Math.sin(r); return [v[0] * c - v[1] * n, v[0] * n + v[1] * c]; }; const ROTATE = `url("data:image/svg+xml;utf8,${encodeURIComponent('')}") 12 12, crosshair`; const uid = (p = "o") => `${p}${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`; const when = (iso: string) => { const d = new Date(iso); return Number.isNaN(d.getTime()) ? iso : d.toLocaleString(undefined, { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" }); }; -/** A colour dot that opens the chooser (the eight colours, none, or one of your own). */ -function ColourButton({ value, onChange, label }: { value: Colour; onChange: (c: Colour) => void; label: string }) { - return }>; +/** Colours of one's own this canvas keeps (#551): offered in every chooser, the one used kept when the chooser closes. */ +interface Kept { colours: readonly string[]; keep: (c: Colour) => void; forget: (c: string) => void } + +/** A colour dot that opens the chooser (the eight colours, the canvas's own ones, or a new one). */ +function ColourButton({ value, onChange, label, kept }: { value: Colour; onChange: (c: Colour) => void; label: string; kept?: Kept }) { + const last = useRef(value); + last.current = value; + return ( + { if (!open) kept?.keep(last.current); }} trigger={ : } {o.name}{o.kind === "group" && · {kids(o.id).length}} @@ -377,11 +392,13 @@ export function CanvasEditor(props: CanvasEditorProps) { ); const blockOf = (t: Obj) => <>{row(t)}{t.kind === "group" && open.includes(t.id) && [...kids(t.id)].reverse().map((k) => row(k, 1))}; - const sortDown = (e: PointerEvent, t: Obj) => { if (e.button !== 0 || (e.target as HTMLElement).closest("button")) return; sortStart.current = { id: t.id, y: e.clientY }; capture(e); }; + const sortDown = (e: PointerEvent, t: Obj) => { if (e.button !== 0 || (e.target as HTMLElement).closest("button")) return; sortStart.current = { id: t.id, y: e.clientY }; }; const sortMove = (e: PointerEvent) => { const st = sortStart.current; if (!st) return; if (!sort) { - if (Math.abs(e.clientY - st.y) < 4) return; + if (Math.abs(e.clientY - st.y) < 4 || !(e.buttons & 1)) return; + // Captured only once it is a drag: captured at the press, a plain click would land on the block, not on its row. + capture(e); const els = [...(e.currentTarget as HTMLElement).parentElement!.querySelectorAll(":scope > .cv-block")], rects = els.map((el) => el.getBoundingClientRect()), from = order.findIndex((t) => t.id === st.id), r = rects[from]; setSort({ id: st.id, from, to: from, h: r.height, x: r.left, w: r.width, y: e.clientY, grab: st.y - r.top, mids: rects.map((q) => q.top + q.height / 2), tops: rects.map((q) => q.top), hs: rects.map((q) => q.height) }); return; @@ -405,6 +422,18 @@ export function CanvasEditor(props: CanvasEditorProps) { {photos.length ?
{photos.map((p) => )}
:

No photos in this project yet.

}
); + const [shapeOwn, setShapeOwn] = useState(() => surface.kind === "blank" && !BLANK_ASPECTS.some((a) => Math.abs(a.ratio - surface.aspect) < 0.001)); + const [ratio, setRatioState] = useState<[number, number]>(() => ratioOf(surface.kind === "blank" ? surface.aspect : 1)); + const presetShape = surface.kind === "blank" ? BLANK_ASPECTS.find((a) => Math.abs(a.ratio - surface.aspect) < 0.001) : undefined; + const [gridCols, setGridCols] = useState(surface.kind === "blank" && surface.grid ? surface.grid : 16); + /** A new shape of the paper: objects and comments keep their size and place against its middle (#551). */ + const reshape = (aspect: number) => { + if (surface.kind !== "blank") return; + const a = Math.min(10, Math.max(0.1, aspect)); + const out = reshapePaper({ surface, objects: objs.map(toStore), frames, picture: null, linkCentres: linked, comments }, a); + setObjs(out.objects.map(toEdit)); setComments(out.comments); setSurface(out.surface); + }; + const setRatio = (r: [number, number]) => { setRatioState(r); if (r[0] > 0 && r[1] > 0) reshape(r[0] / r[1]); }; const setSurfaceKind = (k: "photo" | "blank") => { if (k === surface.kind) return; if (k === "blank") { setFrames([]); setPic(null); setSelF(null); setSurface({ kind: "blank", aspect: base?.aspect ?? 16 / 9, color: "#ffffff" }); props.onBase(null); } @@ -422,12 +451,17 @@ export function CanvasEditor(props: CanvasEditorProps) {
{order.map((t, i) =>
sortDown(e, t)} onPointerMove={sortMove} onPointerUp={sortUp} onPointerCancel={sortUp}>{blockOf(t)}
)} {sort && root.current && createPortal(
{blockOf(byId.get(sort.id)!)}
, root.current)} -
{ setSel([]); setSelF(null); setRootSel(true); }}>{photo ? base?.name ?? "Photo" : "Paper"} · the surface
+
{ setSel([]); setSelF(null); setRootSel(true); setTab("properties"); }}>{photo ? base?.name ?? "Photo" : "Paper"} · the surface

Top of the list is in front. Drag a row to reorder; Shift-click to select several.

- {rootSel && ( - + + ); + + // Inspector: properties (#552): the selection, or with nothing selected the surface. + const propsTab = <> + {!marks.length && ( + setSurfaceKind(v as "photo" | "blank")} options={[{ value: "photo", label: "Base photo" }, { value: "blank", label: "Blank" }]} /> {photo ? ( <> @@ -438,8 +472,11 @@ export function CanvasEditor(props: CanvasEditorProps) { ) : ( <> {photoPicker(null, (id) => { setSurface({ kind: "photo" }); props.onBase(id); }, "Put a photo underneath…")} - { if (v === "own") { setShapeOwn(true); setRatioState(ratioOf(surface.aspect)); } else { setShapeOwn(false); reshape(Number(v)); } }} options={[...BLANK_ASPECTS.map((a) => ({ value: String(a.ratio), label: a.label })), { value: "own", label: "Your own ratio…" }]} /> + {shapeOwn && setRatio([w, ratio[1]])} />× setRatio([ratio[0], h])} />} + {surface.color !== null && setSurface({ ...surface, color: c })} />} setSurface({ ...surface, color: c ? null : "#ffffff" })}>Transparent + { const { grid: _g, ...rest } = surface; setSurface(on ? { ...rest, grid: gridCols } : rest); }}>{surface.grid != null ? "Shown, snapped to" : "Off"}{surface.grid != null && { const c = Math.round(Math.min(GRID_COLS.max, Math.max(GRID_COLS.min, n))); setGridCols(c); setSurface({ ...surface, grid: c }); }} />} +

The grid shows only here, never in the picture of the canvas. A new shape keeps every object's size and place against the middle of the paper.

)}
@@ -451,8 +488,8 @@ export function CanvasEditor(props: CanvasEditorProps) { {one?.kind === "stencil" && Change}>
{STENCILS.map((s) => )}
} {one?.kind === "picture" && {photoPicker(one.photo ?? null, (id) => patchO([one.id], { photo: id, name: photos.find((p) => p.id === id)?.name ?? one.name }), "Choose")}} {one?.kind === "picture" && look(one.look ?? NO_LOOK, (l) => patchO([one.id], { look: l }))} - {marks.some((m) => m.kind !== "group" && m.kind !== "picture") && patchO(sel, { stroke: c })} />} - {marks.some((m) => m.kind === "rect" || m.kind === "ellipse") && patchO(sel, { fill: c ? marks[0].stroke : null })}>Filled{marks[0].fill != null && patchO(sel, { fill: c })} />}} + {marks.some((m) => m.kind !== "group" && m.kind !== "picture") && patchO(sel, { stroke: c })} />} + {marks.some((m) => m.kind === "rect" || m.kind === "ellipse") && patchO(sel, { fill: c ? marks[0].stroke : null })}>Filled{marks[0].fill != null && patchO(sel, { fill: c })} />}} {one?.kind === "pen" && { const p = presets.find((x) => x.id === v)!; const f = focalsOf(p.body.lenses); const focal = f.includes(cur.focal ?? 0) ? cur.focal! : f[0]; patchF(cur.id, { preset: p.id, focal, name: `${focal} mm` }); }} options={presets.filter((p) => !p.body.archived || p.id === preset.id).map((p) => ({ value: p.id, label: p.name }))} /> @@ -580,6 +616,7 @@ export function CanvasEditor(props: CanvasEditorProps) {
setTool(t as Tool)} tools={[TOOLS[0], { separator: true }, ...TOOLS.slice(1, 7), { separator: true }, ...TOOLS.slice(7, 10), { separator: true }, TOOLS[10]]} />
}, + { id: "properties", title: "Properties", icon: "sliders", body: {propsTab} }, { id: "layers", title: "Layers", icon: "layers", body: {layersTab} }, { id: "frames", title: `Frames${photo ? ` · ${frames.length}` : ""}`, icon: "frame", body: {framesTab} }, { id: "comments", title: `Comments · ${comments.filter((c) => !c.resolved).length}`, icon: "comment", body: {commentsTab} }, @@ -592,10 +629,13 @@ export function CanvasEditor(props: CanvasEditorProps) { {access.by === "You" && access.onTakeOver ? : }} }>
{STENCILS.map((s) => )}
} {tool === "picture" && photoPicker(placing, setPlacing, "Choose a photo")} @@ -660,6 +700,7 @@ export function CanvasEditor(props: CanvasEditorProps) {
setEraserAt(null)}> {props.backdrop && } {photoImg} + {surface.kind === "blank" && surface.grid != null &&