feat(studio): edit and style text in the preview - #3077
Open
miguel-heygen wants to merge 32 commits into
Open
Conversation
Double-press a text element in the canvas and the caret opens where you pressed, in the element itself rather than in a panel. Select characters and a small toolbar offers colour, bold, italic and underline, applied to exactly those characters. Styling text needed a capability Studio did not have. The patch vocabulary was inline-style, attribute, html-attribute and text-content, and text-content assigns textContent; the text-field model escapes markup on the way out and refuses a change in child structure. No route existed for a span to reach a composition file. Adds a rich-text operation that has one, guarded by a single sanitiser in packages/core called on both ends of the trip: in the browser so the preview shows what will be saved, and on the server because that is where the file is written. Tags and style properties are a small allowlist, and an unexpected tag loses its formatting rather than its words. Styling is applied by reading the element into a flat list of runs and rebuilding it, not by wrapping a DOM range. Replacing a colour, removing one, and styling across an existing run stop being special cases, and the markup cannot grow with repeated edits. In a flex or grid container the runs go inside one wrapper so a coloured word cannot reflow the element. Also fixes the keyboard: the shortcut guards matched contenteditable=true only, so playback shortcuts ate letters typed into the composition.
… had Three faults that met in one place: an element whose children are text layers. Removing a layer, or adding one, could never save. The per-child operations can only address children that already exist, so they refuse any change in how many there are — which is every add and every delete. The panel offered both buttons and both ended in "Couldn't save this text structure change". A structure change now writes the structure, through the same operation an inline style edit already uses. Styling a run of characters threw away the identity of every layer in the element. The rebuild emitted fresh, bare spans, so the attribute the panel tracks a layer by went with them, and afterwards nothing the panel offered could match a layer to its source. Runs now carry the child they came from and the rebuild puts its identity back, without duplicating it onto a run that was split off. Saving a styled run deleted its neighbours' typography. The allowlist was paint-only, on the reasoning that text edits should not move or resize things — but the design panel writes exactly those typography properties onto exactly those spans, so the rule did not stop text changing layout, it deleted the layout the user had set. Colouring one word dropped a sibling's font size.
…er them Choosing one colour for three characters painted a different shade onto each character of the whole line. Two faults, both in putting the selection back after the rebuild. The offset walk counted a line break as a character everywhere except the one place that maps an offset back to a DOM position, so in an element containing a `<br>` the restored selection sat one character further along for every break before it. And a native colour picker reports every sample while the pointer moves inside it, so one choice of colour arrives as a stream of them — each restyling a selection that had walked on since the last. The wrapper this rebuild adds inside a flex container carries nothing, and reading it as the layer it sits around hid the real one below it, so a second edit of the same element threw away every identity the first one had kept. An element with nothing on it is no longer taken as an identity.
Every colour chosen in the preview was dropped on the way out, silently, for any element whose text contains a line break. Two gates disagreed. The press that opens an edit asks whether the element's own markup can be rewritten. The commit asked the design panel's question instead: does this element have text fields. It has none when its text contains a `<br>` — a `<span>` holding one is not a leaf, so nothing inside counts as a field and the element reports no editable text at all. So the caret opened, the toolbar worked, the preview showed the styling, and the commit returned without a request, a file change or a word about it. The commit now asks the same question the press did. The panel's own text commits still use the panel's rule, which is theirs. Also stops the writer's own `data-hf-id` counting as a layer identity: it is stamped onto every element on the way to disk, so once a file had been saved the wrapper this rebuild adds inside a flex container looked like a layer again and went back to hiding the real ones underneath it.
A rich-text patch adds spans, and it left them without their stable ids. The next preview request minted them and wrote the file a second time — after Studio had recorded the edit in its history. The recorded "after" no longer matched the bytes on disk, so the content check refused and undo reported the file as changed outside Studio. Every colour applied to a run of characters and every text layer added poisoned the history the same way. The patch now mints those ids itself, with the same function the later pass would have used. The clip split already does this for its clone, and its comment names this exact failure.
miguel-heygen
force-pushed
the
feat-studio-inline-rich-text
branch
2 times, most recently
from
August 7, 2026 20:09
fbd3959 to
efdff97
Compare
… the glyphs Colouring a word in the shipped playground saved correctly and rendered white, because that composition sets `-webkit-text-fill-color` on the text element. That property inherits and paints the glyph fill, so it wins over any `color` a run below it sets. The composition is not doing anything wrong; from the editor it reads as the colour picker being broken. The run now says its colour twice when, and only when, something else would paint over it: the rendered span is asked whether its fill differs from its own computed colour, and only then is the fill written alongside. Both sides come from the same computed style, so neither colour notation nor inheritance has to be untangled by hand, and a composition that does not do this keeps the markup it had.
…ally paints under The box around a text layer inside the playground card stopped mid-word. The layer is 260px wide and paints 313, because its parent carries `scale(1.2)`, and the chrome read only the element's OWN transform. The top-left looked right, since the corners are anchored to the real bounding rect, so only the right and bottom edges fell short, by exactly 1/1.2. The same read decides whether to draw the box rotated at all, so an element whose parent is rotated got an upright box over a rotated one. The transform is now accumulated from the element up to the composition root. Only the linear part matters: each transform's origin contributes translation, and translation is already discarded by matching the corners to the element's bounding rect, so composing the matrices is enough and no per-ancestor origin has to be unpicked. The walk stops inside the composition document, because the canvas zoom lives on the iframe in Studio's own document and is applied separately. The fake DOMMatrix the geometry tests use gained the `multiply` it now needs.
…t gate The audit gate was already red on this branch before the selection-box commit landed, with four findings, all of them in the feature's own files: `restyle`, `runNodes`, `offsetOf` and the test's `rangeOver`. Split into named steps rather than suppressed. Two things worth saying about the split, because both are places it could have gone quietly wrong. `restyle` still walks UTF-16 units rather than code points: spreading the string would count a surrogate pair once and slide every index after an emoji. And `offsetOf` counts two different things depending on how the position was given, a place inside a text node or an index among the host's children, where a child element contributes everything inside it. Collapsing those two into one helper made bold stop toggling off, which the suite caught.
…ere external Every mutation route wrote the file without leaving a write receipt, so the watcher's broadcast of Studio's own edit arrived with no identity on it. The external-change coordinator could not tell that echo from an agent or an editor writing the file behind Studio's back, so it took the safe branch and did a full iframe reload. That reload hides the stage for the length of the reload, which is what the flash after a text edit was. Every mutation write now goes through one helper that records the receipt, and the client claims the write before the request goes out rather than after it: the server writes and the watcher fires while the request is still in flight, so a token marked from the response can arrive after the echo it was meant to match. Reproduced in the browser before and after, with the reload path traced end to end. Before, a patch-element write logged `token: null` then a reload from the coordinator; after, the same write logs the token and `suppressed: own write token`, with no reload. Adds `hf-reload-debug` (localStorage, off by default) alongside the existing `hf-resize-debug`: it records each file-change decision and its reason, plus the stack of whoever asked for a full reload.
… one assumed An element that had never been dragged skipped the movement measurement and took the canvas zoom as the whole screen mapping. Nothing above the element was considered, so any parent transform broke the drag: a card at rotationY 180 with scale 1.2 maps a rightward drag to -1.2x the zoom, meaning the text walked LEFT while the overlay followed the pointer, and the overlay only snapped onto the text at drop, when it re-measured. Measured on the live element in that card: one unit of drag offset moved it -0.757 px on x and +0.757 on y, where the skipped path assumed +0.631 on both. The measurement it skipped already handles this — it moves the element, watches where it lands, and inverts that, which is right for rotation, mirroring, scale and perspective alike. So the special case is gone and every drag measures. Same element after: a 120x80 pointer drag moves it 120.3x80.2. Rewrote the test that asserted the skipped path's identity matrix for an unmovable element. It now asserts the honest outcome: an element with no measurable movement is reported unmeasurable whether or not it carries a path offset, and the caller's existing fallback covers it.
…DOM ones The receipt only helps when the client marked the token it sent, and the GSAP mutation writers never sent one. A drag commits through gsap-mutations, so the server minted a token the client had never seen, the change came back looking like someone else's, and the preview did the full reload the receipt was meant to prevent. Same one-line claim on both GSAP mutation writers, the timing sync's mutation call, and the caption auto-save PUT. The rollback call stays deliberately unclaimed and says why: it runs because a mutation did not converge, so the preview is on bytes nobody can vouch for and the reload is the point. Verified live: a drag-shaped update-properties on the timeline now logs `suppressed: own write token` with no reload, where it logged a coordinator reload before.
…last one hovered Shift-click read the hover cache and used it without checking what it described. That cache is filled asynchronously as the pointer moves, so passing over one element on the way to another leaves it naming the element you left. The shift-click then added THAT element, and because the same branch prevented the default and set the suppression flags, the mousedown path that would have resolved the point correctly never ran. Multi-select looked like it grabbed things at random, or like it did nothing. Reproduced on the canvas with a trace: hover #card, shift-click #dot-b, and the group gained #card. Same gesture after: the guard rejects the cache, the mousedown path resolves the point, and the group gains #dot-b. The cache is still used when it is provably about the point clicked, including when it names a clip ancestor of the element there, so the fast path survives for the common case of clicking straight at something. Adds `hf-select-debug` (localStorage, off by default) recording which selection branch ran and what it decided, and pulls the flag/format shared with `hf-reload-debug` into one place rather than copying it.
The marquee built the group correctly and then threw it away. It announced only the primary to the timeline, and the timeline is the source of truth for what is selected: the sync back to the canvas saw one selected id against a group of several, decided the canvas was stale, and replaced the group with that single element a moment after the drop. Drag a box around four things, get one. The whole set is announced now, and the primary goes in as its anchor rather than as a new single selection, so the set it just joined survives. This is the same reason the single-select path already anchors with preserveSet. A test drives applyMarqueeSelection with two elements and asserts both reach the timeline; it fails against the old single-id announce.
Every canvas selection is mirrored onto the timeline, and the timeline syncs back — whatever it holds replaces the canvas selection a moment later. The mirror announced only the primary and anchored it with preserveSet, but preserving a set that does not contain the id empties the set, and an empty set syncs back as "nothing is selected". Adding a second element, or re-resolving a group after moving it, could therefore drop the whole selection rather than keep it. One helper now owns the mirror: publish the members, then anchor. A single selection keeps the previous contract deliberately, so a late async primary still cannot collapse a live group and a fresh click still collapses a stale one. The group re-resolve path also gains the ancestor id fallback the other callers already had — without it a member with no direct timeline row resolved to null and deselected everything. Two tests: a second element joining a selection, and a marquee, both assert the full set reaches the timeline. Both fail against the announce-the-primary-only version.
A drag that jumps is a position that changed without the pointer asking for it, and nothing on that path says anything today, so the frame it diverges can only be guessed at. `hf-drag-debug` (localStorage, off by default) records the whole gesture: the mapping and start position each member got, the pointer delta against the delta actually applied on every eighth move, what each member was told to commit, and where they all sit at the drop, once the commit resolves, and 120/400/900ms later. That last group is the point of it. The source write, the preview reload and the timeline resume all land within a few frames of the drop, and any of them can put the elements back where they started before the new position arrives — a snap-back shows up as a settle sample reverting to the gesture-start reading. A gap between `pointer` and `applied` instead means snapping pulled the group off the cursor, which is a different fault with a different fix.
The drag trace showed the group landing exactly where it was dropped and staying there — no snap-back at any settle sample, and the pointer and the applied delta never more than 2px apart — but two milliseconds after the drop the selection was cleared with seven members still in it. The clear comes from the timeline sync deciding the timeline holds nothing, and that branch said nothing. It says so now, along with whether it is about to act on it. The mirror alongside it reports how many members it managed to publish and whether the anchor was among them, because a member with no timeline row of its own resolves to null and is dropped silently — publish none and the sync reads it back as an empty selection.
After a move the preview re-syncs and the selection is re-resolved against the new document. When the primary could not be found there, both re-resolve paths cleared the entire selection — so a group of five, all still on screen, was deselected because one of them failed to resolve. The trace showed the clear landing 600ms after the drop with five members still held, and the timeline sync running afterwards on an already-empty canvas, which ruled it out as the cause. A live group now re-resolves as a group and keeps whoever survived, picking a new primary from them; it only clears when nobody did. That is what refreshDomEditGroupSelectionsFromPreview was written for — it existed and was never called. Both clears also say which one they are and how many members were held, so if this is not the last of it the next trace names the path immediately.
Resizing the card commits correctly — the source and a fresh load both read 273x181 — but 200ms after the drop, mid-commit, the element renders at 395x261 with the studio size vars still holding 273x181. Something writes the pre-gesture size back inline while the reload is still in flight, and every writer of that size was silent. Both are traced now under the existing hf-resize-debug flag, each with the size going in, the size being replaced, and a short stack. Restoring the pre-gesture size is right on a cancel and wrong after a successful commit, and the function doing it cannot tell the two apart from the inside — so the caller has to be named before this can be fixed at the right end.
The resize hunt is over — the size lands correctly and the jump is gone with the merged fixes in — so the two box-size write traces added to chase it come out again. They were scaffolding for a closed question, and one of them had pushed manualEditsDom past the 600-line cap. The other two files were over from this branch's own work. The timeline mirror moves out of useDomSelection into a module of its own, and the shift-click candidate decision joins the predicate it already depends on in domEditOverlayGestures, which is where a reader looking for how a shift-click picks its element would go first. No behaviour change: same call order, same values, same tests.
…he cap domEditingLayers and timelineTimingSync were both a handful of lines over from this branch's additions. Same tightening as the rest: the prose says the same thing shorter and two single-return objects fit on one line.
Your log caught it across two resizes. The first commits 305x202 and the element is 305x202 at the drop; 200ms later it renders 395x261, its stylesheet size, while --hf-studio-width still reads 305. The second gesture then starts with `actual` at 305 against a live box of 395, and its very first move — a pointer delta of 0.1px — snaps the element back to 305. That snap is the jump. The gap belongs to the soft reload: it reverts the old timeline before building the new one, and GSAP hands back each tween's recorded starting width on the way out. Nothing held the size in between, because the seek reapply that exists for exactly this stands aside for elements GSAP animates. Standing aside is right for the offset — those channels compose, and applying both doubles the move — and wrong for size, where both channels write width and height so the later write simply wins on the same committed number. It applies now. Only an element mid-edit carries the vars, so nothing else is touched. A test seeks an element whose size GSAP owns after the revert put the stylesheet size back, and fails with the skip restored.
… that breaks away A link to a bug hit with several elements selected only reproduced one of them, so the report read as "works for me". The hash now carries the rest as selGroup and reopens the whole selection; members whose element is gone are dropped rather than failing the others. Verified end to end in a real browser: select three, copy the hash, open it fresh, the same three come back. The drag trace also gains a rigidity check. A group moves as one object, so every member travels the same distance; one that does not IS the fault. Drift was being computed but only printed on every eighth frame, which is exactly how a single-frame divergence hides — it now prints on the frame it happens. The frame handler moves to its own module on the way past. It had grown a snap block and a trace block inside a function already juggling four gesture kinds, and it was over both the complexity and file-size gates. Not fixed: the jump itself. Two headful runs driving a real group drag showed the members staying rigid to the pixel, at the drop and 900ms after, so I have not reproduced it yet and will not guess at a fix.
…ed yet Your log caught it on the first frame of the drag: pointer "0,0", applied "4,-3", and all four members jumped 12,-8 composition px before the pointer had moved at all. An element resting within the 6px snap threshold of a guide is already snappable, so the snap computed on frame one closes that gap immediately — picking the selection up moves it. Snapping now sits out until the gesture has travelled the same 4px a drag needs to count as a drag rather than a click, on both the group and single-element paths. Nothing below that distance moves anything, and a real drag snaps exactly as before. The test builds a box resting 4px from a guide and asserts the ungated call still returns dx 4 — the very displacement from your log — while the gated one returns 0 for a pointer that has not moved.
Your Jam confirmed the first-frame jump is gone — pointer "0,0" now reads applied "0,0" — and caught what was left: two milliseconds after each drop, a `[hf-select] clear` with the group still holding three, then four members. Every pointerup trails a click. The group gesture ref is cleared before the commit runs, so by the time that click arrives the box no longer looks busy and it reaches the canvas as an ordinary click — landing in the gap between the members, resolving to nothing, and clearing the selection the drag just moved. The under-threshold path already ate that click; the committed path never did. The flag is now set before the two paths diverge, so neither can forget it. The test drives a real pointerup through the handlers and fails on the committed path with the flag moved back down.
…the frame An element dragged past the edge sits out in the grey, and the rubber band refused to start there — it only began when the press landed inside the composition rect. The one gesture that could reach those elements could not be begun near them, so the timeline was the only way to select something plainly visible on screen. The collecting half never had that limit: it compares rects in overlay space and never clipped to the frame, so those elements have always been selectable once the band could begin. Only the start gate had to go. A press in the grey that never travels still commits an empty selection, which is the deselect it used to be, so the old behaviour of clicking out there to clear is unchanged.
Dragging several elements at once and dropping them made one of them snap back to where it started for a frame or two, then jump forward again. Each member of the group is written separately, and every write patched the live GSAP tween in place and then seeked the player. A seek re-renders the WHOLE timeline, not the tween that changed, so the members still queued behind that write got repainted from their un-patched tweens: back to their pre-drag position, where they sat until their own write landed. Only members whose tween actually renders at the playhead showed it, which is why a group of three flashed one element and left the others still. The group commit now defers the seek for every member but the last, so the queued members keep the transform the gesture left on them and the whole group repaints once, from the fully patched timeline.
Dragging N elements cost N writes and 9 reads for a three-element group: each member fetched the composition's parse to preflight, fetched it again to resolve its tween, then wrote the file on its own round trip. Every one of those writes re-read, re-parsed and re-serialized the whole composition. Three changes, same behaviour: - The parse endpoint shares an in-flight request per file, so callers asking for the same composition at the same moment get one request. Only overlapping calls share — the entry is dropped as soon as it settles, so a read after a write still gets a fresh parse. - The group preflight runs its members together instead of one at a time. A preflight writes nothing, so there is nothing to order. - Members' mutations are queued and sent as one batch write. Anything that re-reads the file flushes the queue first, so a member resolving a shared or stale tween never reads a composition missing writes it is about to build on. The batch carries each member's runtime patch, and only the last one re-renders. A three-element group drag now issues 2 reads and 1 write, down from 9 and 3.
Selecting text painted in more than one colour showed a white swatch. The toolbar reads a property only when the whole selection agrees on it, which is right for bold and italic (a toggle is on or off) but wrong for a swatch: with nothing to report it fell back to the default, so a red-and-green selection claimed to be white. The swatch now reads the colours as they run through the selection and draws one band per run, sized by how many characters carry it. Hard stops, not a fade — it reports the colours that are there, and a blend would draw colours that are not. A single-colour selection is a plain swatch, as before, and picking a colour still applies it to everything selected.
Bands read as two separate swatches sitting next to each other. Each colour now sits at the middle of its share and the browser fills between them, so the control looks like one swatch holding a mixed selection.
Colouring a whole element and then recolouring one word inside it leaves the spaces around that word carrying the first colour. The swatch counted them, so a red word inside green text drew a sliver of green, then red, then green — the element's colour appearing at an edge where no glyph is painted in it. Whitespace paints nothing, so it no longer contributes a colour. The swatch shows the colours the glyphs are actually drawn in, in the order they appear.
…border The swatch grew a green edge on its red side and a red edge on its green side. `background` maps a gradient to the padding box and then repeats it to fill the border box, so the 1px ring showed the strip either side of the tile: the gradient's end colour along the leading edge, its start colour along the trailing one, both read as a mirrored copy of the swatch. Painting from the border box instead gives the ring the colour the glyphs next to it are actually drawn in.
This was referenced Aug 9, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
Text in the canvas can now be edited and styled where it sits.
Double-press a text element and the caret opens at the point you pressed. Type, and it types. Select characters and a small toolbar appears over the selection with colour, bold, italic and underline, applied to exactly those characters. Enter commits, Escape cancels, clicking away keeps the work. Double click takes the word and triple click takes the lot, because nothing here claims either gesture.
Why
Changing a word previously meant leaving the canvas for the design panel, and styling part of a line was not possible at all.
Not possible for a concrete reason: Studio had no patch operation that could write markup. The vocabulary was
inline-style,attribute,html-attributeandtext-content, andtext-contentassignstextContent. The text-field model escapes markup withescapeHtmlTexton the way out, andbuildTextFieldChildOperationsreturnsnullwhen the child count changes, which throws. A<span>had no route to a composition file by any path.How
A
rich-textoperation, separate fromtext-content. Wideningtext-contentwould have turned the design panel and every other caller into a markup sink at once. The new operation is the only one that can carry markup, which keeps the dangerous one explicit and greppable.One sanitiser, in
packages/core, called on both ends. The client sanitises so the preview shows what will be saved; the server sanitises because it writes the file and a client is not a thing to trust. Two implementations would drift and the drift would be a security bug. The allowlist is small:span b strong i em u br,styleonly, and five paint-only properties. An unexpected tag is unwrapped, so a stray paste loses its formatting rather than the user's words.Styling rebuilds rather than wraps. Wrapping a DOM range is three lines and then every case is a special case: recolouring nests spans that shadow each other, removing a style cannot reach the ancestor that set it, styling across a run has to split it. Instead the element is read into a flat list of styled runs, the delta is applied to a span of characters, and the element is rebuilt. Replace, remove, split and merge stop being cases, and the markup cannot grow with repeated edits.
Layout is preserved in containers that box their children. In flex, grid or
-webkit-box, every child is an item to lay out, so text that was one anonymous item would become several the moment a word was styled, breaking centring and rewrapping the line. The runs go inside a single wrapper there.The selection chrome stands down while editing.
pointer-events: noneon the overlay does not disable a child that setsauto, and the selection box covers exactly the text being typed into. Left interactive it swallowed every press, so the caret could not be moved and characters could not be dragged over.Shortcut guards moved to a shared check. They matched
[contenteditable='true']and missed the editing surface, so playback shortcuts claimed letters typed into the composition:aseeked to the in-point instead of typing ana.Test plan
Suites on this branch: studio 3572 passing, studio-server 431, core utils 49. Around 120 tests are new.
Covered deliberately: the sanitiser against both parsers the codebase uses (jsdom and linkedom, which is what makes "one module, two runtimes" a claim rather than a hope); the server operation for hostile payloads, markup-shaped text, non-ASCII and idempotency; and the styling model for source newlines, emoji whose halves a selection boundary can fall between, a selection dragged outside the element, and flex or grid containers.
Verified by hand in Studio: styled a run, committed, read the span back out of the composition file on disk, reloaded and reopened the element for editing. Element measured 659x337 before and after styling a word inside it.
Known and deliberately left: a formatting span gets a fresh
data-hf-idon each restyle, which is diff noise on a line already being edited; preserving it means threading identity through a model that merges and splits runs. Deleting every character and committing empties the element, which then opens only through the design panel, unchanged from before.