diff --git a/.context/TECHSTACK.md b/.context/TECHSTACK.md index b9bbd82e1..d28372cbb 100644 --- a/.context/TECHSTACK.md +++ b/.context/TECHSTACK.md @@ -29,7 +29,7 @@ internal selection language. - Element links use `/c/?frame=&element=` (no selector form, and no backwards compatibility for the old one). `src/lib/elementLink.ts` owns copying from the - element toolbar and Layers menu, stamping first when the element has no id; `Stage.tsx` + element menu and Layers menu, stamping first when the element has no id; `Stage.tsx` focuses its page and frame; `FrameView.tsx` resolves the id in the ready iframe, including script-created elements, re-picks the positional path so the Layers panel follows, and falls back to frame details if nothing carries the id. Browser regressions in @@ -266,7 +266,10 @@ healed document, so a cut-off script never runs). - No files inside frames (`server/inlineData.ts`, `LEAN_FRAMES` in `server/guide.ts`): an agent write that adds a base64 `data:` URI of any kind is refused and nothing is written, with what to - do per kind (font, picture, SVG, media). Checked on what the call submits: MCP `create_frame`, + do per kind (font, picture, SVG, media). So is one that adds a block of 4,096 or more base64 + characters that is not a data: URI (`EMBEDDED_MIN_LENGTH`: a packed script bundle, a compressed + data file in a string literal; one canvas held 6 MB of it per frame, 13 GB across its kept + versions). Checked on what the call submits: MCP `create_frame`, `set_frame_html`, `append_frame_html` chunks, `edit_frame_html`'s `new_str`, every component tool's strings, and the resident's create / set / edit / rewrite chunks. A URI the frame already holds may be carried over (a PDF import embeds its fonts), so such a frame stays editable. @@ -568,7 +571,9 @@ data-doop-webfonts>` for the roster families the frame names and does not load i (`store.pickElements`), and ⌘] / ⌘[ step the picked elements, together, or the selected frame forward or backward, ⌘⌥] / ⌘⌥[ to the front or back (`reorderElements` / `reorderLayers`, `restackFrame`), one undo step each. A picked standalone shape is its page's row: Tab, ⌘A and - the brackets treat it as a frame, and ⌘A skips stack-locked shapes (`isStackLocked`). ↩ and Tab act only when no control has the keyboard (`isControlTarget`) and + the brackets treat it as a frame, and ⌘A skips stack-locked shapes (`isStackLocked`). In the Layers panel ⇧/⌘-click on a + top-level row (frame or canvas shape) adds it to the selection or drops it, as ⇧-click does on the canvas, + and ⌫ in the tree deletes every selected one. ↩ and Tab act only when no control has the keyboard (`isControlTarget`) and something is selected, so buttons, menus and the Layers tree keep theirs. The bracket chords are read by `code` too, since ⌥ changes the typed character on macOS. Tests: `selectionKeys.test.ts`. - Canvas commands (`src/lib/actions/`): every editor command is one entry in `registry.ts` (id, @@ -617,7 +622,18 @@ data-doop-webfonts>` for the roster families the frame names and does not load i (`planGroup`: direction from the wider run, gap the mean space, `align-items` the shared edge, children reordered to the flow and given `flex-shrink:0`) when they do not overlap along it, else pinned (an absolute box of their bounds, children re-based). Layers in flow keep the - flow-carrying group. ⇧⌘G on an absolute group puts its layers back absolute where they show. A + flow-carrying group. ⇧⌘G on an absolute group puts its layers back absolute where they show. Shapes on the canvas + (`src/lib/canvasGroups.ts`): ⌘G on two or more unlocked, unturned standalone shapes of one page keeps the + frontmost one's frame (its id, comments, versions and stack place) and moves the others' layers into it, + inside one `data-doop-drawing="group"` layer placed by percentages so the frame's grips scale them; the + others' frames go, all as one undo step (`recordShellRewrite`). A shape whose frame would go is refused + when it carries comments or a component main. ⇧⌘G on such a group gives each layer a frame of its own + just behind, the group's frame keeping the frontmost. Every write is conditional: a shape a teammate edited + meanwhile stays on the canvas and leaves the group (`keepShell`), and the step is `guarded`: undo or redo + refuses once someone else (as the room reports, `src/lib/theirSaves.ts`) has saved a frame it would overwrite or delete since its own save (`noteSaved`); this browser's later steps and their undo do not count. It checks again before each write, and each write is conditional on the newest version this browser knows, so a save landing meanwhile is a conflict, not overwritten. Refused + too: moving the frame's corner under comments pinned to the frame (they are frame-relative), splitting a + group turned or flipped as a whole, and splitting one whose wrapper has comments; a hidden group splits into hidden shapes. A split is tracked whole, so an undo pressed meanwhile waits for it, and + it selects the new shapes only if the selection and page are still the ones it started from. Tests: `canvasGroups.test.ts`. A click picks the outermost canvas group around the hit, a double-click on a picked group goes one level in, and with a layer inside picked clicks pick its siblings (`groupLevel`); comments still pin to the element under the pointer. Drops (`frameDropRuntime.ts`, canvas drags of layers and @@ -762,9 +778,21 @@ data-doop-webfonts>` for the roster families the frame names and does not load i bounds and turned with it, so a turned layer keeps its grips and resizes along its own axes (`derotateDelta`; no guide snapping while turned). `sizable` now admits the element's own turn and still refuses a turned, skewed, 3D or nonuniformly scaled ancestor; unsupported transforms - use the axis-aligned rendered bounds for the selection outline. The element toolbar lifts to 30px above a - selection wearing furniture, clear of the top zones. Tests: `elementRotate.test.ts`, + use the axis-aligned rendered bounds for the selection outline. Tests: `elementRotate.test.ts`, `elementRotateBrowser.test.ts`, the turned cases in `elementResizeBrowser.test.ts`. +- Distances (`src/lib/measure.ts`, `src/lib/measureKey.ts`, `src/components/MeasureOverlay.tsx`): holding ⌥ + with the Select tool and something selected shows, as Figma does, red lines labelled with the distance + from the selection to what the pointer is over. The picked elements are measured, as one box, to the + element under the pointer in their frame (the runtime's `doop:measure`, `measureElement` in + `frameBridge.ts`), or to the box around the primary one (its parent, the frame for a root layer) when + the pointer is on one of them; selected frames are measured, as one box, to another frame under the + pointer, which is also what a picked element's frame gets once the pointer is over another frame. + Boxes that overlap are measured edge to matching edge, boxes apart across the gap, with a dashed + extension of the target's edge when it is off to one side (`measureBetween`, pure). The overlay lives + in the Stage's world and reads at most once a frame, on pointer events and on changes to the canvas, + selection or camera; nothing shows during a drag, while typing in a field, or with ⌘ / Ctrl held, and + letting ⌥ go over the canvas does not open the browser's menu bar. Turned frames and layers are + measured by their bounds. Tests: `measure.test.ts`, `measureBrowser.test.ts`. - Rulers and guides (`src/components/Rulers.tsx`, math in `src/lib/rulers.ts`): ⇧R or the zoom menu toggles `` rulers docked on the stage's top and left edges (the top bar and the floating chrome step in by `RULER_PX`) (remembered under @@ -877,6 +905,30 @@ data-doop-webfonts>` for the roster families the frame names and does not load i (`actions.handBackComment`: unclaimed, no longer an agent item in memory and in its row, the thread open), so the person's `@mention` answer queues fresh work carrying the whole conversation. MCP agents have had the same two tools all along. Tests: `residentComments.test.ts`, `agentToolParity.test.ts`. +- People in comments (`shared/personMentions.ts`, `server/canvasPeople.ts`, `src/components/MentionPicker.tsx`): + a mention is `@` plus the person's account name in the text (`@Ana Souza`, longest name first, + no case, a name ends where no letter, combining mark, digit or `_` follows). Typing `@` in the + composer, a thread reply or the Comments panel's reply lists the canvas's people (owner, + members, workspace members, from `GET /api/canvases/:id/people`, comment role, names and faces + only, asked again whenever a field mounts) and, for editors, its agents; the thread draws + mentions in brand. Names are not unique, so the picker sends the ids it picked as `mentions` + beside the text (the latest pick of a name in the draft; an agent picked over a person + named like its handle rides as `agent:`, so the agent gets it). The routes, MCP `reply_to_comment` and the resident's reply resolve the text + once (`resolveCommentMentions` → `resolvePersonMentions`) against everyone eligible (those + people plus the thread's authors) before any filtering: a name several people share reaches + only the picked ones, and nobody when none was picked. The result's `roleText` (people + blanked out) is what the agent matcher, the edit-access check and the meter read, so + `@Doop Fan` is not `@doop`; the resident strips agent mentions only outside people's + (`withoutAgentMentions`). The ids ride the `comment.created` / `comment.replied` event, and + `commentNotifications.ts` emails each at once (`mentionEmail`) and leaves them out of that + comment's digest. The author, someone who switched comment emails off, a banned account or + someone who lost access is not written to. Comment links (`src/lib/commentLink.ts`, the shape + of `server/links.ts`'s `commentLink`): "Copy link to comment" on a pin's right-click menu, an + open Comments panel row's, and the link button on a thread's first message. Opening one, + `Stage` follows the root to its current frame, not the one the link names. Tests: + `personMentions.test.ts`, `commentLink.test.ts`, the `@mentions` cases in + `commentNotifications.test.ts`, the picker cases in `commentsPanel.test.tsx`, the mention and + `/people` cases in `canvasCommentsRoute.test.ts`, the person case in `residentComments.test.ts`. - Chat in the Agents tab (`src/components/AgentChat.tsx`, `src/lib/agentChat.ts`): under Recent tasks, each composer prompt (a board card without a `kind`) and any feedback left on it is a turn, oldest first, with the agent's answer under it: waiting, working, the run's closing words, diff --git a/ios/BlitzKit/rust/Cargo.lock b/ios/BlitzKit/rust/Cargo.lock index 37c81396f..ebdc1ed97 100644 --- a/ios/BlitzKit/rust/Cargo.lock +++ b/ios/BlitzKit/rust/Cargo.lock @@ -232,7 +232,7 @@ dependencies = [ [[package]] name = "blitz-dom" version = "0.3.0-beta.2" -source = "git+https://github.com/kgoedecke/blitz?rev=3cbca256ee8863a030e9e37a8be1001975e2bdfe#3cbca256ee8863a030e9e37a8be1001975e2bdfe" +source = "git+https://github.com/kgoedecke/blitz?rev=35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9#35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9" dependencies = [ "accesskit", "anyrender", @@ -243,7 +243,7 @@ dependencies = [ "color", "cssparser", "cursor-icon", - "debug_timer 0.1.3 (git+https://github.com/kgoedecke/blitz?rev=3cbca256ee8863a030e9e37a8be1001975e2bdfe)", + "debug_timer 0.1.3 (git+https://github.com/kgoedecke/blitz?rev=35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9)", "euclid", "html-escape", "image", @@ -277,7 +277,7 @@ dependencies = [ [[package]] name = "blitz-html" version = "0.3.0-beta.2" -source = "git+https://github.com/kgoedecke/blitz?rev=3cbca256ee8863a030e9e37a8be1001975e2bdfe#3cbca256ee8863a030e9e37a8be1001975e2bdfe" +source = "git+https://github.com/kgoedecke/blitz?rev=35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9#35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9" dependencies = [ "blitz-dom", "blitz-traits", @@ -288,7 +288,7 @@ dependencies = [ [[package]] name = "blitz-net" version = "0.3.0-beta.2" -source = "git+https://github.com/kgoedecke/blitz?rev=3cbca256ee8863a030e9e37a8be1001975e2bdfe#3cbca256ee8863a030e9e37a8be1001975e2bdfe" +source = "git+https://github.com/kgoedecke/blitz?rev=35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9#35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9" dependencies = [ "blitz-traits", "data-url", @@ -304,7 +304,7 @@ dependencies = [ [[package]] name = "blitz-paint" version = "0.3.0-beta.2" -source = "git+https://github.com/kgoedecke/blitz?rev=3cbca256ee8863a030e9e37a8be1001975e2bdfe#3cbca256ee8863a030e9e37a8be1001975e2bdfe" +source = "git+https://github.com/kgoedecke/blitz?rev=35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9#35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9" dependencies = [ "anyrender", "anyrender_svg", @@ -327,7 +327,7 @@ dependencies = [ [[package]] name = "blitz-traits" version = "0.3.0-beta.2" -source = "git+https://github.com/kgoedecke/blitz?rev=3cbca256ee8863a030e9e37a8be1001975e2bdfe#3cbca256ee8863a030e9e37a8be1001975e2bdfe" +source = "git+https://github.com/kgoedecke/blitz?rev=35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9#35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9" dependencies = [ "atomic_refcell", "bitflags 2.13.2", @@ -756,7 +756,7 @@ checksum = "da220af51a1a335e9a930beaaef53d261e41ea9eecfb3d973a3ddae1a7284b9c" [[package]] name = "debug_timer" version = "0.1.3" -source = "git+https://github.com/kgoedecke/blitz?rev=3cbca256ee8863a030e9e37a8be1001975e2bdfe#3cbca256ee8863a030e9e37a8be1001975e2bdfe" +source = "git+https://github.com/kgoedecke/blitz?rev=35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9#35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9" [[package]] name = "deranged" @@ -928,7 +928,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -2804,7 +2804,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -2878,7 +2878,7 @@ dependencies = [ [[package]] name = "selectors" version = "0.41.0" -source = "git+https://github.com/kgoedecke/stylo?rev=f247bcfd8e380832e02c9c2b69d83bd5ee59bb43#f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" +source = "git+https://github.com/kgoedecke/stylo?rev=39c0595f1a3c0ecac30f045bc440ee09e2d46a2a#39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" dependencies = [ "bitflags 2.13.2", "cssparser", @@ -2966,7 +2966,7 @@ dependencies = [ [[package]] name = "servo_arc" version = "0.5.0" -source = "git+https://github.com/kgoedecke/stylo?rev=f247bcfd8e380832e02c9c2b69d83bd5ee59bb43#f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" +source = "git+https://github.com/kgoedecke/stylo?rev=39c0595f1a3c0ecac30f045bc440ee09e2d46a2a#39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" dependencies = [ "serde", "stable_deref_trait", @@ -3212,7 +3212,7 @@ dependencies = [ [[package]] name = "stylo" version = "0.22.0" -source = "git+https://github.com/kgoedecke/stylo?rev=f247bcfd8e380832e02c9c2b69d83bd5ee59bb43#f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" +source = "git+https://github.com/kgoedecke/stylo?rev=39c0595f1a3c0ecac30f045bc440ee09e2d46a2a#39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" dependencies = [ "app_units", "arrayvec", @@ -3268,7 +3268,7 @@ dependencies = [ [[package]] name = "stylo_atoms" version = "0.22.0" -source = "git+https://github.com/kgoedecke/stylo?rev=f247bcfd8e380832e02c9c2b69d83bd5ee59bb43#f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" +source = "git+https://github.com/kgoedecke/stylo?rev=39c0595f1a3c0ecac30f045bc440ee09e2d46a2a#39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" dependencies = [ "string_cache", "string_cache_codegen", @@ -3277,7 +3277,7 @@ dependencies = [ [[package]] name = "stylo_derive" version = "0.22.0" -source = "git+https://github.com/kgoedecke/stylo?rev=f247bcfd8e380832e02c9c2b69d83bd5ee59bb43#f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" +source = "git+https://github.com/kgoedecke/stylo?rev=39c0595f1a3c0ecac30f045bc440ee09e2d46a2a#39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" dependencies = [ "darling", "proc-macro2", @@ -3289,7 +3289,7 @@ dependencies = [ [[package]] name = "stylo_dom" version = "0.22.0" -source = "git+https://github.com/kgoedecke/stylo?rev=f247bcfd8e380832e02c9c2b69d83bd5ee59bb43#f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" +source = "git+https://github.com/kgoedecke/stylo?rev=39c0595f1a3c0ecac30f045bc440ee09e2d46a2a#39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" dependencies = [ "bitflags 2.13.2", "stylo_malloc_size_of", @@ -3298,7 +3298,7 @@ dependencies = [ [[package]] name = "stylo_malloc_size_of" version = "0.22.0" -source = "git+https://github.com/kgoedecke/stylo?rev=f247bcfd8e380832e02c9c2b69d83bd5ee59bb43#f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" +source = "git+https://github.com/kgoedecke/stylo?rev=39c0595f1a3c0ecac30f045bc440ee09e2d46a2a#39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" dependencies = [ "app_units", "cssparser", @@ -3316,7 +3316,7 @@ dependencies = [ [[package]] name = "stylo_static_prefs" version = "0.22.0" -source = "git+https://github.com/kgoedecke/stylo?rev=f247bcfd8e380832e02c9c2b69d83bd5ee59bb43#f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" +source = "git+https://github.com/kgoedecke/stylo?rev=39c0595f1a3c0ecac30f045bc440ee09e2d46a2a#39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" dependencies = [ "toml", ] @@ -3324,7 +3324,7 @@ dependencies = [ [[package]] name = "stylo_taffy" version = "0.3.0-beta.2" -source = "git+https://github.com/kgoedecke/blitz?rev=3cbca256ee8863a030e9e37a8be1001975e2bdfe#3cbca256ee8863a030e9e37a8be1001975e2bdfe" +source = "git+https://github.com/kgoedecke/blitz?rev=35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9#35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9" dependencies = [ "bitflags 2.13.2", "stylo", @@ -3335,7 +3335,7 @@ dependencies = [ [[package]] name = "stylo_traits" version = "0.22.0" -source = "git+https://github.com/kgoedecke/stylo?rev=f247bcfd8e380832e02c9c2b69d83bd5ee59bb43#f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" +source = "git+https://github.com/kgoedecke/stylo?rev=39c0595f1a3c0ecac30f045bc440ee09e2d46a2a#39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" dependencies = [ "app_units", "bitflags 2.13.2", @@ -3447,7 +3447,7 @@ dependencies = [ "getrandom", "once_cell", "rustix", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -3590,7 +3590,7 @@ checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" [[package]] name = "to_shmem" version = "0.6.0" -source = "git+https://github.com/kgoedecke/stylo?rev=f247bcfd8e380832e02c9c2b69d83bd5ee59bb43#f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" +source = "git+https://github.com/kgoedecke/stylo?rev=39c0595f1a3c0ecac30f045bc440ee09e2d46a2a#39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" dependencies = [ "cssparser", "servo_arc", @@ -3603,7 +3603,7 @@ dependencies = [ [[package]] name = "to_shmem_derive" version = "0.2.0" -source = "git+https://github.com/kgoedecke/stylo?rev=f247bcfd8e380832e02c9c2b69d83bd5ee59bb43#f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" +source = "git+https://github.com/kgoedecke/stylo?rev=39c0595f1a3c0ecac30f045bc440ee09e2d46a2a#39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" dependencies = [ "darling", "proc-macro2", @@ -4085,7 +4085,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] diff --git a/ios/BlitzKit/rust/Cargo.toml b/ios/BlitzKit/rust/Cargo.toml index bb5f564c8..9d4c45bec 100644 --- a/ios/BlitzKit/rust/Cargo.toml +++ b/ios/BlitzKit/rust/Cargo.toml @@ -11,14 +11,14 @@ crate-type = ["staticlib", "rlib"] [dependencies] # Blitz from the `doop` branch of kgoedecke/blitz: DioxusLabs/blitz at 0f60502 plus our # rendering fixes (inline SVG, web fonts, placeholders, filters, opt-in prefers-reduced-motion), -# each also sent upstream. +# each also sent upstream, and a scale change that starts no CSS transitions (fork only for now). # Update by rebasing that branch and bumping the rev here. -blitz-dom = { git = "https://github.com/kgoedecke/blitz", rev = "3cbca256ee8863a030e9e37a8be1001975e2bdfe", default-features = false, features = ["default"] } +blitz-dom = { git = "https://github.com/kgoedecke/blitz", rev = "35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9", default-features = false, features = ["default"] } # Same taffy as the pinned Blitz workspace: the bridge re-rounds layout on the device-pixel grid. taffy = { git = "https://github.com/DioxusLabs/taffy", rev = "49152ca29664f9687c714c7732d88ff07d62110a", default-features = false, features = ["std", "content_size"] } -blitz-html = { git = "https://github.com/kgoedecke/blitz", rev = "3cbca256ee8863a030e9e37a8be1001975e2bdfe", default-features = false } -blitz-paint = { git = "https://github.com/kgoedecke/blitz", rev = "3cbca256ee8863a030e9e37a8be1001975e2bdfe", default-features = false, features = ["svg"] } -blitz-traits = { git = "https://github.com/kgoedecke/blitz", rev = "3cbca256ee8863a030e9e37a8be1001975e2bdfe", default-features = false } +blitz-html = { git = "https://github.com/kgoedecke/blitz", rev = "35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9", default-features = false } +blitz-paint = { git = "https://github.com/kgoedecke/blitz", rev = "35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9", default-features = false, features = ["svg"] } +blitz-traits = { git = "https://github.com/kgoedecke/blitz", rev = "35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9", default-features = false } # Same parley revision as the pinned Blitz commit, for one shared font context. parley = { git = "https://github.com/linebender/parley", rev = "718dcb721941fd8e72128833122d31f5a4e80504", default-features = false, features = ["std", "system"] } anyrender = "0.14" @@ -39,32 +39,33 @@ url = "2" # panics there; documents still retain downloaded resources in memory. Keep the # existing disk cache on Apple targets, without changing their feature set. [target.'cfg(not(target_os = "android"))'.dependencies] -blitz-net = { git = "https://github.com/kgoedecke/blitz", rev = "3cbca256ee8863a030e9e37a8be1001975e2bdfe", default-features = false, features = ["cache"] } +blitz-net = { git = "https://github.com/kgoedecke/blitz", rev = "35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9", default-features = false, features = ["cache"] } [target.'cfg(target_os = "android")'.dependencies] -blitz-net = { git = "https://github.com/kgoedecke/blitz", rev = "3cbca256ee8863a030e9e37a8be1001975e2bdfe", default-features = false } +blitz-net = { git = "https://github.com/kgoedecke/blitz", rev = "35a984ff9958ad24bd7ca4f7b0d03b8a8d16e0a9", default-features = false } # Local fixes; see the header of each vendored Cargo.toml. # Stylo (the `stylo` crates below) from the `doop` branch of kgoedecke/stylo: 0.22.0 with # `background-clip: text` and `-webkit-text-fill-color` parsed in Servo builds, and the -# `prefers-reduced-motion` media feature. +# `prefers-reduced-motion` media feature, and `TraversalFlags::DeviceChangeOnly` (a restyle for a +# new device pixel ratio starts no transitions). # anyrender from the `doop` branch of kgoedecke/anyrender: the published 0.14 / anyrender_skia # 0.12 commit plus the variable-font fix (DioxusLabs/anyrender#128). Both crates come from the # fork so that blitz-paint and the Skia backend share one `anyrender`. [patch.crates-io] anyrender = { git = "https://github.com/kgoedecke/anyrender", rev = "229216b1c86c13b8ba00eaf8d274d42f4ce91d80" } anyrender_skia = { git = "https://github.com/kgoedecke/anyrender", rev = "229216b1c86c13b8ba00eaf8d274d42f4ce91d80" } -stylo = { git = "https://github.com/kgoedecke/stylo", rev = "f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" } -stylo_traits = { git = "https://github.com/kgoedecke/stylo", rev = "f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" } -stylo_atoms = { git = "https://github.com/kgoedecke/stylo", rev = "f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" } -stylo_dom = { git = "https://github.com/kgoedecke/stylo", rev = "f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" } -stylo_static_prefs = { git = "https://github.com/kgoedecke/stylo", rev = "f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" } -stylo_derive = { git = "https://github.com/kgoedecke/stylo", rev = "f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" } -stylo_malloc_size_of = { git = "https://github.com/kgoedecke/stylo", rev = "f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" } -selectors = { git = "https://github.com/kgoedecke/stylo", rev = "f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" } -servo_arc = { git = "https://github.com/kgoedecke/stylo", rev = "f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" } -to_shmem = { git = "https://github.com/kgoedecke/stylo", rev = "f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" } -to_shmem_derive = { git = "https://github.com/kgoedecke/stylo", rev = "f247bcfd8e380832e02c9c2b69d83bd5ee59bb43" } +stylo = { git = "https://github.com/kgoedecke/stylo", rev = "39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" } +stylo_traits = { git = "https://github.com/kgoedecke/stylo", rev = "39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" } +stylo_atoms = { git = "https://github.com/kgoedecke/stylo", rev = "39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" } +stylo_dom = { git = "https://github.com/kgoedecke/stylo", rev = "39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" } +stylo_static_prefs = { git = "https://github.com/kgoedecke/stylo", rev = "39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" } +stylo_derive = { git = "https://github.com/kgoedecke/stylo", rev = "39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" } +stylo_malloc_size_of = { git = "https://github.com/kgoedecke/stylo", rev = "39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" } +selectors = { git = "https://github.com/kgoedecke/stylo", rev = "39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" } +servo_arc = { git = "https://github.com/kgoedecke/stylo", rev = "39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" } +to_shmem = { git = "https://github.com/kgoedecke/stylo", rev = "39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" } +to_shmem_derive = { git = "https://github.com/kgoedecke/stylo", rev = "39c0595f1a3c0ecac30f045bc440ee09e2d46a2a" } [features] default = ["skia"] diff --git a/ios/BlitzKit/rust/tests/rescale_transitions.rs b/ios/BlitzKit/rust/tests/rescale_transitions.rs new file mode 100644 index 000000000..ffaeff251 --- /dev/null +++ b/ios/BlitzKit/rust/tests/rescale_transitions.rs @@ -0,0 +1,83 @@ +//! The canvas paints one document at two scales, a base bitmap and a zoomed tile, +//! switching back and forth. A new scale recomputes lengths snapped to device pixels +//! (a 1px border is about 2 CSS px at 0.51 and 1 px at 5.63); that must not start CSS +//! transitions, or every `transition: all` box animates between the two widths and +//! the frame jitters, reporting itself as animating forever. +use std::ffi::CString; + +use doopblitz::*; + +const W: u32 = 400; +const H: u32 = 300; + +fn base(doc: *mut Doc, scale: f32, time: f64) { + let (mut w, mut h, mut len) = (0u32, 0u32, 0usize); + doopblitz_doc_set_viewport(doc, W, H, scale); + let buf = doopblitz_doc_render_at(doc, time, &mut w, &mut h, &mut len); + doopblitz_buffer_free(buf, len); +} + +/// The base bitmap at `scale` and `time`, as RGBA bytes. +fn base_pixels(doc: *mut Doc, scale: f32, time: f64) -> Vec { + let (mut w, mut h, mut len) = (0u32, 0u32, 0usize); + doopblitz_doc_set_viewport(doc, W, H, scale); + let buf = doopblitz_doc_render_at(doc, time, &mut w, &mut h, &mut len); + assert!(!buf.is_null()); + let pixels = unsafe { std::slice::from_raw_parts(buf, len) }.to_vec(); + doopblitz_buffer_free(buf, len); + pixels +} + +fn tile(doc: *mut Doc, scale: f32, time: f64) { + let (mut w, mut h, mut len) = (0u32, 0u32, 0usize); + let buf = doopblitz_doc_render_region_at(doc, time, scale, 0.0, 0.0, 200.0, 100.0, &mut w, &mut h, &mut len); + doopblitz_buffer_free(buf, len); +} + +fn open(body: &str) -> *mut Doc { + let html = CString::new(format!("{body}")).unwrap(); + let url = CString::new("https://doop.design/").unwrap(); + doopblitz_doc_new(html.as_ptr(), url.as_ptr(), W, H, 0.51) +} + +#[test] +fn switching_between_base_and_tile_scales_starts_no_transitions() { + let doc = open(r#"
Card
"#); + let mut time = 1.0; + base(doc, 0.51, time); + assert!(!doopblitz_doc_is_animating(doc), "a static page is not animating"); + for _ in 0..3 { + time += 0.05; + tile(doc, 5.63, time); + assert!(!doopblitz_doc_is_animating(doc), "a tile at a new scale started a transition"); + time += 0.05; + base(doc, 0.51, time); + assert!(!doopblitz_doc_is_animating(doc), "the base at its old scale started a transition"); + } + doopblitz_doc_free(doc); +} + +#[test] +fn keyframe_animations_keep_running_across_scale_changes() { + // Two copies of a spinning page; only `switched` has tiles painted between its + // base frames. Each base frame must show the animation moved on, and match the + // copy that never changed scale, so it neither froze nor restarted. + let page = r#"

spinning

"#; + let (switched, steady) = (open(page), open(page)); + let mut time = 1.0; + let mut previous = base_pixels(switched, 0.51, time); + assert_eq!(previous, base_pixels(steady, 0.51, time)); + assert!(doopblitz_doc_is_animating(switched)); + for _ in 0..3 { + tile(switched, 5.63, time + 0.05); + assert!(doopblitz_doc_is_animating(switched), "a scale change stopped a running animation"); + time += 0.1; + let frame = base_pixels(switched, 0.51, time); + assert!(doopblitz_doc_is_animating(switched), "a scale change stopped a running animation"); + assert_ne!(frame, previous, "the animation froze across a scale change"); + assert!(frame == base_pixels(steady, 0.51, time), "a scale change restarted or shifted the animation"); + previous = frame; + } + doopblitz_doc_free(switched); + doopblitz_doc_free(steady); +} diff --git a/ios/Doop/Blitz/BlitzCanvasView.swift b/ios/Doop/Blitz/BlitzCanvasView.swift index 8f02f54cc..cd8921739 100644 --- a/ios/Doop/Blitz/BlitzCanvasView.swift +++ b/ios/Doop/Blitz/BlitzCanvasView.swift @@ -50,7 +50,7 @@ final class CanvasView: UIView, UIGestureRecognizerDelegate { #endif private static let minZoom: CGFloat = 0.03 - private static let maxZoom: CGFloat = 4 + static let maxZoom: CGFloat = 4 init(model: CanvasModel) { self.model = model @@ -381,9 +381,17 @@ final class CanvasView: UIView, UIGestureRecognizerDelegate { zoom = max(Self.minZoom, min(1, available.width / CGFloat(maxX - minX), available.height / CGFloat(maxY - minY))) offset = CGPoint(x: viewport.midX - CGFloat(maxX + minX) * zoom / 2, y: viewport.midY - CGFloat(maxY + minY) * zoom / 2) + restOnPixels() applyTransform() } + /// Rest the camera offset on whole device pixels; with each frame layer snapped + /// at the same density, bitmaps are never resampled by a fraction of a pixel. + private func restOnPixels() { + let s = UIScreen.main.scale + offset = CGPoint(x: (offset.x * s).rounded() / s, y: (offset.y * s).rounded() / s) + } + /// Keep fitted designs clear of the right rail and bottom prompt, with room /// at the top for a title and an agent chip row stacked above it. private var unobscuredViewport: CGRect { @@ -397,9 +405,7 @@ final class CanvasView: UIView, UIGestureRecognizerDelegate { relayout?.cancel() let work = DispatchWorkItem { [weak self] in guard let self else { return } - // Rest on whole device pixels so bitmaps are never resampled by a fraction. - let s = UIScreen.main.scale - self.offset = CGPoint(x: (self.offset.x * s).rounded() / s, y: (self.offset.y * s).rounded() / s) + self.restOnPixels() self.applyTransform() self.rerenderVisible() } @@ -695,13 +701,22 @@ private final class FrameLayer { private var tilePending: (CGRect, CGFloat)? /// Bumped by `clearTile()`: a tile painted for an older request is dropped. private var tileVersion = 0 - /// Tiles cover about a screen, so density can go well past the base cap. - private static let maxTileDensity: CGFloat = 8 + /// Tiles cover about a screen, so density can go well past the base cap: up to + /// screen density at the canvas's deepest zoom, so a tile is never stretched. + private static let maxTileDensity: CGFloat = CanvasView.maxZoom * UIScreen.main.scale /// Playback repaints only the on-screen part of the frame. Steps are self-paced - /// by the paint; the density is chosen so one step stays near `playbackPixels` - /// (about 16 ms on Skia), which keeps motion smooth at any zoom. + /// by the paint. The budget is one screen of device pixels plus the step's 10% + /// margin, so a frame playing on screen paints at screen density (the static + /// tile's density): a lower playback density rounded the layout to a coarser grid + /// and blurred it, and alternating the two made the frame jump by a pixel or two. private static let animationInterval: Double = 1.0 / 60 - private static let playbackPixels: CGFloat = 550_000 + private static let playbackPixels: CGFloat = { + let screen = UIScreen.main.nativeBounds + return screen.width * screen.height * 1.25 + }() + /// When this frame last painted a playback step; a static tile stays out of its way. + private var lastPlaybackAt: CFTimeInterval = 0 + private var playing: Bool { animating && CACurrentMediaTime() - lastPlaybackAt < 0.5 } /// The last camera handed to `setLOD`, so a tile can be refreshed when playback ends. private var lastView: CGRect? private var lastLOD: CGFloat = 0 @@ -796,9 +811,7 @@ private final class FrameLayer { if newRect != rect { let resized = newRect.size != rect.size rect = newRect - CATransaction.begin(); CATransaction.setDisableActions(true) - layer.frame = rect - CATransaction.commit() + placeLayer() if resized { lastChange = CACurrentMediaTime() let size = rect.size, scale = Float(clamp(targetScale)) @@ -831,8 +844,29 @@ private final class FrameLayer { /// Local drag preview; the model is updated when the drag ends. func move(to origin: CGPoint) { rect.origin = origin + placeLayer() + } + + /// Screen pixels per CSS pixel at the last settled camera; 0 before the first. + private var pixelDensity: CGFloat = 0 + + /// Put the layer at `rect`, its origin snapped to the device-pixel grid at the + /// settled camera's density. The camera offset rests on whole device pixels too, + /// so the bitmap's pixels (and a tile's, painted at that density) land one on one + /// on screen pixels; otherwise the linear filter blurs every glyph by up to half a pixel. + /// The size is snapped too, to the whole pixels the engine rounds the bitmap to + /// (a 401 px frame at density 1.5 is a 602 px bitmap), so it is not squeezed into + /// 601.5 screen pixels; the frame's own geometry stays `rect`. + private func placeLayer() { + var frame = rect + if pixelDensity > 0 { + let snap = { (v: CGFloat) in (v * self.pixelDensity).rounded() / self.pixelDensity } + frame = CGRect(x: snap(rect.minX), y: snap(rect.minY), + width: max(1, (rect.width * pixelDensity).rounded()) / pixelDensity, + height: max(1, (rect.height * pixelDensity).rounded()) / pixelDensity) + } CATransaction.begin(); CATransaction.setDisableActions(true) - layer.frame = rect + layer.frame = frame CATransaction.commit() } @@ -842,6 +876,8 @@ private final class FrameLayer { targetScale = visible ? clamp(lod) : min(currentScale == 0 ? Self.parkedScale : currentScale, Self.parkedScale) lastView = visible ? viewportInFrame : nil lastLOD = lod + pixelDensity = lod + placeLayer() refreshTile() #if DEBUG if StressDriver.enabled, visible { @@ -889,8 +925,9 @@ private final class FrameLayer { func tickAnimation(time: Double, viewportInFrame: CGRect, lod: CGFloat) { guard animating, document != nil, !tileRendering, time - lastAnimationStep >= Self.animationInterval else { return } lastAnimationStep = time - let area = viewportInFrame.width * viewportInFrame.height * 1.21 - let density = max(0.25, min(lod, (Self.playbackPixels / max(1, area)).squareRoot())) + lastPlaybackAt = CACurrentMediaTime() + let area = viewportInFrame.width * viewportInFrame.height * 1.21 * lod * lod + let density = max(0.25, min(lod, Self.maxTileDensity, lod * (Self.playbackPixels / max(1, area)).squareRoot())) requestTile(region: tileRegion(around: viewportInFrame, margin: 0.1, density: density), density: density, time: time, force: true) } @@ -899,6 +936,9 @@ private final class FrameLayer { /// Deep zoom: the base bitmap cannot reach screen density, so paint just the /// part on screen as a tile over it, at (close to) screen density. private func refreshTile() { + // A playing frame's tile belongs to the playback loop: a static tile painted + // between its steps, at another density and an older pose, made it jump. + guard !playing else { return } if let view = lastView, lastLOD > targetScale + 0.05 { let density = min(lastLOD, Self.maxTileDensity) requestTile(region: tileRegion(around: view, margin: 0.3, density: density), density: density, time: animationTime) @@ -950,7 +990,9 @@ private final class FrameLayer { self.tileRegion = region self.tileDensity = density } - if self.animating, !stillAnimating { + // Only a playback step (painted at the current time) can tell that the + // animation ran out; a static tile is painted at an older pose. + if force, self.animating, !stillAnimating { // The animation ran out: paint the base at its final pose; that // render then refreshes or drops the tile, so nothing jumps back. self.animating = false diff --git a/ios/README.md b/ios/README.md index 6b167a168..696485c10 100644 --- a/ios/README.md +++ b/ios/README.md @@ -51,10 +51,22 @@ HTML/CSS engine (Stylo + Taffy + Parley), compiled into the app as a static libr - **Deep zoom tiles**: a base bitmap is capped at 3 bitmap pixels per CSS pixel and about two screens of pixels. When the screen density exceeds what the base bitmap holds, the part of the frame on screen (plus a 30% margin) is painted as a tile at - up to 8 bitmap pixels per CSS pixel and composited over the base, so text stays - sharp at any zoom at roughly one screen of pixels per paint. Tiles refresh when a - gesture settles and when the frame's HTML changes; a tiled frame holds its - animations still. + screen density (up to 12 bitmap pixels per CSS pixel at 400% on a 3x screen) and + composited over the base, so text stays sharp at any zoom at roughly one screen of + pixels per paint. Tiles refresh when a gesture settles and when the frame's HTML + changes; a tiled frame holds its animations still. +- **Pixel alignment**: Core Animation stretches each bitmap with a linear filter, so + a bitmap is only sharp when its pixels land on screen pixels. When the camera + settles its offset rests on whole device pixels (the first fit included) and each + frame layer's origin is snapped to the device-pixel grid at the camera's density; + a frame half a pixel off blurred every glyph (55-80% of full sharpness at most + zooms, only 100% and 200% were crisp). +- **Scale changes start no transitions**: base and tile paint one document at + different scales, and a new scale recomputes lengths snapped to device pixels (a 1px + border is about 2 CSS px at 0.5x). The Blitz and Stylo forks restyle for a scale + change with `TraversalFlags::DeviceChangeOnly`, which starts no CSS transitions; + otherwise every `transition: all` box animated between the two widths, the frame + jittered by a pixel or two and repainted forever. `rust/tests/rescale_transitions.rs`. - **SVG**: `blitz-paint` is pulled in with `default-features = false` so the bridge controls what it links; its `svg` feature must stay on, or neither inline `` elements nor SVG images (``, backgrounds) are painted at all. @@ -94,11 +106,14 @@ HTML/CSS engine (Stylo + Taffy + Parley), compiled into the app as a static libr - **CSS animations**: a frame whose document reports running animations or transitions (`doopblitz_doc_is_animating`) is played by a `CADisplayLink` while it is on screen: each step paints only the on-screen part of the frame as a tile - (`doopblitz_doc_render_region_at`) at a density chosen so one step stays near - 550k pixels, about 10-20 ms on Skia, which gives 30-40 steps a second at any - zoom. Playback pauses during gestures and for frames narrower than 100 pt, at - most two frames play at once, and when an animation ends the tile is repainted - at the density the camera wants. Base bitmaps keep the last animation pose. + (`doopblitz_doc_render_region_at`) at screen density, within a budget of one + screen of device pixels per step (about 15 ms on an iPhone 15 Pro Max). While a + frame plays, its tile is the playback tile alone: a static tile at another density + and an older pose between steps made it jump, and only a playback step decides + that the animation ended. Playback pauses during gestures and for frames narrower + than 100 pt, at most two frames play at once, and when an animation ends the tile + is repainted at the density the camera wants. Base bitmaps keep the last animation + pose. - **Element inspection**: tapping inside any frame selects it and hit tests the Blitz DOM automatically, without a separate mode. A compact, icon-only glass action bar above the prompt offers Copy, Paste, Duplicate, Delete, Comment and Export for diff --git a/server/actions.ts b/server/actions.ts index 5723f9095..d9b398f39 100644 --- a/server/actions.ts +++ b/server/actions.ts @@ -1,3 +1,4 @@ +import type { ResolvedMentions } from '../shared/personMentions.ts' import { nanoid } from 'nanoid' import { indexOfAscii, lastIndexOfAscii } from '../shared/asciiSearch.ts' import { env } from './env.ts' @@ -40,6 +41,7 @@ import { hasElementId, stampElementId } from './elementIds.ts' import { decodeEscapedHtml, looksEscapedHtml, repairEscapedHtml } from './escapedHtml.ts' import { forgetLibrary } from './componentLibrary.ts' import { withCanvasFaces, withCanvasFacesMidStream } from './canvasFaces.ts' +import { EMBEDDED_MIN_LENGTH } from './inlineData.ts' import { MAX_TOKENS, MAX_TOKEN_DESCRIPTION, @@ -837,7 +839,7 @@ async function frameAnchor(frame: Frame, input: FrameAnchorInput, by: string): P export async function addElementComment( frameId: string, - input: FrameAnchorInput & { text: string }, + input: FrameAnchorInput & { text: string; mentions?: ResolvedMentions }, from: string, fromUserId?: string, ): Promise { @@ -846,7 +848,7 @@ export async function addElementComment( const anchor = await frameAnchor(frame, input, from) /* a frame deleted while its element was being stamped takes no comment */ if (!store.getFrame(frameId)) return undefined - return postComment(frame.canvasId, anchor, input.text, from, fromUserId) + return postComment(frame.canvasId, anchor, input.text, from, fromUserId, 'user', undefined, input.mentions) } /** The anchor as it is written onto a comment; what the anchor does not @@ -1010,14 +1012,23 @@ export const moveComment = atomic(async function moveComment( * between frames, or a spot where something should go. */ export function addCanvasComment( canvasId: string, - input: { pageId: string; x: number; y: number; text: string }, + input: { pageId: string; x: number; y: number; text: string; mentions?: ResolvedMentions }, from: string, fromUserId?: string, ): ElementComment | undefined { const canvas = store.getCanvas(canvasId) if (!canvas || !canvasPages(canvas).some((page) => page.id === input.pageId)) return undefined if (!Number.isFinite(input.x) || !Number.isFinite(input.y)) return undefined - return postComment(canvasId, { pageId: input.pageId, x: input.x, y: input.y }, input.text, from, fromUserId) + return postComment( + canvasId, + { pageId: input.pageId, x: input.x, y: input.y }, + input.text, + from, + fromUserId, + 'user', + undefined, + input.mentions, + ) } /** Reply inside a thread: the reply inherits the root comment's anchor (its @@ -1029,12 +1040,13 @@ export function replyToComment( from: string, fromUserId?: string, kind: ActorKind = 'user', + mentions?: ResolvedMentions, ): ElementComment | undefined { const open = openThread(commentId) if (!open) return undefined const anchor = replyAnchor(open) if (!anchor) return undefined - return postComment(open.root.canvasId, anchor, text, from, fromUserId, kind, open.root.id) + return postComment(open.root.canvasId, anchor, text, from, fromUserId, kind, open.root.id, mentions) } function replyAnchor({ root, frame }: { root: ElementComment; frame?: Frame }): CommentAnchor | undefined { @@ -1074,11 +1086,14 @@ function postComment( fromUserId?: string, kind: ActorKind = 'user', parentId?: string, + /** the people the text @mentions, read by the caller (server/canvasPeople.ts) */ + mentions?: ResolvedMentions, ): ElementComment | undefined { const clean = text.trim() if (!clean) return undefined - /* @Doop, @brand, @a11y… — whichever resident agent is mentioned picks it up */ - const mentioned = mentionedRole(clean, canvasRoster(canvasId)) + /* @Doop, @brand, @a11y… — whichever resident agent is mentioned picks it + up; a person's name (`@Brand Smith`) is not an agent's */ + const mentioned = mentionedRole(mentions?.roleText ?? clean, canvasRoster(canvasId)) const list = commentLog.get(canvasId) ?? [] /* strictly increasing per canvas: thread order is reconstructed from `at` after a restart, so two messages must never share a timestamp */ @@ -1120,6 +1135,7 @@ function postComment( comment, frame, actorKind: kind, + ...(mentions?.ids.length ? { mentions: mentions.ids } : {}), }) return comment } @@ -1793,12 +1809,15 @@ interface StreamState { /** the frame's HTML before the opening chunk replaced it: what a later chunk * may carry over (server/inlineData.ts compares against it) */ base: string - /** the end of the agent's last chunk as it sent it, before components expanded: - * enough to catch a data: URI prefix split across two chunks */ + /** the end of the agent's stream as it sent it, before components expanded: what the + * next chunk is joined to, so base64 split across chunks is seen whole */ tail: string } -const STREAM_TAIL_CHARS = 256 +/* enough for a data: URI's prefix split across two chunks, and for a block of base64 text sent + in pieces: a run is refused once it reaches EMBEDDED_MIN_LENGTH (server/inlineData.ts), so one + still growing at the end of the stream is shorter than that and is held here whole */ +const STREAM_TAIL_CHARS = Math.max(256, EMBEDDED_MIN_LENGTH) const streams = new Map() // frameId -> state diff --git a/server/canvasPeople.ts b/server/canvasPeople.ts new file mode 100644 index 000000000..450861304 --- /dev/null +++ b/server/canvasPeople.ts @@ -0,0 +1,91 @@ +import { and, eq, inArray, or, isNull } from 'drizzle-orm' +import { db } from './db/index.ts' +import * as authSchema from './db/auth-schema.ts' +import { workspaceMemberIds } from './workspaces.ts' +import { avatarUrl } from '../shared/avatar.ts' +import { resolvePersonMentions, type ResolvedMentions } from '../shared/personMentions.ts' +import type { Canvas, ElementComment } from '../shared/types.ts' +import { commentThread } from './actions.ts' + +/** The people a comment on this canvas may @mention: everyone who has it for + * good (the owner, invited members, the members of its workspace). Share-link + * visitors are not listed: a link is not a membership, and their names would + * reach everyone else holding it. */ +export function mentionableIds(canvas: Canvas): string[] { + const ids = new Set() + if (canvas.ownerId) ids.add(canvas.ownerId) + for (const id of canvas.memberIds ?? []) ids.add(id) + if (canvas.workspaceId) for (const id of workspaceMemberIds(canvas.workspaceId)) ids.add(id) + return [...ids] +} + +export interface CanvasPerson { + id: string + name: string + image?: string +} + +/** Those people with their names and faces, banned accounts left out. */ +export function mentionablePeople(canvas: Canvas): Promise { + return peopleByIds(mentionableIds(canvas)) +} + +async function peopleByIds(ids: string[]): Promise { + if (!ids.length) return [] + const rows = await db + .select({ id: authSchema.user.id, name: authSchema.user.name, image: authSchema.user.image }) + .from(authSchema.user) + .where(and(inArray(authSchema.user.id, ids), or(isNull(authSchema.user.banned), eq(authSchema.user.banned, false)))) + const byId = new Map(rows.map((r) => [r.id, r])) + return ids.flatMap((id) => { + const row = byId.get(id) + if (!row) return [] + const image = avatarUrl(row.image) + return [{ id, name: row.name, ...(image ? { image } : {}) }] + }) +} + +/** Who a comment's text @mentions: the canvas's people and whoever already + * wrote in the thread (`authorIds`), each read by name against all of them + * before anything else is decided, so a name is never handed to a shorter + * one because its owner turned email off. `picked` is what the editor's + * picker chose, for a name several people share (an unknown id is ignored). + * Who is then actually told (the author, opt-outs, access) is the + * notifier's business. */ +export async function resolveCommentMentions( + canvas: Canvas, + text: string, + { authorIds = [], picked }: { authorIds?: readonly string[]; picked?: unknown } = {}, +): Promise { + if (!text.includes('@')) return { ids: [], roleText: text } + try { + const people = await peopleByIds([...new Set([...mentionableIds(canvas), ...authorIds])]) + return resolvePersonMentions(text, people, pickedIds(picked)) + } catch (err) { + /* the comment still posts; nobody is emailed about a mention */ + console.error(`[comments] could not read the people on ${canvas.id}`, err) + return { ids: [], roleText: text } + } +} + +/** Everyone a comment on this canvas may @mention, the thread's authors + * included; none when they cannot be read (nobody is then emailed). */ +export async function commentPeople(canvas: Canvas, authorIds: readonly string[] = []): Promise { + try { + return await peopleByIds([...new Set([...mentionableIds(canvas), ...authorIds])]) + } catch (err) { + console.error(`[comments] could not read the people on ${canvas.id}`, err) + return [] + } +} + +/** The accounts that already wrote in a comment's thread. */ +export function threadAuthorIds(comment: ElementComment): string[] { + return commentThread(comment).flatMap((c) => (c.fromUserId ? [c.fromUserId] : [])) +} + +/** The ids a request sent as its picks, if they are a short list of strings. */ +export function pickedIds(value: unknown): string[] { + if (!Array.isArray(value)) return [] + return value.filter((v): v is string => typeof v === 'string' && v.length > 0 && v.length <= 64).slice(0, 20) +} diff --git a/server/commentNotifications.ts b/server/commentNotifications.ts index e08081af2..cd270d330 100644 --- a/server/commentNotifications.ts +++ b/server/commentNotifications.ts @@ -24,6 +24,8 @@ import type { ActorKind, Canvas, ElementComment } from '../shared/types.ts' * message. Held mail is in memory only — a restart during the window drops * it, which is acceptable for a courtesy email and keeps this state-free. * + * Someone a comment @mentions is told at once instead (tellMentioned). + * * Requires SMTP (server/mailer.ts). Without it nothing is queued: an email * nobody receives is not worth logging on every comment. */ @@ -69,7 +71,52 @@ export function onCanvasEvent(canvasId: string, event: CanvasEvent): void { ...(event.frame ? { frameName: event.frame.name } : {}), actorKind: event.actorKind, } - for (const userId of recipientsFor(canvas, event.comment, event.actorKind)) queue(userId, canvasId, item) + /* someone the comment @mentions hears about it at once, on its own, and + not again in the digest; the author's own mention tells nobody */ + const author = event.actorKind === 'user' ? event.comment.fromUserId : undefined + const mentioned = (event.mentions ?? []).filter((id) => id !== author) + const told = new Set(mentioned) + for (const userId of recipientsFor(canvas, event.comment, event.actorKind)) + if (!told.has(userId)) queue(userId, canvasId, item) + if (mentioned.length) void tellMentioned(canvasId, item, mentioned) +} + +/** Email the people a comment @mentions (resolved when it was posted, + * server/canvasPeople.ts), each once. Someone who switched comment emails + * off, was banned or can no longer open the canvas is not written to. */ +async function tellMentioned(canvasId: string, item: PendingComment, ids: string[]) { + try { + const people = await mailableForComments(ids) + /* access is read after the lookup: it may have changed meanwhile */ + const canvas = store.getCanvas(canvasId) + if (!canvas) return + await Promise.all( + people + .filter((person) => canAccessCanvas(person.id, canvas)) + .map((person) => + sendMail(mentionEmail(person, canvas, item)).catch((err: unknown) => { + console.error(`[comments] mention email to ${person.id} failed`, err) + }), + ), + ) + } catch (err) { + console.error(`[comments] could not read the people mentioned on ${canvasId}`, err) + } +} + +/** The email for one comment that names the person. */ +export function mentionEmail( + person: Mailable, + canvas: Pick, + { comment, frameName }: PendingComment, +): { to: string; subject: string; text: string } { + const where = frameName ? `in ${quote(frameName)}` : 'on the canvas' + const text = comment.text.length > 600 ? `${comment.text.slice(0, 597)}…` : comment.text + return { + to: person.email, + subject: `${comment.from} mentioned you on ${quote(canvas.name)}`, + text: `Hi ${person.name || 'there'},\n\n${comment.from} mentioned you ${where}:\n\n ${quote(text.replace(/\n/g, '\n '))}\n\nReply in the thread:\n${commentLink(comment)}\n\n—\nYou get this because you collaborate on ${quote(canvas.name)}. Turn comment emails off under Settings → Your account: ${settingsLink('account')}\n`, + } } function queue(userId: string, canvasId: string, item: PendingComment) { diff --git a/server/events.ts b/server/events.ts index 75679a645..e4d628225 100644 --- a/server/events.ts +++ b/server/events.ts @@ -12,8 +12,21 @@ import type { Actor, ActorKind, AgentTask, ElementComment, Frame } from '../shar */ export type CanvasEvent = /* `frame` is an element comment's frame; a canvas comment has none */ - | { type: 'comment.created'; comment: ElementComment; frame: Frame | undefined; actorKind: ActorKind } - | { type: 'comment.replied'; comment: ElementComment; frame: Frame | undefined; actorKind: ActorKind } + /* `mentions`: the people the text @mentions (shared/personMentions.ts) */ + | { + type: 'comment.created' + comment: ElementComment + frame: Frame | undefined + actorKind: ActorKind + mentions?: string[] + } + | { + type: 'comment.replied' + comment: ElementComment + frame: Frame | undefined + actorKind: ActorKind + mentions?: string[] + } /** the root of a thread (or a lone reply) was resolved; `by` is a display name */ | { type: 'comment.resolved'; comment: ElementComment; frame: Frame | undefined; by: string } | { type: 'frame.created'; frame: Frame; actor: Actor } diff --git a/server/guide.ts b/server/guide.ts index 5787118c6..c9a6efa84 100644 --- a/server/guide.ts +++ b/server/guide.ts @@ -198,7 +198,8 @@ export const FRAME_STYLES = `- Style an element on the element itself: style=" * guide and the resident agents' system prompt. */ export const LEAN_FRAMES = `- Frames carry markup, never files. A frame is sent whole to every viewer and agent on each edit, so anything pasted into it is paid for on every round-trip. A base64 data: URI of any - kind is refused and nothing is written. Put each heavy thing where it belongs: + kind is refused and nothing is written, and so is a long block of base64 text in a script or + anywhere else (a packed bundle, a compressed data file). Put each heavy thing where it belongs: - Fonts: a family the canvas library or the hosted fonts already have is used by name alone. Any other font file goes into the library with upload_font, then is named in CSS: never an @font-face with the file inlined. @@ -213,7 +214,9 @@ export const LEAN_FRAMES = `- Frames carry markup, never files. A frame is sent ` + + it('finds a long block of it in a script, by its decoded size', () => { + expect(newInlineData(loader(packed(8000)))).toEqual([{ mime: 'embedded/base64', bytes: 6000 }]) + /* the URL-safe alphabet, and padding after it */ + expect(newInlineData(``)).toHaveLength(1) + }) + + it('leaves alone what a design writes without spaces', () => { + /* an integrity hash, a signed URL, a long id, a path */ + const hash = `` + const url = `` + const path = `` + const prose = `

${'word '.repeat(4000)}

` + for (const html of [hash, url, path, prose, loader(packed(4095))]) expect(newInlineData(html)).toEqual([]) + }) + + it('counts a data: URI once, however long its payload', () => { + const big = `` + expect(newInlineData(big)).toEqual([{ mime: 'image/png', bytes: 6750 }]) + expect(newInlineData(big + loader(packed(8000)))).toHaveLength(2) + }) + + it('takes `;base64,` for a label only on a real data: URI', () => { + /* the prefix kept apart from `data:`, to be joined when the page runs */ + const split = `` + expect(newInlineData(split)).toEqual([{ mime: 'embedded/base64', bytes: 6000 }]) + }) + + it('lets a block the frame already holds be carried over, and refuses one more', () => { + const held = loader(packed(8000)) + expect(newInlineData(held, doc(held))).toEqual([]) + const more = `H4sI${'Zz9+/0xQ'.repeat(1000)}` + expect(newInlineData(held + loader(more), doc(held))).toEqual([{ mime: 'embedded/base64', bytes: 6003 }]) + }) + + it('reads megabytes of it in one pass', () => { + const html = loader(packed(6_000_000)) + `

${'Ab3+ '.repeat(200_000)}

` + const started = performance.now() + expect(newInlineData(html)).toEqual([{ mime: 'embedded/base64', bytes: 4_500_000 }]) + /* a loose bound: one pass takes milliseconds, walking each run from every character minutes */ + expect(performance.now() - started).toBeLessThan(10_000) + }) + + it('sees a block wrapped over lines or written as joined strings', () => { + const lines = (width: number) => packed(8000).match(new RegExp(`.{1,${width}}`, 'g'))! + /* `base64 file` wraps at 76 columns, PEM at 64: atob reads through the line ends */ + expect(newInlineData(``)).toEqual([ + { mime: 'embedded/base64', bytes: 6000 }, + ]) + expect(newInlineData(``)).toHaveLength(1) + expect(newInlineData(``)).toHaveLength(1) + /* words, however many, are not lines of base64 */ + expect(newInlineData(`

${'supercalifragilistic expialidocious '.repeat(400)}

`)).toEqual([]) + }) + + it('lets a block the frame holds come back smaller or in pieces, and counts what was added to it', () => { + const block = packed(40_000) + const held = doc(loader(block)) + /* a span cut out of its middle, and one cut from each end */ + expect(newInlineData(loader(block.slice(0, 15_000) + block.slice(25_000)), held)).toEqual([]) + expect(newInlineData(loader(block.slice(3000, 30_000)), held)).toEqual([]) + /* 5,000 characters of something else put into it */ + const grown = block.slice(0, 20_000) + 'Zz9+/0xQ'.repeat(625) + block.slice(20_000) + const [added] = newInlineData(loader(grown), held) + expect(added?.mime).toBe('embedded/base64') + expect(added!.bytes).toBeGreaterThanOrEqual(3072) + expect(added!.bytes).toBeLessThan(6000) + /* and a block that only starts like the one held is all new */ + expect(newInlineData(loader(block.slice(0, 300) + 'Zz9+/0xQ'.repeat(1000)), held)).toHaveLength(1) + }) + + it('says what it found and what to do instead', () => { + const message = inlineDataRefusal(loader(packed(8000)) + loader(packed(400_000)))! + expect(message).toContain('nothing was written') + expect(message).toContain('2 blocks of base64 text (299 KB)') + expect(message).toContain('`), + width: 400, + height: 300, + }, + actions.resolveActor({ name: 'Kevin', kind: 'user' }), + )! + const full = await call('get_frame', { frame_id: frame.id, expand_components: true }) + const html = (JSON.parse(full.text) as { html: string }).html + expect( + (await call('set_frame_html', { frame_id: frame.id, html: html.replace('', '

More

') })) + .isError, + ).toBe(false) + }) + it('lets a later chunk of a rework carry over what the frame had before the stream', async () => { const frame = imported() expect( diff --git a/tests/inspectFrame.test.ts b/tests/inspectFrame.test.ts new file mode 100644 index 000000000..72749fa83 --- /dev/null +++ b/tests/inspectFrame.test.ts @@ -0,0 +1,122 @@ +import { Client } from '@modelcontextprotocol/sdk/client/index.js' +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js' +import { describe, expect, it, vi } from 'vitest' +import { findBrowserPath, inspectFrame } from '../server/screenshot.ts' +import type { Frame } from '../shared/types.ts' + +vi.mock('../server/db/persist.ts', () => ({ + saveCanvas: () => {}, + saveFrame: () => {}, + saveFrameNow: async () => {}, + saveActivity: () => {}, + saveFrameVersion: () => {}, + saveComponent: () => {}, +})) + +/** inspect_frame: the rendered frame as data, with the layout faults a reviewer would flag. */ + +const frame = (body: string, size = { width: 400, height: 300 }): Frame => ({ + id: 'inspected', + canvasId: 'inspect-canvas', + name: 'Screen', + html: `${body}`, + x: 0, + y: 0, + ...size, + createdAt: 0, + updatedAt: 0, + updatedBy: 'alice', +}) + +const FAULTY = frame(` +

Runs off the side

+
A label far too long for its pill
+

Arrivals

+ 12:40 +`) + +const CLEAN = frame(` +
+ +
+

One clean line

+`) + +describe.skipIf(!findBrowserPath())('inspectFrame', () => { + it('reports text past the edge, cut off by its box, and overlapping', async () => { + const { problems, problemCount } = await inspectFrame(FAULTY) + const byType = (type: string) => problems.filter((p) => p.type === type) + expect(byType('off-frame')).toEqual([ + expect.objectContaining({ text: 'Runs off the side', detail: expect.stringContaining('past the right edge') }), + ]) + expect(byType('clipped')).toEqual([ + expect.objectContaining({ selector: expect.stringContaining('div'), detail: 'text cut off with an ellipsis' }), + ]) + expect(byType('overlap')).toEqual([ + expect.objectContaining({ text: 'Arrivals', detail: expect.stringContaining('"12:40"') }), + ]) + expect(problemCount).toBe(3) + }, 30_000) + + it('leaves a clean frame alone, an image a rounded card crops included', async () => { + expect((await inspectFrame(CLEAN)).problems).toEqual([]) + }, 30_000) + + it('reports on the asked-for selectors in place of the outline', async () => { + const result = await inspectFrame(FAULTY, { selectors: ['.badge', '.missing', 'p[', 'h2, .pill'] }) + expect(result.elements.map((e) => [e.matched, e.text])).toEqual([ + ['.badge', '12:40'], + ['h2, .pill', 'A label far too long for its pill'], + ['h2, .pill', 'Arrivals'], + ]) + expect(result.unmatched).toEqual([ + { selector: '.missing', reason: 'no visible match' }, + { selector: 'p[', reason: 'invalid selector' }, + ]) + }, 30_000) + + it('reports text its own fixed height cuts off', async () => { + const clamped = frame( + '

Three lines of wrapped text that its twenty pixel box cuts down to one

', + ) + expect((await inspectFrame(clamped)).problems).toEqual([ + expect.objectContaining({ type: 'clipped', detail: 'text cut off by the box (overflow)' }), + ]) + }, 30_000) + + it('returns every match of every asked-for selector, past the outline’s 64', async () => { + const rows = ['a', 'b', 'c', 'd'] + .map((group) => + Array.from( + { length: 20 }, + (_, i) => `${i}`, + ).join(''), + ) + .join('') + const result = await inspectFrame(frame(rows), { selectors: ['.a', '.b', '.c', '.d'] }) + expect(result.elements).toHaveLength(80) + expect(result.unmatched ?? []).toEqual([]) + }, 30_000) + + it('is an MCP tool', async () => { + const { store } = await import('../server/store.ts') + const actions = await import('../server/actions.ts') + const { buildMcpServer } = await import('../server/mcp.ts') + const canvas = store.createCanvas('inspect', 'owner') + const owner = actions.resolveActor({ name: 'Owner', kind: 'user' }) + const made = actions.createFrame(canvas.id, { name: 'Screen', html: FAULTY.html, width: 400, height: 300 }, owner)! + const client = new Client({ name: 'inspect-test', version: '1.0.0' }) + const [a, b] = InMemoryTransport.createLinkedPair() + await buildMcpServer('Owner', 'owner').connect(b) + await client.connect(a) + const result = (await client.callTool({ + name: 'inspect_frame', + arguments: { frame_id: made.id, selectors: ['.badge'] }, + })) as { isError?: boolean; content: { text: string }[] } + await client.close() + expect(result.isError).toBeFalsy() + const body = JSON.parse(result.content[0]!.text) as { problemCount: number; elements: { text: string }[] } + expect(body.problemCount).toBe(3) + expect(body.elements.map((e) => e.text)).toEqual(['12:40']) + }, 30_000) +}) diff --git a/tests/layersStack.test.tsx b/tests/layersStack.test.tsx index d5e53e138..2c8897f4b 100644 --- a/tests/layersStack.test.tsx +++ b/tests/layersStack.test.tsx @@ -9,6 +9,7 @@ const restackFrames = vi.fn((_canvasId: string, _frames: StackWrite[]) => Promis const createFrame = vi.fn((canvasId: string, input: Partial & { name: string }) => Promise.resolve({ ...frameWith('new', 9), canvasId, ...input } as Frame), ) +const deleteFrame = vi.fn((_id: string) => Promise.resolve()) vi.mock('../src/lib/api', () => ({ api: { /* the Components tab's dot asks; nothing waits in these tests */ @@ -17,7 +18,7 @@ vi.mock('../src/lib/api', () => ({ restackFrames: (canvasId: string, frames: StackWrite[]) => restackFrames(canvasId, frames), createFrame: (canvasId: string, input: Partial & { name: string }) => createFrame(canvasId, input), updateFrame: () => Promise.resolve(), - deleteFrame: () => Promise.resolve(), + deleteFrame: (id: string) => deleteFrame(id), }, ApiError: class extends Error {}, errorMessage: (_err: unknown, fallback: string) => fallback, @@ -122,6 +123,58 @@ describe('LayersPanel stacking', () => { container.remove() }) + it('adds a frame or a canvas shape to the selection with ⇧- or ⌘-click, and drops it again', () => { + const click = (key: string, init: MouseEventInit = {}) => + act(() => { + row(key).dispatchEvent(new MouseEvent('click', { bubbles: true, ...init })) + }) + const selected = () => [...useStore.getState().selectedIds].sort() + click('s1') + click('f1', { shiftKey: true }) + expect(selected()).toEqual(['f1', 's1']) + expect(row('s1').getAttribute('aria-selected')).toBe('true') + expect(row('f1').getAttribute('aria-selected')).toBe('true') + click('f2', { metaKey: true }) + expect(selected()).toEqual(['f1', 'f2', 's1']) + click('f1', { shiftKey: true }) + expect(selected()).toEqual(['f2', 's1']) + /* a plain click narrows to the one row */ + click('f2') + expect(selected()).toEqual(['f2']) + }) + + it('deletes every selected frame and shape with ⌫ in the tree', () => { + deleteFrame.mockClear() + act(() => useStore.getState().selectMany(['f1', 's1'])) + const tree = container.querySelector('[role="tree"]')! + act(() => { + tree.dispatchEvent(new KeyboardEvent('keydown', { key: 'Delete', bubbles: true })) + }) + expect(deleteFrame.mock.calls.map(([id]) => id).sort()).toEqual(['f1', 's1']) + }) + + it('keeps a shape locked on its own layer when ⌫ deletes the selection', () => { + deleteFrame.mockClear() + const lockedShape = shape.replace('data-doop-drawing="rect"', 'data-doop-drawing="rect" data-doop-locked=""') + act(() => useStore.getState().patchFrameLocal('s1', { html: lockedShape })) + act(() => useStore.getState().selectMany(['f1', 's1'])) + const tree = container.querySelector('[role="tree"]')! + act(() => { + tree.dispatchEvent(new KeyboardEvent('keydown', { key: 'Delete', bubbles: true })) + }) + expect(deleteFrame.mock.calls.map(([id]) => id)).toEqual(['f1']) + }) + + it('walks the rows from a canvas shape selected as a whole', () => { + act(() => useStore.getState().select('s1')) + const tree = container.querySelector('[role="tree"]')! + act(() => { + tree.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true })) + }) + /* the list runs s1, f2, f1: the row under the shape is f2 */ + expect(useStore.getState().selectedIds).toEqual(['f2']) + }) + it('lists the frame in front at the top', () => { expect(stack()).toEqual(['f1', 'f2', 's1']) expect(listed()).toEqual(['s1', 'f2', 'f1']) diff --git a/tests/mcp-comments-write.test.ts b/tests/mcp-comments-write.test.ts index fe9708a30..11ae61489 100644 --- a/tests/mcp-comments-write.test.ts +++ b/tests/mcp-comments-write.test.ts @@ -169,8 +169,12 @@ describe('element-comment write MCP tools', () => { }) expect(isError).toBeFalsy() expect(parsed).toEqual(reply) - /* the 4th arg is who pays, the 5th the actor kind: an agent reply must not log as a human */ - expect(replySpy).toHaveBeenCalledWith('m1', ' Done ', 'Claude', OWNER_ID, 'agent') + /* the 4th arg is who pays, the 5th the actor kind: an agent reply must not log as a human; + the 6th is the people the text @mentions (none here) */ + expect(replySpy).toHaveBeenCalledWith('m1', ' Done ', 'Claude', OWNER_ID, 'agent', { + ids: [], + roleText: 'Done', + }) expect(heartbeat).toHaveBeenCalledTimes(1) } finally { await close() @@ -195,7 +199,14 @@ describe('element-comment write MCP tools', () => { agent_name: 'Claude', }) expect(isError).toBeFalsy() - expect(replySpy).toHaveBeenCalledWith('m1', '@Doop tighten this', 'Claude', 'mate-1', 'agent') + expect(replySpy).toHaveBeenCalledWith( + 'm1', + '@Doop tighten this', + 'Claude', + 'mate-1', + 'agent', + expect.objectContaining({ ids: [] }), + ) } finally { await close() } diff --git a/tests/measure.test.ts b/tests/measure.test.ts new file mode 100644 index 000000000..d6d49ed0a --- /dev/null +++ b/tests/measure.test.ts @@ -0,0 +1,85 @@ +import { describe, expect, it } from 'vitest' +import { formatDistance, lineLength, measureBetween } from '../src/lib/measure' + +const rect = (x: number, y: number, width: number, height: number) => ({ x, y, width, height }) + +describe('measureBetween', () => { + it('measures a box inside another to each matching edge, through its own middle', () => { + const { lines, guides } = measureBetween(rect(20, 30, 100, 40), rect(0, 0, 200, 100)) + expect(guides).toEqual([]) + expect(lines).toEqual([ + { axis: 'x', from: 0, to: 20, at: 50 }, + { axis: 'x', from: 120, to: 200, at: 50 }, + { axis: 'y', from: 0, to: 30, at: 70 }, + { axis: 'y', from: 70, to: 100, at: 70 }, + ]) + }) + + it('gives the same distances whichever of the two is selected', () => { + const inner = rect(20, 30, 100, 40) + const outer = rect(0, 0, 200, 100) + expect(measureBetween(outer, inner)).toEqual(measureBetween(inner, outer)) + }) + + it('leaves out an edge that already meets the other', () => { + const { lines } = measureBetween(rect(0, 10, 50, 20), rect(0, 0, 200, 100)) + expect(lines.map((l) => [l.axis, lineLength(l)])).toEqual([ + ['x', 150], + ['y', 10], + ['y', 70], + ]) + }) + + it('measures the gap to a box beside it, through what the two share', () => { + expect(measureBetween(rect(0, 0, 100, 100), rect(140, 50, 60, 100))).toEqual({ + lines: [{ axis: 'x', from: 100, to: 140, at: 75 }], + guides: [], + }) + expect(measureBetween(rect(140, 50, 60, 100), rect(0, 0, 100, 100)).lines).toEqual([ + { axis: 'x', from: 100, to: 140, at: 75 }, + ]) + }) + + it('measures only the gap to a box below it, not their offset', () => { + expect(measureBetween(rect(0, 0, 100, 40), rect(30, 100, 100, 40)).lines).toEqual([ + { axis: 'y', from: 40, to: 100, at: 65 }, + ]) + }) + + it('carries a diagonal box’s edges out to the lines', () => { + expect(measureBetween(rect(0, 0, 100, 100), rect(150, 200, 50, 50))).toEqual({ + lines: [ + { axis: 'x', from: 100, to: 150, at: 50 }, + { axis: 'y', from: 100, to: 200, at: 50 }, + ], + guides: [ + { axis: 'y', from: 50, to: 200, at: 150 }, + { axis: 'x', from: 50, to: 150, at: 200 }, + ], + }) + }) + + it('measures up and left as well', () => { + const { lines, guides } = measureBetween(rect(150, 200, 50, 50), rect(0, 0, 100, 100)) + expect(lines).toEqual([ + { axis: 'x', from: 100, to: 150, at: 225 }, + { axis: 'y', from: 100, to: 200, at: 175 }, + ]) + expect(guides).toEqual([ + { axis: 'y', from: 100, to: 225, at: 100 }, + { axis: 'x', from: 100, to: 175, at: 100 }, + ]) + }) + + it('shows nothing between boxes that touch', () => { + expect(measureBetween(rect(0, 0, 100, 100), rect(100, 0, 50, 100)).lines).toEqual([]) + }) +}) + +describe('formatDistance', () => { + it('keeps at most two decimals and none it does not need', () => { + expect(formatDistance(12)).toBe('12') + expect(formatDistance(5.836)).toBe('5.84') + expect(formatDistance(1.5)).toBe('1.5') + }) +}) diff --git a/tests/measureBrowser.test.ts b/tests/measureBrowser.test.ts new file mode 100644 index 000000000..618dfca89 --- /dev/null +++ b/tests/measureBrowser.test.ts @@ -0,0 +1,96 @@ +import { beforeEach, describe, expect, it } from 'vitest' +import type { Page } from 'puppeteer-core' +import { findBrowserPath } from '../server/screenshot' +import { pagePerTest } from './browser' +import { canvasFrame, openCanvasPage } from './canvasPageFixture' + +const BOXES = `
` + +/* ⌥ held with something selected shows the distances to what the pointer is over */ +describe.skipIf(!findBrowserPath())('⌥ distances', () => { + const pages = pagePerTest() + let page: Page + const LEFT = { ...canvasFrame({ id: 'left', name: 'Left', x: 0, y: 0, width: 300, height: 200 }), html: BOXES } + const RIGHT = canvasFrame({ id: 'right', name: 'Right', x: 420, y: 50, width: 200, height: 100 }) + + beforeEach(async () => { + page = await pages.open() + page.setDefaultTimeout(10_000) + await page.setViewport({ width: 1600, height: 1000 }) + await openCanvasPage(page, [LEFT, RIGHT]) + }) + + /** a design point of a frame, on screen */ + async function pointIn(frame: 0 | 1, x: number, y: number) { + return page.evaluate( + (frame, x, y) => { + const surface = document.querySelectorAll('[data-frame-surface]')[frame]! + const r = surface.getBoundingClientRect() + const scale = r.width / (surface as HTMLElement).offsetWidth + return { x: r.left + x * scale, y: r.top + y * scale } + }, + frame, + x, + y, + ) + } + async function moveTo(frame: 0 | 1, x: number, y: number) { + const at = await pointIn(frame, x, y) + await page.mouse.move(at.x, at.y, { steps: 3 }) + } + async function distances() { + return page.$$eval('[data-measure-distance]', (labels) => + labels.map((el) => `${el.getAttribute('data-measure-distance')}:${el.textContent}`), + ) + } + + it('measures the gap from the selected frame to the one under the pointer', async () => { + await page.click('[data-frame-title]') + await moveTo(1, 100, 50) + expect(await distances()).toEqual([]) + await page.keyboard.down('Alt') + await expect.poll(distances).toEqual(['x:120']) + /* nothing to measure to over the selection itself */ + await moveTo(0, 280, 180) + await expect.poll(distances).toEqual([]) + await moveTo(1, 100, 50) + await expect.poll(distances).toEqual(['x:120']) + await page.keyboard.up('Alt') + await expect.poll(distances).toEqual([]) + }) + + it('measures a picked element to its sibling, and to the frame from the element itself', async () => { + const a = await pointIn(0, 80, 65) + await page.mouse.click(a.x, a.y) + await page.waitForSelector('[data-element-outline]') + await page.keyboard.down('Alt') + await moveTo(0, 220, 65) + await expect.poll(distances).toEqual(['x:60']) + await moveTo(0, 80, 65) + await expect.poll(distances).toEqual(['x:30', 'x:170', 'y:40', 'y:110']) + /* both picked: one box, measured to the frame even from the other's place */ + const b = await pointIn(0, 220, 65) + await page.keyboard.up('Alt') + await page.keyboard.down('Shift') + await page.mouse.click(b.x, b.y) + await page.keyboard.up('Shift') + await page.waitForSelector('[data-picked-element]') + await page.keyboard.down('Alt') + await moveTo(0, 221, 66) + await expect.poll(distances).toEqual(['x:30', 'x:50', 'y:40', 'y:110']) + /* over another frame the frames are measured */ + await moveTo(1, 100, 50) + await expect.poll(distances).toEqual(['x:120']) + await moveTo(0, 80, 65) + /* a drag owns ⌥ */ + await page.mouse.down() + await expect.poll(distances).toEqual([]) + await page.mouse.up() + await page.keyboard.up('Alt') + }) +}) diff --git a/tests/pageCanvasBrowser.test.ts b/tests/pageCanvasBrowser.test.ts index 03990bcdc..db9f05a40 100644 --- a/tests/pageCanvasBrowser.test.ts +++ b/tests/pageCanvasBrowser.test.ts @@ -79,6 +79,22 @@ describe.skipIf(!findBrowserPath())('page camera and snapping', { timeout: 30_00 await page.waitForSelector('iframe[data-doop-frame]') } + /* right-click an element of the target frame and take its menu's link item */ + async function copyLinkTo(selector: string) { + const iframe = (await page.$('iframe[title="target"]'))! + const doc = (await iframe.contentFrame())! + const inner = await doc.$eval(selector, (el) => el.getBoundingClientRect().toJSON()) + const outer = await iframe.evaluate((el) => el.getBoundingClientRect().toJSON()) + const zoom = outer.width / 200 + await page.mouse.click(outer.x + (inner.x + 5) * zoom, outer.y + (inner.y + 5) * zoom, { button: 'right' }) + const item = await page.waitForFunction(() => + [...document.querySelectorAll('[role="menuitem"]')].find( + (el) => el.firstChild?.textContent === 'Copy link to element', + ), + ) + await (await item.asElement()!.toElement('div')).click() + } + it('restores pan and zoom when returning to a page', async () => { await load(canvas([frame('directory', 'first', 0), frame('target', 'second', 3000)])) const initial = await page.evaluate(() => window.pageState().viewport) @@ -155,7 +171,6 @@ describe.skipIf(!findBrowserPath())('page camera and snapping', { timeout: 30_00 canvas([frame('original', 'first', 0), target]), `?${new URLSearchParams({ frame: target.id, element: 'h1h1h1' })}`, ) - await page.waitForSelector('button[aria-label="Copy link to element"]') await page.waitForFunction((sel) => window.pageState().selectedElement?.selector === sel, {}, selector) expect(await page.evaluate(() => window.pageState())).toMatchObject({ activePageId: pageId, @@ -166,8 +181,8 @@ describe.skipIf(!findBrowserPath())('page camera and snapping', { timeout: 30_00 viewport: { x: -2500, y: 300, zoom: 1 }, }) - // Copy through the actual element toolbar, then reopen the resulting URL. - await page.locator('button[aria-label="Copy link to element"]').click() + // Copy through the element's own menu, then reopen the resulting URL. + await copyLinkTo('h1') await page.waitForFunction(() => window.pageState().notice === 'Element link copied') const copied = await page.evaluate(() => navigator.clipboard.readText()) const url = new URL(copied) @@ -176,7 +191,6 @@ describe.skipIf(!findBrowserPath())('page camera and snapping', { timeout: 30_00 expect(url.searchParams.get('element')).toBe('h1h1h1') expect(url.searchParams.has('selector')).toBe(false) await load(canvas([target]), url.search) - await page.waitForSelector('button[aria-label="Copy link to element"]') await page.waitForFunction((sel) => window.pageState().selectedElement?.selector === sel, {}, selector) // Deselecting still removes the probe and its panel after a deep link. @@ -189,8 +203,8 @@ describe.skipIf(!findBrowserPath())('page camera and snapping', { timeout: 30_00 const target = { ...frame('target', 'first', 0), html: '

Design

Body

' } await load(canvas([target]), '?frame=target') await page.evaluate(() => window.pickElement('target', '#hero > p:nth-of-type(1)')) - await page.waitForSelector('button[aria-label="Copy link to element"]') - await page.locator('button[aria-label="Copy link to element"]').click() + await page.waitForFunction(() => window.pageState().selectedElement?.selector === '#hero > p:nth-of-type(1)') + await copyLinkTo('p') await page.waitForFunction(() => window.pageState().notice === 'Element link copied') const url = new URL(await page.evaluate(() => navigator.clipboard.readText())) const elementId = url.searchParams.get('element')! @@ -203,6 +217,19 @@ describe.skipIf(!findBrowserPath())('page camera and snapping', { timeout: 30_00 await page.waitForFunction(() => window.pageState().selectedElement?.selector === '#hero > p:nth-of-type(1)') }) + it('lets a reader copy the link of the element they picked from the frame menu', async () => { + const target = { + ...frame('target', 'first', 0), + html: '

Design

', + } + await load({ ...canvas([target]), role: 'view' }, '?frame=target&element=h1h1h1') + await page.waitForFunction(() => window.pageState().selectedElement?.selector === '#hero > h1:nth-of-type(1)') + await copyLinkTo('h1') + await page.waitForFunction(() => window.pageState().notice === 'Element link copied') + const url = new URL(await page.evaluate(() => navigator.clipboard.readText())) + expect(url.searchParams.get('element')).toBe('h1h1h1') + }) + it('falls back to the frame when no element carries the linked id', async () => { await load( canvas([frame('target', 'second', 3000)]), @@ -246,7 +273,6 @@ describe.skipIf(!findBrowserPath())('page camera and snapping', { timeout: 30_00 `, } await load(canvas([frame('original', 'first', 0), target]), '?frame=target&element=chart0') - await page.waitForSelector('button[aria-label="Copy link to element"]', { timeout: 5000 }) await page.waitForFunction(() => window.pageState().selectedElement?.selector === '#chart') expect(await page.evaluate(() => window.pageState())).toMatchObject({ activePageId: pageId, @@ -258,12 +284,11 @@ describe.skipIf(!findBrowserPath())('page camera and snapping', { timeout: 30_00 expect(await page.evaluate(() => window.pageState().notice)).toBeUndefined() /* the live element wears its id, so the link needs no stamp */ - await page.locator('button[aria-label="Copy link to element"]').click() + await copyLinkTo('#chart') await page.waitForFunction(() => window.pageState().notice === 'Element link copied') const copied = await page.evaluate(() => navigator.clipboard.readText()) expect(new URL(copied).searchParams.get('element')).toBe('chart0') await load(canvas([target]), new URL(copied).search) - await page.waitForSelector('button[aria-label="Copy link to element"]', { timeout: 5000 }) await page.waitForFunction(() => window.pageState().selectedElement?.selector === '#chart') }) @@ -282,7 +307,6 @@ describe.skipIf(!findBrowserPath())('page camera and snapping', { timeout: 30_00 inspectorOpen: true, notice: 'This element no longer exists. Showing its frame instead.', }) - expect(await page.$('button[aria-label="Copy link to element"]')).toBeNull() }) it('follows another element link and browser history within the same mounted canvas', async () => { @@ -297,7 +321,6 @@ describe.skipIf(!findBrowserPath())('page camera and snapping', { timeout: 30_00 window.dispatchEvent(new PopStateEvent('popstate')) }) await waitState('second link', () => window.pageState().selectedElement?.selector === '#two') - await page.waitForSelector('button[aria-label="Copy link to element"]') await page.evaluate(() => history.back()) await waitState('back to the first link', () => window.pageState().selectedElement?.selector === '#one') await page.evaluate(() => { @@ -305,7 +328,6 @@ describe.skipIf(!findBrowserPath())('page camera and snapping', { timeout: 30_00 window.dispatchEvent(new PopStateEvent('popstate')) }) await waitState('frame-only link', () => window.pageState().inspectorOpen && !window.pageState().selectedElement) - await page.waitForSelector('button[aria-label="Copy link to element"]', { hidden: true }) }) it('does not snap a drag to the invisible frame on another page', async () => { diff --git a/tests/personMentions.test.ts b/tests/personMentions.test.ts new file mode 100644 index 000000000..59e5f75a4 --- /dev/null +++ b/tests/personMentions.test.ts @@ -0,0 +1,134 @@ +import { describe, expect, it } from 'vitest' +import { AGENT_ROLES, DEFAULT_ROLE_ID, mentionedRole } from '../shared/agents.ts' +import { + AGENT_PICK, + activeMentionQuery, + resolvePersonMentions, + withoutAgentMentions, + findMentions, + mentionedPeople, + mentionSegments, + nameMatches, +} from '../shared/personMentions.ts' + +const ana = { id: 'u1', name: 'Ana Souza' } +const anaB = { id: 'u2', name: 'Ana' } +const bo = { id: 'u3', name: 'Bo' } +const people = [anaB, ana, bo] + +describe('findMentions', () => { + it('finds a name with spaces, case aside', () => { + expect(mentionedPeople('hey @ana souza, look', people)).toEqual([ana]) + }) + + it('prefers the longer name over a prefix of it', () => { + expect(findMentions('@Ana Souza and @Ana', people).map((m) => m.person.id)).toEqual(['u1', 'u2']) + }) + + it('needs the name to end where a letter would go on', () => { + expect(mentionedPeople('@Bob is not Bo', people)).toEqual([]) + expect(mentionedPeople('thanks @Bo!', people)).toEqual([bo]) + }) + + it('is not an email address', () => { + expect(mentionedPeople('mail ana@Bo.com', people)).toEqual([]) + }) + + it('reads an accent written as a combining mark as part of the name', () => { + expect(mentionedPeople('@Jose\u0301 hi', [{ id: 'j', name: 'Jose' }])).toEqual([]) + }) + + it('starts after punctuation, as the picker does', () => { + expect(mentionedPeople('(@Bo)', people)).toEqual([bo]) + expect(activeMentionQuery('(@B', 3)).toEqual({ start: 1, query: 'B' }) + }) + + it('lists each person once, in order', () => { + expect(mentionedPeople('@Bo @Ana Souza @Bo', people)).toEqual([bo, ana]) + }) +}) + +describe('mentionSegments', () => { + it('cuts the text around each mention', () => { + expect(mentionSegments('hi @Bo, ok', people)).toEqual([ + { text: 'hi ' }, + { text: '@Bo', person: bo }, + { text: ', ok' }, + ]) + }) +}) + +describe('activeMentionQuery', () => { + it('reads the query typed after an @ at the caret', () => { + expect(activeMentionQuery('hi @An', 6)).toEqual({ start: 3, query: 'An' }) + expect(activeMentionQuery('@Ana S', 6)).toEqual({ start: 0, query: 'Ana S' }) + }) + + it('is nothing inside a word, across lines or after a space right after @', () => { + expect(activeMentionQuery('ana@b', 5)).toBeNull() + expect(activeMentionQuery('@a\nb', 4)).toBeNull() + expect(activeMentionQuery('@ x', 3)).toBeNull() + }) +}) + +describe('nameMatches', () => { + it('matches the start of the name or of any word', () => { + expect(nameMatches('Ana Souza', 'sou')).toBe(true) + expect(nameMatches('Ana Souza', 'ana s')).toBe(true) + expect(nameMatches('Ana Souza', 'za')).toBe(false) + }) + + it('stops matching once the whole name and a space are typed', () => { + expect(nameMatches('Ana Souza', 'ana ')).toBe(true) + expect(nameMatches('Ana Souza', 'ana souza ')).toBe(false) + }) +}) + +describe('resolvePersonMentions', () => { + const sam1 = { id: 's1', name: 'Sam' } + const sam2 = { id: 's2', name: 'sam' } + + it('reaches a name several people share only through the pick', () => { + expect(resolvePersonMentions('@Sam look', [sam1, sam2]).ids).toEqual([]) + expect(resolvePersonMentions('@Sam look', [sam1, sam2], ['s2']).ids).toEqual(['s2']) + expect(resolvePersonMentions('@Sam look', [sam2, sam1], ['s2']).ids).toEqual(['s2']) + }) + + it('gives a name to its owner, never to a shorter one', () => { + expect(resolvePersonMentions('@Ana Souza ok', people).ids).toEqual(['u1']) + }) + + it('blanks people out of the text the agent matcher reads', () => { + const brand = { id: 'b', name: `${DEFAULT_ROLE_ID} Fan` } + const { ids, roleText } = resolvePersonMentions(`hi @${DEFAULT_ROLE_ID} Fan`, [brand]) + expect(ids).toEqual(['b']) + expect(mentionedRole(roleText, AGENT_ROLES)).toBeUndefined() + expect(mentionedRole(`hi @${DEFAULT_ROLE_ID} Fan`, AGENT_ROLES)).toBeDefined() + }) + + it('leaves a picked agent to the agent matcher, over a person named like it', () => { + const named = { id: 'p', name: DEFAULT_ROLE_ID } + const text = `@${DEFAULT_ROLE_ID} tidy this` + expect(resolvePersonMentions(text, [named]).ids).toEqual(['p']) + const agent = resolvePersonMentions(text, [named], [`${AGENT_PICK}${DEFAULT_ROLE_ID}`]) + expect(agent.ids).toEqual([]) + expect(mentionedRole(agent.roleText, AGENT_ROLES)?.id).toBe(DEFAULT_ROLE_ID) + /* a person picked as well keeps their mention */ + expect(resolvePersonMentions(text, [named], [`${AGENT_PICK}${DEFAULT_ROLE_ID}`, 'p']).ids).toEqual(['p']) + }) + + it('leaves a picked agent whose handle a shorter name begins', () => { + const short = { id: 'p', name: 'cop' } + const text = '@copy-editor please' + expect(resolvePersonMentions(text, [short], [`${AGENT_PICK}copy-editor`]).ids).toEqual([]) + }) +}) + +describe('withoutAgentMentions', () => { + it("turns agent mentions into names and keeps people's", () => { + const fan = { id: 'f', name: `${DEFAULT_ROLE_ID} Fan` } + expect(withoutAgentMentions(`@${DEFAULT_ROLE_ID} asked; cc @${DEFAULT_ROLE_ID} Fan`, AGENT_ROLES, [fan])).toBe( + `${DEFAULT_ROLE_ID} asked; cc @${DEFAULT_ROLE_ID} Fan`, + ) + }) +}) diff --git a/tests/residentComments.test.ts b/tests/residentComments.test.ts index 23687e195..40dc5d3af 100644 --- a/tests/residentComments.test.ts +++ b/tests/residentComments.test.ts @@ -97,6 +97,16 @@ describe('the resident agent replying in a thread', () => { expect(actions.takeAgentCommentsFor(CANVAS, AGENT, 'alice')).toEqual([]) }) + it("keeps a person's mention whose name starts like an agent's, and queues no agent work", async () => { + const c = await ask() + const fan = { id: 'u-fan', name: `${DEFAULT_ROLE_ID} Fan` } + const posted = replyInThread(CANVAS, c.id, `Done. @${fan.name}, take a look`, actor(), run(), false, [fan]) + expect(posted.ok).toBe(true) + expect(texts(c.id)[1]).toBe(`${AGENT}: Done. @${fan.name}, take a look`) + expect(posted.ok && posted.reply.forAgent).toBeFalsy() + expect(actions.takeAgentCommentsFor(CANVAS, AGENT, 'alice')).toEqual([]) + }) + it('stays on its own canvas', async () => { const c = await ask() const posted = replyInThread('canvas-2', c.id, 'Done', actor(), run())