Skip to content

Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.

feat(v0.15): rich text — per-span styling on the text element, one shared geometry module for all three renderers (R1)

Ashiq Hussain Mir2502d07c239c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c6eaf04..8523610 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,74 @@
All notable changes to Canvix will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
+## [0.15.0] — 2026-11-05
+
+### Added
+
+- **Rich content & export, part 1 — rich text (R1).** Per-range
+ styling inside a single text box: bold, italic, underline,
+ strikethrough, colour and links as `spans` — style runs laid over
+ `TextElement.text`, with the existing flat fields kept as the
+ inherit-base.
+ - **One geometry module for all three renderers** —
+ `src/lib/rich-text.ts` normalizes, sanitizes, edits and LAYS OUT
+ the runs (`layoutRichLines`: greedy word-wrap across span
+ boundaries, hard breaks for over-wide words, textarea `\n` as a
+ hard line break, trailing whitespace dropped at wraps, per-run
+ coalescing, align-resolved line x). The editor's Konva nodes, the
+ SVG serializer and the video-export frame builder all consume the
+ same `PositionedRun[]` — the D7 charts pattern, so no renderer
+ re-derives positions.
+ - **The editing UX** — the existing textarea overlay gains a
+ floating selection toolbar (B / I / U / S, a colour input, a link
+ popover with Apply/Remove, and clear-styling) that applies to the
+ current selection, plus a styled mirror layer behind a transparent
+ textarea so the formatting is visible while editing. Every
+ keystroke reconciles the runs (`reconcileSpans`: common
+ prefix/suffix diff — insert, delete, cut, paste and replace all
+ ride one path; typing at a style boundary extends the run you are
+ inside).
+ - **Migration is lossless by construction** — legacy elements have
+ no `spans` and render through the untouched flat path; styling a
+ range CREATES the array; clearing it returns to flat with the base
+ fields never modified. A malformed array (text-length mismatch,
+ over the 128-run cap) normalizes to `null` — styling data can
+ never corrupt the text. 38 new unit tests cover the module
+ (sanitization, normalization, range ops, keystroke reconcile,
+ layout math with a deterministic fake measure).
+ - **Security** — links are http(s)-only, control-char-stripped and
+ length-capped (`sanitizeLink`, fail-closed) on every write path:
+ the editor toolbar, the MCP `update_element` patch whitelist, and
+ the normalize pass. The MCP patch validates runs against the
+ (possibly simultaneously patched) text and drops malformed arrays
+ instead of storing them.
+ - **Two bugs found by the new e2e while wiring the renderers,
+ both fixed**: the rich `Group`'s tight glyph `clientRect` put the
+ Transformer's anchors on the text itself (a click at the element
+ centre hit a bottom anchor and fired a phantom `transformstart`,
+ eating an undo step — now a transparent hit rect keeps the
+ declared box exactly like the flat `Konva.Text`), and a blur from
+ the textarea into the link popover committed the editing session
+ early (blur now ignores focus moves inside the toolbar).
+ - **Honest limits, on the record** — collab merge stays whole-box
+ LWW: two offline editors of one text box still last-writer-win
+ the ENTIRE element (text + spans ride together; per-span stamps
+ are a post-1.0 evaluation on real usage). Curved text
+ (`curve ≠ 0`) ignores spans in all three renderers. The splice
+ ghost-copies effect falls back to the flat path. SVG exports
+ render links styled (blue + underline) but not as clickable
+ `<a>` anchors. Gradient fills map across the whole element box
+ via per-run point offsets.
+ - **e2e acceptance** (anonymous, zero registrations): a legacy flat
+ element opens losslessly; bolding a range saves exactly
+ `[{Hello, bold}, { rich world}]` with the text untouched; the
+ mirror carries `<strong>` while editing; ONE undo reverts the
+ spans to null; the exported SVG contains both `font-weight="700"`
+ and `font-weight="400"` tspans; a `javascript:` URL applied
+ through the UI is stripped (never stored) while an `https://` URL
+ survives; the properties-bar "Rich text · Clear" chip flattens
+ the element.
+
## [0.14.5] — 2026-11-05
### Added
diff --git a/README.md b/README.md
index 67ec6d7..dc64053 100644
--- a/README.md
+++ b/README.md
@@ -1013,6 +1013,29 @@ tool descriptions so agents pick the right format.
measured the span off by the last box's size and refused
overlapping selections (Canva/Figma distribute those; now so
does Canvix) *(v0.14.5)*
+- [x] Rich text (v0.15 R1) — per-range styling inside ONE text box:
+ bold / italic / underline / strikethrough / colour / links as style
+ runs (`spans`) over the existing flat fields, which stay the
+ inherit-base. One shared geometry module (`src/lib/rich-text.ts`)
+ lays out the runs and the editor canvas, the SVG serializer and the
+ video-export frame builder all draw the SAME positions (the D7
+ charts pattern). Editing rides the existing textarea overlay with a
+ floating selection toolbar (B/I/U/S, colour, link, clear) and a
+ styled mirror so you see the formatting as you apply it; typing
+ reconciles the runs per keystroke. Migration is lossless by
+ construction — legacy elements render through the untouched flat
+ path until a user styles a range, and "Clear styling" drops the
+ spans with the base fields never having been touched. Links are
+ http(s)-only (`sanitizeLink` fail-closed — `javascript:` and
+ friends are stripped on every write path: editor, MCP
+ `update_element`, normalize). Undo is ONE step per editing session.
+ Honest limits, on the record: **collab merge stays whole-box LWW**
+ — two offline editors of one text box still last-writer-win the
+ entire element (text + spans together; per-span stamps are a
+ post-1.0 evaluation on real usage) — curved text (`curve ≠ 0`)
+ ignores spans in all three renderers, the splice ghost-copies
+ effect falls back to the flat path, and SVG exports render links
+ styled but not as `<a>` anchors. *(v0.15.0)*
- [ ] Mobile editor polish — touch-first selection handles, gesture
zoom/pan without modifier keys, bottom-sheet property panels
(the responsive groundwork from v0.11.3 makes this tractable)
diff --git a/package.json b/package.json
index d417e33..990a658 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "canvix",
- "version": "0.14.5",
+ "version": "0.15.0",
"private": false,
"description": "Canvix \u2014 free & open-source graphic design tool. A community-built Canva alternative.",
"scripts": {
diff --git a/public/plugins/wordcloud/manifest.json b/public/plugins/wordcloud/manifest.json
index 072cf14..2217f57 100644
--- a/public/plugins/wordcloud/manifest.json
+++ b/public/plugins/wordcloud/manifest.json
@@ -9,7 +9,7 @@
"url": "https://github.com/mir-ashiq/canvix"
},
"engines": {
- "canvix": ">=0.13.4 <0.15.0"
+ "canvix": ">=0.13.4 <0.16.0"
},
"entry": {
"panel": "panel.html",
diff --git a/src/app/globals.css b/src/app/globals.css
index bb26426..7b59e38 100644
--- a/src/app/globals.css
+++ b/src/app/globals.css
@@ -538,3 +538,87 @@ input[type="number"] {
.cv-panel-bg {
background: var(--cv-panel);
}
+
+/* ── v0.15 (R1): rich-text editing overlay ─────────────────── */
+
+/* styled mirror behind the (transparent) textarea — same geometry,
+ same font metrics, pointer-transparent */
+.cv-rich-mirror {
+ position: absolute;
+ pointer-events: none;
+ border: none;
+ background: transparent;
+ white-space: pre-wrap;
+ word-wrap: break-word;
+ overflow-wrap: break-word;
+ overflow: hidden;
+ transform-origin: top left;
+ z-index: 39; /* under the textarea overlay (z-index 40) */
+ padding: 0;
+ margin: 0;
+}
+
+/* the floating selection toolbar (B / I / U / S / colour / link) */
+.cv-rich-toolbar {
+ position: absolute;
+ z-index: 45;
+ display: flex;
+ align-items: center;
+ gap: 2px;
+ padding: 4px 6px;
+ background: var(--cv-surface, #1f2226);
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ border-radius: 10px;
+ box-shadow: 0 6px 24px rgba(0, 0, 0, 0.45);
+ transform-origin: top left;
+}
+
+.cv-rich-toolbar .cv-tbtn {
+ width: 28px;
+ height: 28px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ flex-shrink: 0;
+}
+
+.cv-rich-color-input {
+ width: 18px;
+ height: 18px;
+ padding: 0;
+ border: none;
+ background: transparent;
+ cursor: pointer;
+}
+
+/* the link editor popover (opens off the Link button) */
+.cv-rich-link-pop {
+ position: absolute;
+ top: 36px;
+ left: 0;
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ padding: 6px;
+ background: var(--cv-surface, #1f2226);
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ border-radius: 8px;
+ z-index: 46;
+ box-shadow: 0 6px 24px rgba(0, 0, 0, 0.45);
+}
+
+.cv-rich-link-pop input {
+ width: 200px;
+ height: 28px;
+ padding: 0 8px;
+ font-size: 12px;
+ color: #fff;
+ background: rgba(255, 255, 255, 0.08);
+ border: 1px solid rgba(255, 255, 255, 0.15);
+ border-radius: 6px;
+ outline: none;
+}
+
+.cv-rich-link-pop input:focus {
+ border-color: var(--cv-violet, #9954ff);
+}
diff --git a/src/components/editor/PropertiesBar.tsx b/src/components/editor/PropertiesBar.tsx
index 4ce21e6..5534210 100644
--- a/src/components/editor/PropertiesBar.tsx
+++ b/src/components/editor/PropertiesBar.tsx
@@ -22,6 +22,7 @@ import { beatSourceOf } from '@/lib/media/beat-detect'
import { cn } from '@/lib/utils'
import { getPluginSystemState, subscribePluginSystem } from '@/lib/plugins/renderer-cache'
import { applyDesignAction } from '@/lib/design-actions'
+import { normalizeSpans } from '@/lib/rich-text'
import { FontDropdown } from './toolbar/FontDropdown'
import { ColorMenu } from './toolbar/ColorMenu'
import { IMAGE_FILTER_PRESETS, applyPresetToImageData, isImageFilterId, clampFilterIntensity } from '@/lib/image-filters'
@@ -142,18 +143,36 @@ export function ContextToolbar({ variant = 'topbar' }: { variant?: 'topbar' | 'm
title="Text colour"
/>
- <TBtn onClick={() => update(ids, { bold: !text.bold })} dataActive={text.bold} title="Bold" ariaLabel="Bold">
- <Bold size={14} />
- </TBtn>
- <TBtn onClick={() => update(ids, { italic: !text.italic })} dataActive={text.italic} title="Italic" ariaLabel="Italic">
- <Italic size={14} />
- </TBtn>
- <TBtn onClick={() => update(ids, { underline: !text.underline })} dataActive={text.underline} title="Underline" ariaLabel="Underline">
- <Underline size={14} />
- </TBtn>
- <TBtn onClick={() => update(ids, { strike: !text.strike })} dataActive={text.strike} title="Strikethrough" ariaLabel="Strikethrough">
- <Strikethrough size={14} />
- </TBtn>
+ {/* v0.15 (R1): while the element carries rich spans, per-range
+ styles rule the canvas — offer the honest one-click clear back
+ to the flat base style instead of misleading flat toggles */}
+ {normalizeSpans(text.spans, text.text) ? (
+ <button
+ className="cv-tbtn"
+ style={{ width: 'auto', padding: '0 10px', fontSize: 11, gap: 6 }}
+ onClick={() => update(ids, { spans: null })}
+ title="Rich text active — clear per-range styling back to the base style"
+ aria-label="Clear rich text styling"
+ data-testid="clear-rich-text"
+ >
+ Rich text · Clear
+ </button>
+ ) : (
+ <>
+ <TBtn onClick={() => update(ids, { bold: !text.bold })} dataActive={text.bold} title="Bold" ariaLabel="Bold">
+ <Bold size={14} />
+ </TBtn>
+ <TBtn onClick={() => update(ids, { italic: !text.italic })} dataActive={text.italic} title="Italic" ariaLabel="Italic">
+ <Italic size={14} />
+ </TBtn>
+ <TBtn onClick={() => update(ids, { underline: !text.underline })} dataActive={text.underline} title="Underline" ariaLabel="Underline">
+ <Underline size={14} />
+ </TBtn>
+ <TBtn onClick={() => update(ids, { strike: !text.strike })} dataActive={text.strike} title="Strikethrough" ariaLabel="Strikethrough">
+ <Strikethrough size={14} />
+ </TBtn>
+ </>
+ )}
<TBtn onClick={() => update(ids, { uppercase: !text.uppercase })} dataActive={text.uppercase} title="Uppercase" ariaLabel="Uppercase">
<CaseUpper size={14} />
</TBtn>
diff --git a/src/components/editor/canvas/CanvasStage.tsx b/src/components/editor/canvas/CanvasStage.tsx
index 612d174..07a7ce1 100644
--- a/src/components/editor/canvas/CanvasStage.tsx
+++ b/src/components/editor/canvas/CanvasStage.tsx
@@ -16,6 +16,17 @@ import { CollabOverlay } from './CollabOverlay'
import { CommentPins } from './CommentPins'
import { getActiveCollabSession } from '@/hooks/use-collab'
import { tableGeometry } from '@/lib/v06-geometry'
+import {
+ applyStyleToRange,
+ LINK_COLOR,
+ normalizeSpans,
+ reconcileSpans,
+ styleStateInRange,
+ type RangeStyleState,
+ type SpanStylePatch,
+} from '@/lib/rich-text'
+import type { TextSpan } from '@/lib/types'
+import { Bold, Check, Italic, Link2, Strikethrough, Underline, X } from 'lucide-react'
/** canva-measured tokens */
const GUIDE_COLOR = '#9954FF' // rgb(153,84,255) — measured 2026-09-03
@@ -68,6 +79,20 @@ export default function CanvasStage() {
/** v0.6: table cell being edited via the overlay ({ id, row, col }) */
const [editingCell, setEditingCell] = useState<{ id: string; row: number; col: number } | null>(null)
const [editValue, setEditValue] = useState('')
+ /** v0.15 (R1): rich text — spans for the element being edited (null = flat) */
+ const [editSpans, setEditSpans] = useState<TextSpan[] | null>(null)
+ /** toolbar chip state for the CURRENT textarea selection */
+ const [selState, setSelState] = useState<RangeStyleState | null>(null)
+ /** true while the textarea has a NON-collapsed selection (drives the
+ * toolbar buttons' disabled state) */
+ const [hasSelRange, setHasSelRange] = useState(false)
+ /** link popover */
+ const [linkOpen, setLinkOpen] = useState(false)
+ const [linkDraft, setLinkDraft] = useState('')
+ /** live mirror of {value, spans} — the onChange diff needs the PREVIOUS
+ * value synchronously, and commit must read the freshest spans */
+ const textEditRef = useRef<{ value: string; spans: TextSpan[] | null }>({ value: '', spans: null })
+ const textAreaRef = useRef<HTMLTextAreaElement | null>(null)
/** freehand draft: [x0,y0,x1,y1,…] in page coords */
const [draft, setDraft] = useState<number[] | null>(null)
/** marquee draft in PAGE coords */
@@ -290,7 +315,14 @@ export default function CanvasStage() {
// if the text lives inside a group, edit via double-click is disabled for simplicity
state.pushHistory()
setEditingTextId(id)
- setEditValue((el as TextElement).text)
+ const startText = (el as TextElement).text
+ const startSpans = normalizeSpans((el as TextElement).spans ?? null, startText)
+ setEditValue(startText)
+ setEditSpans(startSpans)
+ textEditRef.current = { value: startText, spans: startSpans }
+ setSelState(null)
+ setHasSelRange(false)
+ setLinkOpen(false)
}, [])
const commitEditText = useCallback(async () => {
@@ -311,7 +343,12 @@ export default function CanvasStage() {
}
if (!id) return
setEditingTextId(null)
- useEditorStore.getState().updateElementsLive([id], { text })
+ setEditSpans(null)
+ setSelState(null)
+ setHasSelRange(false)
+ setLinkOpen(false)
+ const final = textEditRef.current
+ useEditorStore.getState().updateElementsLive([id], { text: final.value, spans: final.spans })
// sync measured height after the Konva text re-renders
requestAnimationFrame(() =>
requestAnimationFrame(() => {
@@ -682,6 +719,27 @@ export default function CanvasStage() {
const editingText = editingTextId ? (page.elements.find((e) => e.id === editingTextId) as TextElement | undefined) : undefined
+ /** v0.15 (R1): apply a rich-text style patch to the CURRENT textarea
+ * selection (one live element patch — the editing session already owns
+ * a single history entry from beginEditText, so undo stays one step). */
+ const applyRichStyle = useCallback(
+ (patch: SpanStylePatch) => {
+ const ta = textAreaRef.current
+ if (!ta || !editingTextId) return
+ const start = ta.selectionStart
+ const end = ta.selectionEnd
+ if (start === end) return
+ const cur = textEditRef.current
+ const next = applyStyleToRange(cur.spans, cur.value, start, end, patch)
+ textEditRef.current = { value: cur.value, spans: next }
+ setEditSpans(next)
+ useEditorStore.getState().updateElementsLive([editingTextId], { spans: next })
+ setSelState(styleStateInRange(next, cur.value, start, end))
+ setHasSelRange(start !== end)
+ },
+ [editingTextId],
+ )
+
// v0.6: table cell overlay geometry
const editingTable = editingCell ? (page.elements.find((e) => e.id === editingCell.id) as import('@/lib/types').TableElement | undefined) : undefined
const cellStyle: React.CSSProperties | null = editingTable && editingCell
@@ -919,31 +977,146 @@ export default function CanvasStage() {
/>
)}
+ {/* v0.15 (R1): rich-text editing — floating selection toolbar */}
+ {editingText && textareaStyle && (editingText.curve ?? 0) === 0 && (
+ <div
+ className="cv-rich-toolbar"
+ role="toolbar"
+ aria-label="Rich text formatting"
+ data-testid="rich-toolbar"
+ style={{
+ left: Math.max(8, pan.x + editingText.x * zoom),
+ top: Math.max(8, pan.y + editingText.y * zoom - 46),
+ }}
+ onMouseDown={(e) => {
+ // keep the textarea's selection & focus — but never block the
+ // native colour picker's own activation
+ if (!(e.target as HTMLElement).closest('input')) e.preventDefault()
+ }}
+ >
+ <button className="cv-tbtn" title="Bold" aria-label="Bold selection" data-active={selState?.bold === 'all' ? 'true' : undefined} disabled={!hasSelRange} onClick={() => applyRichStyle({ bold: selState?.bold !== 'all' })}>
+ <Bold size={14} />
+ </button>
+ <button className="cv-tbtn" title="Italic" aria-label="Italic selection" data-active={selState?.italic === 'all' ? 'true' : undefined} disabled={!hasSelRange} onClick={() => applyRichStyle({ italic: selState?.italic !== 'all' })}>
+ <Italic size={14} />
+ </button>
+ <button className="cv-tbtn" title="Underline" aria-label="Underline selection" data-active={selState?.underline === 'all' ? 'true' : undefined} disabled={!hasSelRange} onClick={() => applyRichStyle({ underline: selState?.underline !== 'all' })}>
+ <Underline size={14} />
+ </button>
+ <button className="cv-tbtn" title="Strikethrough" aria-label="Strikethrough selection" data-active={selState?.strike === 'all' ? 'true' : undefined} disabled={!hasSelRange} onClick={() => applyRichStyle({ strike: selState?.strike !== 'all' })}>
+ <Strikethrough size={14} />
+ </button>
+ <label className="cv-tbtn" title="Colour" aria-label="Colour selection" style={{ position: 'relative', overflow: 'hidden' }}>
+ <input
+ type="color"
+ className="cv-rich-color-input"
+ aria-label="Rich text colour"
+ value={typeof selState?.color === 'string' ? selState.color : '#FFFFFF'}
+ onChange={(e) => applyRichStyle({ color: e.target.value })}
+ />
+ </label>
+ <button className="cv-tbtn" title="Link" aria-label="Link selection" data-active={selState?.link ? 'true' : undefined} onClick={() => { setLinkDraft(typeof selState?.link === 'string' ? selState.link : ''); setLinkOpen((o) => !o) }}>
+ <Link2 size={14} />
+ </button>
+ <button className="cv-tbtn" title="Clear styling" aria-label="Clear styling" disabled={!hasSelRange} onClick={() => applyRichStyle({ bold: false, italic: false, underline: false, strike: false, color: null, link: null })}>
+ <X size={14} />
+ </button>
+ {linkOpen && (
+ <span className="cv-rich-link-pop" role="dialog" aria-label="Link editor">
+ <input
+ aria-label="Link URL"
+ placeholder="https://…"
+ value={linkDraft}
+ onChange={(e) => setLinkDraft(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') {
+ e.preventDefault()
+ applyRichStyle({ link: linkDraft })
+ setLinkOpen(false)
+ }
+ e.stopPropagation()
+ }}
+ />
+ <button className="cv-tbtn" title="Apply link" aria-label="Apply link" onClick={() => { applyRichStyle({ link: linkDraft }); setLinkOpen(false) }}>
+ <Check size={14} />
+ </button>
+ <button className="cv-tbtn" title="Remove link" aria-label="Remove link" disabled={selState?.link == null} onClick={() => { applyRichStyle({ link: null }); setLinkOpen(false) }}>
+ <X size={14} />
+ </button>
+ </span>
+ )}
+ </div>
+ )}
+
{/* text editing overlay */}
{editingText && textareaStyle && (
- <textarea
- className="cv-textarea-overlay"
- style={textareaStyle}
- value={editValue}
- autoFocus
- onChange={(e) => {
- setEditValue(e.target.value)
- useEditorStore.getState().updateElementsLive([editingText.id], { text: e.target.value })
- }}
- onBlur={() => void commitEditText()}
- onKeyDown={(e) => {
- if (e.key === 'Escape') {
- e.preventDefault()
+ <>
+ {editSpans && (
+ <div
+ className="cv-rich-mirror"
+ aria-hidden="true"
+ data-testid="rich-mirror"
+ style={{ ...textareaStyle, outline: 'none', color: editingText.fill }}
+ >
+ {editSpans.map((s, i) => {
+ let node: React.ReactNode = s.text
+ if (s.bold) node = <strong>{node}</strong>
+ if (s.italic) node = <em>{node}</em>
+ const color = s.color ?? (s.link ? LINK_COLOR : undefined)
+ const decor = [s.underline ? 'underline' : '', s.strike ? 'line-through' : ''].filter(Boolean).join(' ')
+ if (color || decor || s.link) {
+ node = (
+ <span style={{ color, textDecoration: decor || (s.link ? 'underline' : undefined) }}>
+ {node}
+ </span>
+ )
+ }
+ return <span key={i}>{node}</span>
+ })}
+ </div>
+ )}
+ <textarea
+ ref={textAreaRef}
+ className={`cv-textarea-overlay${editSpans ? ' cv-rich-editing' : ''}`}
+ style={editSpans ? { ...textareaStyle, color: 'transparent', caretColor: editingText.fill } : textareaStyle}
+ value={editValue}
+ autoFocus
+ onChange={(e) => {
+ const v = e.target.value
+ const prev = textEditRef.current
+ const nextSpans = reconcileSpans(prev.spans, prev.value, v)
+ textEditRef.current = { value: v, spans: nextSpans }
+ setEditValue(v)
+ setEditSpans(nextSpans)
+ useEditorStore.getState().updateElementsLive([editingText.id], { text: v, spans: nextSpans })
+ }}
+ onSelect={(e) => {
+ const ta = e.currentTarget
+ setHasSelRange(ta.selectionStart !== ta.selectionEnd)
+ setSelState(styleStateInRange(textEditRef.current.spans, textEditRef.current.value, ta.selectionStart, ta.selectionEnd))
+ }}
+ onBlur={(e) => {
+ // v0.15 (R1): focus moving INTO the floating toolbar (colour
+ // picker, link popover input) is not an editing-session exit
+ // — only a blur outside the whole overlay commits
+ const related = e.relatedTarget as HTMLElement | null
+ if (related && related.closest('.cv-rich-toolbar')) return
void commitEditText()
- }
- e.stopPropagation()
- }}
- onFocus={(e) => {
- const len = e.target.value.length
- e.target.setSelectionRange(len, len)
- }}
- aria-label="Edit text"
- />
+ }}
+ onKeyDown={(e) => {
+ if (e.key === 'Escape') {
+ e.preventDefault()
+ void commitEditText()
+ }
+ e.stopPropagation()
+ }}
+ onFocus={(e) => {
+ const len = e.target.value.length
+ e.target.setSelectionRange(len, len)
+ }}
+ aria-label="Edit text"
+ />
+ </>
)}
{/* v0.6: table cell editing overlay */}
diff --git a/src/components/editor/canvas/element-node.tsx b/src/components/editor/canvas/element-node.tsx
index b8727a8..6d3cbac 100644
--- a/src/components/editor/canvas/element-node.tsx
+++ b/src/components/editor/canvas/element-node.tsx
@@ -26,6 +26,8 @@ import { elementGradientProps } from '@/lib/editor-utils'
import { useEditorStore } from '@/store/editor-store'
import { useLoadedImage } from './use-loaded-image'
import { isImageFilterId, clampFilterIntensity, applyPresetToImageData } from '@/lib/image-filters'
+import { createCanvasMeasure, layoutRichLines, normalizeSpans } from '@/lib/rich-text'
+import type { TextSpan } from '@/lib/types'
import { CurvedTextNode, EmbedNode, FrameNode, TableNode, type TableCellRef } from './v06-nodes'
import { PluginNode } from './PluginNode'
import { ChartNode } from './chart-node'
@@ -68,6 +70,99 @@ function shadowProps(el: AnyElement) {
}
/** canva-style text effect presets → Konva text attrs */
+/** v0.15 (R1): the browser-side measure for rich text layout — canvas 2d
+ * with the codebase's graceful no-canvas fallback (svg-export pattern). */
+const richMeasure = createCanvasMeasure()
+
+/** shift a Konva gradient's anchor points so a per-run node maps the
+ * ELEMENT-box gradient continuously instead of restarting per run */
+function shiftGradientForRun(grad: Record<string, unknown>, dx: number, dy: number): Record<string, unknown> {
+ const pointKeys = new Set([
+ 'fillLinearGradientStartPoint', 'fillLinearGradientEndPoint',
+ 'fillRadialGradientStartPoint', 'fillRadialGradientEndPoint',
+ ])
+ const out: Record<string, unknown> = {}
+ for (const [k, v] of Object.entries(grad)) {
+ if (pointKeys.has(k) && v && typeof v === 'object') {
+ const p = v as { x: number; y: number }
+ out[k] = { x: p.x - dx, y: p.y - dy }
+ } else {
+ out[k] = v
+ }
+ }
+ return out
+}
+
+/**
+ * v0.15 (R1): rich text — one Konva.Text per positioned run at the exact
+ * coordinates from the shared geometry module (src/lib/rich-text.ts);
+ * the SVG serializer and the video-export frame builder draw the SAME
+ * positions. Gradient fills map across the whole element box via
+ * per-run point offsets; hollow/outline strokes follow the run colour.
+ * The Group carries an explicit block height so the post-edit height
+ * sync (CanvasStage's rAF) reads the true text block height, matching
+ * the flat Konva.Text behaviour.
+ */
+function RichTextNode({
+ t,
+ spans,
+ common,
+ effect,
+}: {
+ t: TextElement
+ spans: TextSpan[]
+ common: Record<string, unknown>
+ effect: Record<string, unknown>
+}) {
+ const runs = useMemo(() => layoutRichLines(t, spans, richMeasure), [t, spans])
+ const blockH = runs.length
+ ? Math.max(...runs.map((r) => r.y)) + t.fontSize * t.lineHeight
+ : t.fontSize * t.lineHeight
+ const grad =
+ t.fillGradient && (!t.effect || ['none', 'shadow', 'lift', 'echo', 'splice'].includes(t.effect))
+ ? elementGradientProps(t.fillGradient, t.width, Math.max(t.height, blockH), 'corner')
+ : {}
+ const strokeEffect = t.effect === 'hollow' || t.effect === 'outline'
+ return (
+ <Group {...common} height={blockH}>
+ {/* the element's declared box as a transparent hit rect — keeps the
+ Group's clientRect (and therefore the Transformer's anchors and
+ the click/marquee hit region) on the DECLARED box exactly like
+ the flat Konva.Text, instead of the tight glyph bbox (without
+ it, a click at the element centre lands on a bottom anchor and
+ fires a phantom transformstart → an undo step that changes
+ nothing) */}
+ <Rect width={t.width} height={Math.max(t.height, blockH)} fill="transparent" perfectDrawEnabled={false} />
+ {t.effect === 'background' && (
+ <Rect width={t.width} height={Math.max(t.height, blockH)} fill={t.effectBackground ?? '#EFEFEF'} cornerRadius={Math.min(8, t.fontSize * 0.2)} />
+ )}
+ {runs.map((run, i) => {
+ const runGrad =
+ Object.keys(grad).length && !strokeEffect && run.style.color === t.fill
+ ? shiftGradientForRun(grad, run.x, run.y)
+ : {}
+ const runEffect = strokeEffect ? { ...effect, fill: 'transparent', stroke: run.style.color } : effect
+ return (
+ <Text
+ key={i}
+ x={run.x}
+ y={run.y}
+ text={run.text}
+ fontSize={t.fontSize}
+ fontFamily={t.fontFamily}
+ fontStyle={`${run.style.italic ? 'italic ' : ''}${run.style.bold ? 'bold' : 'normal'}`}
+ textDecoration={[run.style.underline ? 'underline' : '', run.style.strike ? 'line-through' : ''].filter(Boolean).join(' ')}
+ fill={Object.keys(runGrad).length ? undefined : run.style.color}
+ {...runGrad}
+ {...runEffect}
+ perfectDrawEnabled={false}
+ />
+ )
+ })}
+ </Group>
+ )
+}
+
function textEffectProps(t: TextElement): Record<string, string | number> {
switch (t.effect) {
case 'shadow':
@@ -474,6 +569,13 @@ function ElementNodeImpl({ element: el, interactive, hiding, hideCell, registerN
const t = el as TextElement
const effect = t.effect && t.effect !== 'none' ? textEffectProps(t) : {}
const rendered = t.uppercase ? t.text.toUpperCase() : t.text
+ // v0.15 (R1): rich text — spans render through the shared layout;
+ // curved text and the splice ghost-copies effect stay on the flat
+ // path (single-style by design, documented in README · R1)
+ const richSpans = (t.curve ?? 0) === 0 && t.effect !== 'splice' ? normalizeSpans(t.spans, t.text) : null
+ if (richSpans) {
+ return <RichTextNode t={t} spans={richSpans} common={common} effect={effect} />
+ }
// gradient fill (skipped for effects that own the fill, e.g. Hollow)
const textGrad: GradientFill | null | undefined = t.fillGradient
const gradProps =
diff --git a/src/lib/mcp/tools.ts b/src/lib/mcp/tools.ts
index 61e8828..0f61916 100644
--- a/src/lib/mcp/tools.ts
+++ b/src/lib/mcp/tools.ts
@@ -25,6 +25,7 @@ import {
type ChartKind,
} from '@/lib/types'
import { isChartKind, sanitizeChartLabels, sanitizeChartSeries, clampChartHole, CHART_PALETTE } from '@/lib/chart-geometry'
+import { normalizeSpans } from '@/lib/rich-text'
export const SERVER_VERSION = '0.6.1'
@@ -1212,7 +1213,7 @@ export function buildTools(deps: ToolDeps): ToolDef[] {
// ── patch sanitizer (whitelist per element type) ──────────────
const COMMON_KEYS = new Set(['x', 'y', 'width', 'height', 'rotation', 'opacity', 'visible', 'locked', 'name'])
-const TEXT_KEYS = new Set([...COMMON_KEYS, 'text', 'fontSize', 'fontFamily', 'bold', 'italic', 'underline', 'strike', 'uppercase', 'fill', 'align', 'lineHeight', 'letterSpacing', 'curve'])
+const TEXT_KEYS = new Set([...COMMON_KEYS, 'text', 'fontSize', 'fontFamily', 'bold', 'italic', 'underline', 'strike', 'uppercase', 'fill', 'align', 'lineHeight', 'letterSpacing', 'curve', 'spans'])
const SHAPE_KEYS = new Set([...COMMON_KEYS, 'fill', 'stroke', 'strokeWidth', 'cornerRadius'])
const IMAGE_KEYS = new Set([...COMMON_KEYS, 'src', 'radius', 'brightness', 'contrast', 'saturation', 'filter', 'filterIntensity'])
const TABLE_KEYS = new Set([...COMMON_KEYS, 'rows', 'cols', 'cells', 'colWidths', 'rowHeight', 'borderColor', 'borderWidth', 'headerFill', 'textColor', 'fontSize', 'fontFamily'])
@@ -1262,6 +1263,14 @@ function sanitizePatch(patch: Record<string, unknown>, el: AnyElement, pageW: nu
case 'title':
out[key] = asString(value).slice(0, 500)
break
+ // v0.15 (R1): rich text — runs are normalized against the possibly-
+ // patched text (patch {text, spans} lands atomically); a malformed
+ // array is dropped to null (flat), never stored, never corrupts text
+ case 'spans': {
+ const effectiveText = typeof out.text === 'string' ? out.text : ((el as { text?: string }).text ?? '')
+ out.spans = normalizeSpans(Array.isArray(value) ? (value as import('@/lib/types').TextSpan[]) : null, effectiveText)
+ break
+ }
case 'fill':
case 'stroke':
case 'borderColor':
diff --git a/src/lib/rich-text.test.ts b/src/lib/rich-text.test.ts
new file mode 100644
index 0000000..ee3b1c1
--- /dev/null
+++ b/src/lib/rich-text.test.ts
@@ -0,0 +1,320 @@
+import { describe, expect, it } from 'vitest'
+import {
+ applyStyleToRange,
+ layoutRichLines,
+ MAX_SPANS,
+ normalizeSpans,
+ reconcileSpans,
+ resolveLineX,
+ resolveSpanStyle,
+ sanitizeLink,
+ styleStateInRange,
+ type MeasureText,
+} from './rich-text'
+import type { TextElement, TextSpan } from './types'
+
+function makeText(overrides: Partial<TextElement> = {}): TextElement {
+ return {
+ id: 't1',
+ type: 'text',
+ name: 'text',
+ x: 100,
+ y: 50,
+ width: 400,
+ height: 80,
+ rotation: 0,
+ opacity: 1,
+ locked: false,
+ visible: true,
+ text: 'Hello world',
+ fontSize: 32,
+ fontFamily: 'Poppins',
+ bold: false,
+ italic: false,
+ underline: false,
+ strike: false,
+ uppercase: false,
+ fill: '#1F2226',
+ align: 'left',
+ lineHeight: 1.4,
+ letterSpacing: 0,
+ ...overrides,
+ } as TextElement
+}
+
+/** deterministic fake: every character is 10px wide, +letterSpacing per char */
+const fakeMeasure: MeasureText = (text, style) => text.length * 10 + style.letterSpacing * text.length
+
+// ── sanitizeLink ───────────────────────────────────────────────
+
+describe('sanitizeLink', () => {
+ it('accepts http and https, trims and strips control chars', () => {
+ expect(sanitizeLink('https://example.com/a?b=1')).toBe('https://example.com/a?b=1')
+ expect(sanitizeLink('http://example.com')).toBe('http://example.com')
+ expect(sanitizeLink(' https://example.com ')).toBe('https://example.com')
+ expect(sanitizeLink('https://exa\nmple.com')).toBe('https://example.com')
+ expect(sanitizeLink('HTTPS://EXAMPLE.COM')).toBe('HTTPS://EXAMPLE.COM')
+ })
+ it('fails closed on every dangerous shape', () => {
+ expect(sanitizeLink('javascript:alert(1)')).toBeNull()
+ expect(sanitizeLink(' data:text/html,<script>')).toBeNull()
+ expect(sanitizeLink('vbscript:msgbox')).toBeNull()
+ expect(sanitizeLink('/design/abc')).toBeNull()
+ expect(sanitizeLink('example.com')).toBeNull()
+ expect(sanitizeLink('')).toBeNull()
+ expect(sanitizeLink(null)).toBeNull()
+ expect(sanitizeLink(undefined)).toBeNull()
+ expect(sanitizeLink('https://' + 'a'.repeat(600))).toBeNull()
+ })
+})
+
+// ── normalizeSpans ─────────────────────────────────────────────
+
+describe('normalizeSpans', () => {
+ it('returns null for absent / empty / single-plain', () => {
+ expect(normalizeSpans(null, 'abc')).toBeNull()
+ expect(normalizeSpans(undefined, 'abc')).toBeNull()
+ expect(normalizeSpans([], 'abc')).toBeNull()
+ expect(normalizeSpans([{ text: 'abc' }], 'abc')).toBeNull()
+ expect(normalizeSpans([{ text: 'abc', bold: false }], 'abc')).toBeNull()
+ })
+ it('drops empty runs and merges adjacent same-style runs', () => {
+ const out = normalizeSpans([{ text: '' }, { text: 'ab', bold: true }, { text: 'cd', bold: true }, { text: 'e' }], 'abcde')
+ expect(out).toEqual([{ text: 'abcd', bold: true }, { text: 'e' }])
+ })
+ it('falsy booleans normalize to inherit and merge with plain runs', () => {
+ const out = normalizeSpans([{ text: 'a', bold: false }, { text: 'b' }], 'ab')
+ expect(out).toBeNull()
+ })
+ it('drops invalid links and over-long colours', () => {
+ const out = normalizeSpans([{ text: 'ab', link: 'javascript:x' }, { text: 'cd', color: 'x'.repeat(65) }], 'abcd')
+ expect(out).toBeNull()
+ const kept = normalizeSpans([{ text: 'ab', link: 'https://ok.dev' }, { text: 'cd', color: '#FF0000' }], 'abcd')
+ expect(kept).toEqual([{ text: 'ab', link: 'https://ok.dev' }, { text: 'cd', color: '#FF0000' }])
+ })
+ it('fails safe (null) on text-length mismatch and run-cap overflow', () => {
+ expect(normalizeSpans([{ text: 'abc', bold: true }], 'abcd')).toBeNull()
+ const many: TextSpan[] = []
+ for (let i = 0; i < MAX_SPANS + 5; i++) many.push({ text: 'a', bold: i % 2 === 0 })
+ expect(normalizeSpans(many, 'a'.repeat(MAX_SPANS + 5))).toBeNull()
+ })
+ it('never mutates its input', () => {
+ const input = [{ text: 'ab', bold: true }, { text: 'cd', bold: true }]
+ normalizeSpans(input, 'abcd')
+ expect(input).toEqual([{ text: 'ab', bold: true }, { text: 'cd', bold: true }])
+ })
+})
+
+// ── resolveSpanStyle ───────────────────────────────────────────
+
+describe('resolveSpanStyle', () => {
+ const el = makeText({ fill: '#111111' })
+ it('inherits every base field when the span is bare', () => {
+ expect(resolveSpanStyle(el, { text: 'a' })).toMatchObject({
+ bold: false, italic: false, underline: false, strike: false, color: '#111111', link: null,
+ })
+ })
+ it('span keys override, link implies blue + underline', () => {
+ expect(resolveSpanStyle(el, { text: 'a', bold: true })).toMatchObject({ bold: true, color: '#111111' })
+ expect(resolveSpanStyle(el, { text: 'a', link: 'https://x.dev' })).toMatchObject({ color: '#1155CC', underline: true, link: 'https://x.dev' })
+ expect(resolveSpanStyle(el, { text: 'a', link: 'https://x.dev', color: '#FF0000' })).toMatchObject({ color: '#FF0000' })
+ })
+ it('invalid stored link resolves as no link', () => {
+ expect(resolveSpanStyle(el, { text: 'a', link: 'javascript:x' }).link).toBeNull()
+ })
+})
+
+// ── styleStateInRange ──────────────────────────────────────────
+
+describe('styleStateInRange', () => {
+ it('flat text reports none/null everywhere', () => {
+ const s = styleStateInRange(null, 'Hello world', 0, 11)
+ expect(s).toMatchObject({ bold: 'none', italic: 'none', underline: 'none', strike: 'none', color: null, link: null })
+ })
+ it('aggregates all / mixed per property and dedupes colors', () => {
+ const spans: TextSpan[] = [{ text: 'ab', bold: true, color: '#FF0000' }, { text: 'cd', bold: true }, { text: 'ef' }]
+ expect(styleStateInRange(spans, 'abcdef', 0, 4).bold).toBe('all')
+ expect(styleStateInRange(spans, 'abcdef', 0, 6).bold).toBe('mixed')
+ expect(styleStateInRange(spans, 'abcdef', 0, 2).color).toBe('#FF0000')
+ expect(styleStateInRange(spans, 'abcdef', 0, 4).color).toBe('mixed')
+ expect(styleStateInRange(spans, 'abcdef', 4, 6).bold).toBe('none')
+ })
+})
+
+// ── applyStyleToRange ──────────────────────────────────────────
+
+describe('applyStyleToRange', () => {
+ it('creates spans from flat (the migration moment) and splits mid-run', () => {
+ const out = applyStyleToRange(null, 'Hello world', 0, 5, { bold: true })
+ expect(out).toEqual([{ text: 'Hello', bold: true }, { text: ' world' }])
+ })
+ it('un-bolding a fully-bold range strips back to inherit', () => {
+ const spans: TextSpan[] = [{ text: 'Hello', bold: true }, { text: ' world' }]
+ const out = applyStyleToRange(spans, 'Hello world', 0, 5, { bold: false })
+ expect(out).toBeNull()
+ })
+ it('everything back to plain normalizes to null (flat again — lossless)', () => {
+ let spans = applyStyleToRange(null, 'Hello world', 0, 5, { bold: true })
+ spans = applyStyleToRange(spans, 'Hello world', 6, 11, { color: '#FF0000' })
+ expect(spans).not.toBeNull()
+ spans = applyStyleToRange(spans, 'Hello world', 0, 5, { bold: false })
+ spans = applyStyleToRange(spans, 'Hello world', 6, 11, { color: null })
+ expect(spans).toBeNull()
+ })
+ it('sanitizes links on apply — javascript: strips to no link', () => {
+ const out = applyStyleToRange(null, 'abcdef', 0, 3, { link: 'javascript:alert(1)' })
+ expect(out).toBeNull()
+ const kept = applyStyleToRange(null, 'abcdef', 0, 3, { link: 'https://ok.dev' })
+ expect(kept).toEqual([{ text: 'abc', link: 'https://ok.dev' }, { text: 'def' }])
+ const stripped = applyStyleToRange(kept, 'abcdef', 0, 3, { link: null })
+ expect(stripped).toBeNull()
+ })
+ it('merges newly-adjacent same-style runs', () => {
+ const spans: TextSpan[] = [{ text: 'ab', bold: true }, { text: 'cd' }, { text: 'ef', bold: true }]
+ const out = applyStyleToRange(spans, 'abcdef', 2, 4, { bold: true })
+ expect(out).toEqual([{ text: 'abcdef', bold: true }])
+ })
+ it('a collapsed range is a no-op', () => {
+ expect(applyStyleToRange(null, 'abc', 1, 1, { bold: true })).toBeNull()
+ })
+ it('refuses ops that would exceed MAX_SPANS (returns input unchanged)', () => {
+ // 126 alternating single-char runs + one 3-char run = 127 runs,
+ // 129 chars; styling the middle char of the tail run splits it in
+ // three → 129 runs > cap → the op is refused, input returned as-is
+ const text = 'a'.repeat(126) + 'xyz'
+ const spans: TextSpan[] = []
+ for (let i = 0; i < 126; i++) spans.push({ text: 'a', bold: i % 2 === 0 })
+ spans.push({ text: 'xyz', italic: true })
+ expect(spans).toHaveLength(127)
+ const out = applyStyleToRange(spans, text, 127, 128, { strike: true })
+ expect(out).toEqual(spans)
+ })
+})
+
+// ── reconcileSpans ─────────────────────────────────────────────
+
+describe('reconcileSpans', () => {
+ const spans: TextSpan[] = [{ text: 'Hello' }, { text: ' bold', bold: true }]
+ it('typing inside a styled run extends it', () => {
+ const out = reconcileSpans(spans, 'Hello bold', 'Hello boldX')
+ expect(out).toEqual([{ text: 'Hello' }, { text: ' boldX', bold: true }])
+ })
+ it('typing at a style boundary appends to the PREVIOUS run', () => {
+ const out = reconcileSpans(spans, 'Hello bold', 'Hello boldy')
+ expect(out).toEqual([{ text: 'Hello' }, { text: ' boldy', bold: true }])
+ })
+ it('typing in the unstyled head extends the unstyled run', () => {
+ const out = reconcileSpans(spans, 'Hello bold', 'XHello bold')
+ expect(out).toEqual([{ text: 'XHello' }, { text: ' bold', bold: true }])
+ })
+ it('deleting across the boundary shrinks both runs', () => {
+ const out = reconcileSpans(spans, 'Hello bold', 'Heold')
+ expect(out).toEqual([{ text: 'He' }, { text: 'old', bold: true }])
+ })
+ it('deleting the styled tail flattens to null', () => {
+ const out = reconcileSpans(spans, 'Hello bold', 'Hello')
+ expect(out).toBeNull()
+ })
+ it('deleting everything → null; pasting over a selection splices', () => {
+ expect(reconcileSpans(spans, 'Hello bold', '')).toBeNull()
+ const out = reconcileSpans(spans, 'Hello bold', 'HeXXld') // replaced 'llo bo'
+ expect(out).not.toBeNull()
+ expect(out!.map((r) => r.text).join('')).toBe('HeXXld')
+ expect(out![0].text).toBe('HeXX') // insertion rides the run ending at the cut
+ expect(out![0].bold).toBeUndefined()
+ expect(out![1]).toMatchObject({ text: 'ld', bold: true })
+ })
+ it('no-change returns the same spans', () => {
+ expect(reconcileSpans(spans, 'Hello bold', 'Hello bold')).toBe(spans)
+ })
+ it('malformed input (length mismatch) fails safe to null', () => {
+ expect(reconcileSpans([{ text: 'xy', bold: true }], 'abc', 'abcd')).toBeNull()
+ })
+})
+
+// ── layoutRichLines ────────────────────────────────────────────
+
+describe('layoutRichLines', () => {
+ it('single line, one style: one coalesced run at x=0', () => {
+ const el = makeText({ text: 'abc def', width: 400 })
+ const spans = normalizeSpans([{ text: 'abc', bold: true }, { text: ' def', bold: true }], 'abc def')!
+ const runs = layoutRichLines(el, spans, fakeMeasure)
+ expect(runs).toHaveLength(1)
+ expect(runs[0]).toMatchObject({ x: 0, y: 0, text: 'abc def', width: 70 })
+ expect(runs[0].style.bold).toBe(true)
+ })
+ it('wraps at the box width and steps y by fontSize × lineHeight', () => {
+ const el = makeText({ text: 'aaaa bbbb', width: 45 }) // 'aaaa bbbb' = 90px; line cap 45
+ const spans = normalizeSpans([{ text: 'aaaa', bold: true }, { text: ' bbbb' }], 'aaaa bbbb')!
+ const runs = layoutRichLines(el, spans, fakeMeasure)
+ expect(runs.map((r) => r.text)).toEqual(['aaaa', 'bbbb'])
+ expect(runs[0].y).toBe(0)
+ expect(runs[1].y).toBeCloseTo(32 * 1.4, 5)
+ })
+ it('trailing whitespace at the break is dropped and not measured into the line', () => {
+ const el = makeText({ text: 'aaaa bbbb', width: 45, align: 'center' })
+ const spans = normalizeSpans([{ text: 'aaaa', bold: true }, { text: ' ' }, { text: 'bbbb', italic: true }], 'aaaa bbbb')!
+ const runs = layoutRichLines(el, spans, fakeMeasure)
+ expect(runs.map((r) => r.text)).toEqual(['aaaa', 'bbbb'])
+ // centered: line width 40 in a 45px box → x = 2.5
+ expect(runs[0].x).toBeCloseTo(2.5, 5)
+ expect(runs[1].x).toBeCloseTo(2.5, 5)
+ })
+ it('right align pins line ends to the box edge', () => {
+ const el = makeText({ text: 'aa bb', width: 30, align: 'right' })
+ const spans = normalizeSpans([{ text: 'aa', bold: true }, { text: ' bb' }], 'aa bb')!
+ const runs = layoutRichLines(el, spans, fakeMeasure)
+ expect(runs[0].x).toBeCloseTo(10, 5) // 30 - 20
+ expect(runs[1].x).toBeCloseTo(10, 5)
+ })
+ it('hard newlines (textarea Enter) are hard breaks — every segment its own line', () => {
+ const el = makeText({ text: 'ab\ncd', width: 400 })
+ const spans = normalizeSpans([{ text: 'ab', bold: true }, { text: '\ncd' }], 'ab\ncd')!
+ const runs = layoutRichLines(el, spans, fakeMeasure)
+ expect(runs.map((r) => r.text)).toEqual(['ab', 'cd'])
+ expect(runs[0].y).toBe(0)
+ expect(runs[1].y).toBeCloseTo(32 * 1.4, 5)
+ })
+
+ it('hard-breaks a word wider than the box (at least one glyph per line)', () => {
+ const el = makeText({ text: 'aaaaaa', width: 25 })
+ const runs = layoutRichLines(el, normalizeSpans([{ text: 'aaaaaa', bold: true }], 'aaaaaa')!, fakeMeasure)
+ expect(runs.map((r) => r.text)).toEqual(['aa', 'aa', 'aa'])
+ runs.forEach((r) => expect(r.style.bold).toBe(true))
+ })
+ it('a word split across spans keeps its per-fragment styles and coalesces when equal', () => {
+ const el = makeText({ text: 'abcdef', width: 400 })
+ const split = normalizeSpans([{ text: 'abc', bold: true }, { text: 'def', bold: true }], 'abcdef')!
+ expect(layoutRichLines(el, split, fakeMeasure)).toHaveLength(1) // equal styles coalesce
+ const diff = normalizeSpans([{ text: 'abc', bold: true }, { text: 'def' }], 'abcdef')!
+ const runs = layoutRichLines(el, diff, fakeMeasure)
+ expect(runs).toHaveLength(2)
+ expect(runs[0]).toMatchObject({ text: 'abc', x: 0, width: 30 })
+ expect(runs[1]).toMatchObject({ text: 'def', x: 30 })
+ expect(runs[1].style.bold).toBe(false)
+ })
+ it('uppercase renders uppercased runs; link runs resolve blue + underlined', () => {
+ const el = makeText({ text: 'abc def', uppercase: true, width: 400 })
+ const spans = normalizeSpans([{ text: 'abc ' }, { text: 'def', link: 'https://x.dev' }], 'abc def')!
+ const runs = layoutRichLines(el, spans, fakeMeasure)
+ expect(runs.map((r) => r.text)).toEqual(['ABC ', 'DEF'])
+ expect(runs[1].style).toMatchObject({ color: '#1155CC', underline: true, link: 'https://x.dev' })
+ })
+ it('letterSpacing rides the measure contract (width includes it)', () => {
+ const el = makeText({ text: 'ab', width: 400, letterSpacing: 2 })
+ const runs = layoutRichLines(el, normalizeSpans([{ text: 'ab', bold: true }], 'ab')!, fakeMeasure)
+ expect(runs[0].width).toBe(24) // 2 chars × 10 + 2 × 2
+ })
+})
+
+// ── resolveLineX ───────────────────────────────────────────────
+
+describe('resolveLineX', () => {
+ it('left/justify → 0, center → half the slack, right → the edge', () => {
+ expect(resolveLineX('left', 100, 60)).toBe(0)
+ expect(resolveLineX('justify', 100, 60)).toBe(0)
+ expect(resolveLineX('center', 100, 60)).toBeCloseTo(20, 6)
+ expect(resolveLineX('right', 100, 60)).toBeCloseTo(40, 6)
+ expect(resolveLineX('center', 50, 100)).toBe(0) // over-wide: clamp, never negative
+ })
+})
diff --git a/src/lib/rich-text.ts b/src/lib/rich-text.ts
new file mode 100644
index 0000000..6dd670b
--- /dev/null
+++ b/src/lib/rich-text.ts
@@ -0,0 +1,595 @@
+import type { TextAlign, TextElement, TextSpan } from './types'
+
+// ─────────────────────────────────────────────────────────────
+// v0.15 (R1): rich text — per-span styling on the text element.
+//
+// THE MODEL
+// `TextElement.spans` is an OPTIONAL array of style runs laid
+// over `el.text`. The concatenated span text must equal `el.text`
+// (character-for-character, UTF-16 units — the same units the
+// editing textarea's selectionStart/End report). The flat
+// element fields (bold/italic/fill/…) stay the BASE style:
+// a span key that is absent/undefined INHERITS the base.
+//
+// Legacy elements simply have no spans — every renderer's
+// existing flat path is untouched, which makes the migration
+// lossless by construction: nothing to migrate until a user
+// styles a range, and "clear styling" drops spans back to null
+// with the base fields never having been touched.
+//
+// A malformed spans array (text mismatch, over the run cap) is
+// normalized to `null` — renderers fall back to the flat path
+// and the text itself is NEVER corrupted by styling data.
+//
+// This module is the "one geometry module for all renderers"
+// (the D7 charts pattern): the editor's Konva nodes, the SVG
+// serializer and the video-export frame builder all consume
+// `layoutRichLines` and never re-derive run positions.
+//
+// HONEST LIMITS (documented in README · R1)
+// - Collab merge stays whole-box LWW: two offline editors of
+// one text box still last-writer-win the ENTIRE element
+// (text + spans ride together). Per-span stamps are a
+// post-1.0 evaluation, on real usage.
+// - Curved text (curve ≠ 0) ignores spans in all three
+// renderers — the arc path is single-style by design.
+// ─────────────────────────────────────────────────────────────
+
+/** Hard cap on style runs per element — beyond this the editor
+ * refuses new styling ops and normalize falls back to flat. */
+export const MAX_SPANS = 128
+/** Longest sanitized link href stored on a span. */
+export const MAX_LINK_LENGTH = 512
+/** Rendering colour for a run that carries a link (and no explicit
+ * colour override): the classic document hyperlink blue. */
+export const LINK_COLOR = '#1155CC'
+/** Longest colour string accepted on a span (CSS colours, incl.
+ * rgb()/hsl() functional notation, stay well under this). */
+const MAX_COLOR_LENGTH = 64
+
+export type MeasureText = (text: string, style: SpanMeasureStyle) => number
+
+export interface SpanMeasureStyle {
+ bold: boolean
+ italic: boolean
+ fontSize: number
+ fontFamily: string
+ letterSpacing: number
+}
+
+/** A span's style fully resolved against the element's base. */
+export interface ResolvedSpanStyle {
+ bold: boolean
+ italic: boolean
+ underline: boolean
+ strike: boolean
+ color: string
+ link: string | null
+}
+
+/** What a renderer actually draws: one coalesced styled run at an
+ * exact position inside the element's local box (x from the
+ * align-resolved line start; y = lineIndex · fontSize · lineHeight;
+ * baseline ≈ y + 0.8 · fontSize — the same Konva ascent
+ * approximation the flat SVG serializer already uses). */
+export interface PositionedRun {
+ x: number
+ y: number
+ text: string
+ width: number
+ style: ResolvedSpanStyle
+}
+
+/** Style patch for `applyStyleToRange`. Absent = untouched;
+ * `false`/`null` = strip back to inherit. */
+export interface SpanStylePatch {
+ bold?: boolean
+ italic?: boolean
+ underline?: boolean
+ strike?: boolean
+ color?: string | null
+ link?: string | null
+}
+
+/** Toolbar state for the current selection. */
+export interface RangeStyleState {
+ bold: 'all' | 'none' | 'mixed'
+ italic: 'all' | 'none' | 'mixed'
+ underline: 'all' | 'none' | 'mixed'
+ strike: 'all' | 'none' | 'mixed'
+ color: 'mixed' | string | null
+ link: 'mixed' | string | null
+}
+
+// ── link hygiene ──────────────────────────────────────────────
+
+/** Only http(s) URLs survive (trimmed, control chars stripped,
+ * length-capped). Everything else — javascript:, data:, vbscript:,
+ * relative paths — returns null. Fail closed, like every other
+ * hostile-input path in this codebase. */
+export function sanitizeLink(url: string | null | undefined): string | null {
+ if (typeof url !== 'string') return null
+ // strip control characters (incl. \n/\r — no header/attr injection)
+ const cleaned = url.replace(/[\x00-\x1f\x7f]/g, '').trim()
+ if (!cleaned || cleaned.length > MAX_LINK_LENGTH) return null
+ if (!/^https?:\/\//i.test(cleaned)) return null
+ return cleaned
+}
+
+// ── normalization ─────────────────────────────────────────────
+
+/** Run one span through the inherit-semantics wringer:
+ * falsy booleans → undefined (inherit), '' colour/link → drop,
+ * link sanitized, colour length-capped. */
+function cleanSpan(span: TextSpan): TextSpan {
+ const out: TextSpan = { text: span.text }
+ if (span.bold) out.bold = true
+ if (span.italic) out.italic = true
+ if (span.underline) out.underline = true
+ if (span.strike) out.strike = true
+ if (typeof span.color === 'string' && span.color && span.color.length <= MAX_COLOR_LENGTH) out.color = span.color
+ const link = sanitizeLink(span.link)
+ if (link) out.link = link
+ return out
+}
+
+function sameStyle(a: TextSpan, b: TextSpan): boolean {
+ return a.bold === b.bold && a.italic === b.italic && a.underline === b.underline && a.strike === b.strike && a.color === b.color && a.link === b.link
+}
+
+function isPlain(span: TextSpan): boolean {
+ return !span.bold && !span.italic && !span.underline && !span.strike && !span.color && !span.link
+}
+
+/** Clean + merge runs, collapse to null when flat/mismatched — WITHOUT
+ * the run-cap check (callers that need to distinguish "flat again" from
+ * "over cap" use this and apply the cap themselves). */
+function mergeSpans(spans: TextSpan[] | null | undefined, text: string): TextSpan[] | null {
+ if (!spans || spans.length === 0) return null
+ const cleaned: TextSpan[] = []
+ for (const raw of spans) {
+ if (typeof raw?.text !== 'string' || raw.text === '') continue
+ const span = cleanSpan(raw)
+ const prev = cleaned[cleaned.length - 1]
+ if (prev && sameStyle(prev, span)) {
+ prev.text += span.text
+ } else {
+ cleaned.push(span)
+ }
+ }
+ if (cleaned.length === 0) return null
+ if (cleaned.length === 1 && isPlain(cleaned[0])) return null
+ let total = 0
+ for (const s of cleaned) total += s.text.length
+ if (total !== text.length) return null
+ return cleaned
+}
+
+/**
+ * Canonicalize a spans array. Returns `null` when the element
+ * should render flat: absent/empty spans, a single unstyled run,
+ * a text-length mismatch (fail-safe — never corrupt `el.text`),
+ * or a run count over the cap. Never mutates its input.
+ */
+export function normalizeSpans(spans: TextSpan[] | null | undefined, text: string): TextSpan[] | null {
+ const merged = mergeSpans(spans, text)
+ if (merged && merged.length > MAX_SPANS) return null
+ return merged
+}
+
+/** Concatenated length of the span texts (pre-normalize). */
+export function spanStringLength(spans: TextSpan[] | null | undefined): number {
+ if (!spans) return 0
+ let n = 0
+ for (const s of spans) n += typeof s?.text === 'string' ? s.text.length : 0
+ return n
+}
+
+// ── style resolution ──────────────────────────────────────────
+
+/** Resolve a span against the element base: absent keys inherit
+ * `el.bold`/`el.italic`/… and the fill colour; a link colours the
+ * run (link blue) unless the span carries its own colour. */
+export function resolveSpanStyle(el: TextElement, span: TextSpan): ResolvedSpanStyle {
+ const link = sanitizeLink(span.link)
+ return {
+ bold: span.bold ?? el.bold ?? false,
+ italic: span.italic ?? el.italic ?? false,
+ underline: span.underline ?? (link ? true : el.underline ?? false),
+ strike: span.strike ?? el.strike ?? false,
+ color: span.color ?? (link ? LINK_COLOR : el.fill),
+ link,
+ }
+}
+
+// ── range editing (the textarea drives these) ─────────────────
+
+/** Split runs so that `offset` is a run boundary (UTF-16 units).
+ * Returns a fresh array — never mutates. */
+function splitAt(spans: TextSpan[], offset: number): TextSpan[] {
+ const out: TextSpan[] = []
+ let pos = 0
+ for (const span of spans) {
+ const start = pos
+ const end = pos + span.text.length
+ pos = end
+ if (offset > start && offset < end) {
+ out.push({ ...span, text: span.text.slice(0, offset - start) })
+ out.push({ ...span, text: span.text.slice(offset - start) })
+ } else {
+ out.push({ ...span })
+ }
+ }
+ return out
+}
+
+function runBounds(spans: TextSpan[]): Array<{ start: number; end: number }> {
+ const bounds: Array<{ start: number; end: number }> = []
+ let pos = 0
+ for (const s of spans) {
+ bounds.push({ start: pos, end: pos + s.text.length })
+ pos += s.text.length
+ }
+ return bounds
+}
+
+/** Query the SPAN-LEVEL state of [start, end) for toolbar chips:
+ * `'all'` = every covered run sets it, `'none'` = none do,
+ * `'mixed'` = some do. `color`/`link` report the shared value,
+ * `null` when unstyled, `'mixed'` when they disagree. */
+export function styleStateInRange(
+ spans: TextSpan[] | null | undefined,
+ text: string,
+ start: number,
+ end: number,
+): RangeStyleState {
+ const state: RangeStyleState = {
+ bold: 'none', italic: 'none', underline: 'none', strike: 'none',
+ color: null, link: null,
+ }
+ const s = Math.max(0, Math.min(start, end))
+ const e = Math.max(0, Math.min(Math.max(start, end), text.length))
+ if (s >= e) return state
+ const runs = spans ?? [{ text }]
+ const flags: Record<'bold' | 'italic' | 'underline' | 'strike', 'none' | 'all' | 'mixed'> = {
+ bold: 'none', italic: 'none', underline: 'none', strike: 'none',
+ }
+ const colors = new Set<string>()
+ const links = new Set<string>()
+ let colorless = 0
+ let linkless = 0
+ let covered = 0
+ for (const run of runs) {
+ const b = { start: covered, end: covered + run.text.length }
+ covered = b.end
+ if (b.end <= s || b.start >= e) continue
+ for (const key of ['bold', 'italic', 'underline', 'strike'] as const) {
+ const on = Boolean(run[key])
+ if (flags[key] === 'none' && on) flags[key] = 'all'
+ else if (flags[key] === 'all' && !on) flags[key] = 'mixed'
+ else if (flags[key] === 'mixed') { /* sticky */ }
+ }
+ if (run.color) colors.add(run.color)
+ else colorless++
+ if (run.link) {
+ const clean = sanitizeLink(run.link)
+ if (clean) links.add(clean)
+ else linkless++
+ } else linkless++
+ }
+ return {
+ ...flags,
+ color: colors.size === 0 ? null : colorless > 0 || colors.size > 1 ? 'mixed' : Array.from(colors)[0],
+ link: links.size === 0 ? null : linkless > 0 || links.size > 1 ? 'mixed' : Array.from(links)[0],
+ }
+}
+
+/**
+ * Apply a style patch to the character range [start, end) of the
+ * element's text. `spans === null` (flat) means one implicit
+ * inherit-run covers everything — styling a range of a flat
+ * element is what CREATES the spans array (the migration moment).
+ * The link value is sanitized here (fail closed: an invalid href
+ * strips the link instead of storing it). Returns the new spans
+ * (possibly `null` when everything normalized back to flat).
+ * Refuses to exceed MAX_SPANS runs (returns the input unchanged).
+ */
+export function applyStyleToRange(
+ spans: TextSpan[] | null | undefined,
+ text: string,
+ start: number,
+ end: number,
+ patch: SpanStylePatch,
+): TextSpan[] | null {
+ const s = Math.max(0, Math.min(start, end))
+ const e = Math.max(0, Math.min(Math.max(start, end), text.length))
+ if (s >= e) return spans ?? null
+ const base: TextSpan[] = spans && spans.length > 0 ? spans.map((r) => ({ ...r })) : [{ text }]
+ // safety: caller's spans might not cover the full text — pad/truncate is
+ // normalize's job; here just guard the invariant cheaply
+ let total = 0
+ for (const r of base) total += r.text.length
+ if (total !== text.length) return spans ?? null
+
+ let runs = splitAt(base, s)
+ runs = splitAt(runs, e)
+ const bounds = runBounds(runs)
+ const next = runs.map((run, i) => {
+ if (bounds[i].start < s || bounds[i].end > e) return run // not fully covered
+ const out = { ...run }
+ if (patch.bold !== undefined) out.bold = patch.bold || undefined
+ if (patch.italic !== undefined) out.italic = patch.italic || undefined
+ if (patch.underline !== undefined) out.underline = patch.underline || undefined
+ if (patch.strike !== undefined) out.strike = patch.strike || undefined
+ if (patch.color !== undefined) out.color = patch.color || undefined
+ if (patch.link !== undefined) {
+ const clean = sanitizeLink(patch.link)
+ out.link = clean ?? undefined
+ }
+ return out
+ })
+ const normalized = mergeSpans(next, text)
+ if (normalized === null) return null // everything styled back to plain — flat again
+ if (normalized.length > MAX_SPANS) return spans ?? null // refused: would exceed the run cap
+ return normalized
+}
+
+/**
+ * Keep spans aligned with the text while the user types: diff the
+ * old/new textarea value (common prefix + suffix) and splice the
+ * runs. Handles insert, delete, cut, paste and replace in one
+ * path. Returns `null` when the result is flat (e.g. everything
+ * was deleted).
+ */
+export function reconcileSpans(
+ spans: TextSpan[] | null | undefined,
+ oldText: string,
+ newText: string,
+): TextSpan[] | null {
+ if (!spans || spans.length === 0) return null
+ if (oldText === newText) return spans
+ // normalize first so the run math below can trust the invariant
+ const runs = normalizeSpans(spans, oldText)
+ if (!runs) return null
+
+ const minLen = Math.min(oldText.length, newText.length)
+ let p = 0
+ while (p < minLen && oldText[p] === newText[p]) p++
+ let s = 0
+ while (s < minLen - p && oldText[oldText.length - 1 - s] === newText[newText.length - 1 - s]) s++
+
+ const removed = oldText.length - p - s
+ const inserted = newText.slice(p, newText.length - s)
+
+ let working = runs.map((r) => ({ ...r }))
+ if (removed > 0) {
+ // split at both boundaries first — after this no run straddles
+ // p or p+removed, so each run is fully inside or fully outside
+ working = splitAt(working, p)
+ working = splitAt(working, p + removed)
+ let pos = 0
+ const kept: TextSpan[] = []
+ for (const r of working) {
+ const start = pos
+ const end = pos + r.text.length
+ pos = end
+ if (end <= p || start >= p + removed) kept.push(r)
+ // runs fully inside [p, p+removed) are dropped on the floor
+ }
+ working = kept
+ }
+ if (inserted) {
+ // insert at offset p, in priority order: prepend to the first run
+ // (p === 0), append to the run ENDING at p (typing extends the span
+ // you're inside), splice the run containing p — never fall through
+ // to the end-of-array safety unless coverage is empty
+ let pos = 0
+ let placed = false
+ const out: TextSpan[] = []
+ for (const r of working) {
+ const start = pos
+ const end = pos + r.text.length
+ pos = end
+ if (!placed) {
+ if (p === 0 && start === 0) {
+ out.push({ ...r, text: inserted + r.text })
+ placed = true
+ continue
+ }
+ if (end === p) {
+ out.push({ ...r, text: r.text + inserted })
+ placed = true
+ continue
+ }
+ if (start < p && p < end) {
+ out.push({ ...r, text: r.text.slice(0, p - start) + inserted + r.text.slice(p - start) })
+ placed = true
+ continue
+ }
+ }
+ out.push({ ...r })
+ }
+ if (!placed) out.push({ text: inserted })
+ working = out
+ }
+ return normalizeSpans(working, newText)
+}
+
+// ── layout (the shared geometry for all three renderers) ──────
+
+/** Line x-offset for a wrapped line of `lineWidth` inside a box of
+ * `boxWidth` (justify renders left-aligned, matching the flat
+ * paths' documented behaviour). */
+export function resolveLineX(align: TextAlign, boxWidth: number, lineWidth: number): number {
+ if (align === 'center') return Math.max(0, (boxWidth - lineWidth) / 2)
+ if (align === 'right') return Math.max(0, boxWidth - lineWidth)
+ return 0
+}
+
+interface Fragment {
+ text: string
+ style: ResolvedSpanStyle
+ width: number
+ kind: 'word' | 'ws' | 'nl'
+}
+
+/**
+ * Greedy word-wrap layout of the spans into positioned runs.
+ *
+ * - `measure` is INJECTED so each renderer stays consistent with
+ * its own glyph metrics: the editor & video-export pass a
+ * canvas-2d measure, the SVG serializer passes its own
+ * (svg-export) measureText adapted to include letterSpacing.
+ * Unit tests pass a deterministic fake.
+ * - The measure contract: advance width of `text` in the given
+ * style INCLUDING `letterSpacing × text.length` (the Konva
+ * per-character model).
+ * - Words split across spans lay out as per-fragment runs and
+ * coalesce back when adjacent fragments share a resolved style.
+ * - Trailing whitespace at a line break is not rendered and does
+ * not count toward the line width (Konva `wrap="word"` parity).
+ * - A word wider than the box hard-breaks by character (at least
+ * one glyph per line — never an infinite loop).
+ */
+export function layoutRichLines(
+ el: TextElement,
+ spans: TextSpan[],
+ measure: MeasureText,
+): PositionedRun[] {
+ const maxWidth = Math.max(1, el.width)
+ const measureStyle = (style: ResolvedSpanStyle): SpanMeasureStyle => ({
+ bold: style.bold,
+ italic: style.italic,
+ fontSize: el.fontSize,
+ fontFamily: el.fontFamily,
+ letterSpacing: el.letterSpacing,
+ })
+
+ // fragment the spans into word / whitespace / newline chunks — the
+ // textarea's Enter key produces real '\n' characters (Konva's flat
+ // path treats them as hard line breaks, so the rich path must too)
+ const fragments: Fragment[] = []
+ for (const span of spans) {
+ const style = resolveSpanStyle(el, span)
+ const rendered = el.uppercase ? span.text.toUpperCase() : span.text
+ for (const seg of rendered.split(/(\n)/)) {
+ if (seg === '') continue
+ if (seg === '\n') {
+ fragments.push({ text: '\n', style, width: 0, kind: 'nl' })
+ continue
+ }
+ for (const token of seg.split(/([ \t]+)/)) {
+ if (!token) continue
+ fragments.push({ text: token, style, width: measure(token, measureStyle(style)), kind: /^[ \t]+$/.test(token) ? 'ws' : 'word' })
+ }
+ }
+ }
+
+ // greedy wrap into lines of fragments (trailing ws dropped at breaks)
+ const lines: Fragment[][] = []
+ let line: Fragment[] = []
+ let lineW = 0
+ const pushLine = () => {
+ while (line.length && line[line.length - 1].kind === 'ws') {
+ lineW -= line.pop()!.width
+ }
+ lines.push(line)
+ line = []
+ lineW = 0
+ }
+ for (const frag of fragments) {
+ if (frag.kind === 'nl') {
+ pushLine()
+ continue
+ }
+ if (frag.kind === 'ws') {
+ line.push(frag)
+ lineW += frag.width
+ continue
+ }
+ const overflow = lineW + frag.width > maxWidth
+ if (overflow && line.length > 0) pushLine()
+ if (frag.width > maxWidth) {
+ // hard-break the over-wide word by character — at least one
+ // glyph per line, so the loop can never spin forever
+ let chunk = ''
+ let chunkW = 0
+ for (const ch of frag.text) {
+ const chW = measure(ch, measureStyle(frag.style))
+ if (chunkW + chW > maxWidth && chunk) {
+ line.push({ text: chunk, style: frag.style, width: chunkW, kind: 'word' })
+ lines.push(line)
+ line = []
+ chunk = ''
+ chunkW = 0
+ }
+ chunk += ch
+ chunkW += chW
+ }
+ if (chunk) {
+ line.push({ text: chunk, style: frag.style, width: chunkW, kind: 'word' })
+ lineW = chunkW
+ }
+ continue
+ }
+ line.push(frag)
+ lineW += frag.width
+ }
+ pushLine()
+
+ // position runs (coalescing same-style neighbours on a line)
+ const out: PositionedRun[] = []
+ const lineHeight = el.fontSize * el.lineHeight
+ lines.forEach((frags, i) => {
+ let w = 0
+ for (const f of frags) w += f.width
+ let x = resolveLineX(el.align === 'justify' ? 'left' : el.align, maxWidth, w)
+ for (const f of frags) {
+ const prev = out[out.length - 1]
+ if (
+ prev &&
+ Math.abs(prev.y - i * lineHeight) < 1e-9 &&
+ Math.abs(prev.x + prev.width - x) < 1e-9 &&
+ prev.style.bold === f.style.bold &&
+ prev.style.italic === f.style.italic &&
+ prev.style.underline === f.style.underline &&
+ prev.style.strike === f.style.strike &&
+ prev.style.color === f.style.color &&
+ prev.style.link === f.style.link
+ ) {
+ prev.text += f.text
+ prev.width += f.width
+ } else {
+ out.push({ x, y: i * lineHeight, text: f.text, width: f.width, style: f.style })
+ }
+ x += f.width
+ }
+ })
+ return out
+}
+
+// ── the browser-side measure (editor + video export) ──────────
+
+let canvasCtx: CanvasRenderingContext2D | null = null
+
+/**
+ * Canvas-2d measure with the codebase's graceful fallback (the
+ * svg-export measureText pattern): when no 2d context exists
+ * (SSR, jsdom without the canvas API) fall back to the
+ * 0.55 × fontSize per-character approximation.
+ */
+export function createCanvasMeasure(): MeasureText {
+ return (text, style) => {
+ try {
+ if (!canvasCtx) {
+ const canvas = document.createElement('canvas')
+ canvasCtx = canvas.getContext('2d')
+ }
+ if (!canvasCtx) return text.length * style.fontSize * 0.55 + style.letterSpacing * text.length
+ canvasCtx.font = `${style.italic ? 'italic ' : ''}${style.bold ? 700 : 400} ${style.fontSize}px ${style.fontFamily}`
+ return canvasCtx.measureText(text).width + style.letterSpacing * text.length
+ } catch {
+ return text.length * style.fontSize * 0.55 + style.letterSpacing * text.length
+ }
+ }
+}
diff --git a/src/lib/svg-export.ts b/src/lib/svg-export.ts
index dd0f6bc..e228a45 100644
--- a/src/lib/svg-export.ts
+++ b/src/lib/svg-export.ts
@@ -26,11 +26,13 @@ import type {
StickerElement,
TableElement,
TextElement,
+ TextSpan,
GroupElement,
} from '@/lib/types'
import { svgImageFilterParts } from '@/lib/image-filters'
import { chartPrimitives } from '@/lib/chart-geometry'
import { arcForCurve, embedLayout, frameClipPathD, hostOf, tableGeometry, youtubeThumbUrl } from '@/lib/v06-geometry'
+import { layoutRichLines, normalizeSpans } from '@/lib/rich-text'
import type { PluginElement } from '@/lib/types'
import { getRenderEntry, renderKey } from '@/lib/plugins/renderer-cache'
@@ -276,6 +278,43 @@ function pluginPlaceholderSvg(el: PluginElement, rotate: string): string {
</g>`
}
+// v0.15 (R1): rich text — per-run tspans at the shared layout's exact
+// positions. The measure adapter wraps this serializer's own
+// measureText (adding letterSpacing per character) so SVG output stays
+// consistent with the editor's canvas metrics to the pixel.
+function richTextSvg(t: TextElement, spans: TextSpan[], ctx: SvgContext): string {
+ const runs = layoutRichLines(t, spans, (text, style) => measureText(text, t.fontFamily, t.fontSize, style.bold) + style.letterSpacing * text.length)
+ const gradientFill = t.fillGradient ? gradientRefFor(t, ctx) : null
+ const sharedAttrs = [
+ `font-family="${esc(t.fontFamily)}"`,
+ `font-size="${t.fontSize}"`,
+ t.letterSpacing ? `letter-spacing="${t.letterSpacing}"` : '',
+ opacityAttr(t),
+ shadowAttrs(t, ctx),
+ ]
+ .filter(Boolean)
+ .join(' ')
+ const transform = t.rotation ? ` transform="rotate(${t.rotation} ${t.x} ${t.y})"` : ''
+ const tspans = runs
+ .map((r) => {
+ const decor = [r.style.underline ? 'underline' : '', r.style.strike ? 'line-through' : ''].filter(Boolean).join(' ')
+ const fill = gradientFill && r.style.color === t.fill ? gradientFill : esc(r.style.color)
+ const attrs = [
+ `x="${(t.x + r.x).toFixed(2)}"`,
+ `y="${(t.y + r.y + t.fontSize * 0.8).toFixed(2)}"`,
+ `font-weight="${r.style.bold ? 700 : 400}"`,
+ `font-style="${r.style.italic ? 'italic' : 'normal'}"`,
+ decor ? `text-decoration="${decor}"` : '',
+ `fill="${fill}"`,
+ ]
+ .filter(Boolean)
+ .join(' ')
+ return `<tspan ${attrs}>${esc(r.text)}</tspan>`
+ })
+ .join('')
+ return ` <text ${sharedAttrs}${transform} xml:space="preserve">${tspans}</text>`
+}
+
function serializeElement(el: AnyElement, ctx: SvgContext): string {
if (!el.visible) return ''
const transformBase = rotationTransform(el)
@@ -285,6 +324,13 @@ function serializeElement(el: AnyElement, ctx: SvgContext): string {
const t = el as TextElement
const rendered = t.uppercase ? t.text.toUpperCase() : t.text
+ // v0.15 (R1): rich text — spans before the flat paths (curved text
+ // stays flat: the arc path is single-style by design)
+ if (t.curve === 0 || t.curve === undefined) {
+ const richSpans = normalizeSpans(t.spans, t.text)
+ if (richSpans) return richTextSvg(t, richSpans, ctx)
+ }
+
// v0.6: curved text → textPath on an arc (path def carries the translate)
const arc = arcForCurve(t.curve ?? 0, t.width)
if (arc) {
diff --git a/src/lib/types.ts b/src/lib/types.ts
index cc8daa3..4891bf0 100644
--- a/src/lib/types.ts
+++ b/src/lib/types.ts
@@ -121,6 +121,23 @@ export interface BaseElement {
}
}
+/**
+ * v0.15 (R1) rich text — one styled run laid over `TextElement.text`.
+ * Concatenated span text must equal `el.text` (UTF-16 units; the
+ * textarea's selection offsets). Every key is optional: absent means
+ * INHERIT the element's flat field. See src/lib/rich-text.ts.
+ */
+export interface TextSpan {
+ text: string
+ bold?: boolean
+ italic?: boolean
+ underline?: boolean
+ strike?: boolean
+ color?: string
+ /** http(s) only — sanitizeLink() gates every write */
+ link?: string
+}
+
export interface TextElement extends BaseElement {
type: 'text'
text: string
@@ -139,6 +156,9 @@ export interface TextElement extends BaseElement {
letterSpacing: number
/** v0.6 canva curved text — arc angle in degrees (−180..180, 0 = straight) */
curve?: number
+ /** v0.15 (R1) rich text — optional style runs over `text`; null/absent = flat.
+ * Malformed arrays normalize to null (fail-safe, never corrupts `text`). */
+ spans?: TextSpan[] | null
/** text background block colour (canva "Background" effect) */
effectBackground?: string
/** canva-style effect preset */
diff --git a/src/lib/video-export.ts b/src/lib/video-export.ts
index 108388e..539a11c 100644
--- a/src/lib/video-export.ts
+++ b/src/lib/video-export.ts
@@ -16,6 +16,7 @@ import type { AnyElement, AudioElement, ChartElement, EmbedElement, FrameElement
import { imageHasFilters, renderFilteredCanvas } from '@/lib/image-filters'
import { chartPrimitives } from '@/lib/chart-geometry'
import { embedLayout, hexPoints, hostOf, tableGeometry, youtubeThumbUrl } from '@/lib/v06-geometry'
+import { createCanvasMeasure, layoutRichLines, normalizeSpans } from '@/lib/rich-text'
import { animateElementAt, pageHoldDuration } from '@/lib/animations'
import { beatEnvelopeAt, beatSourceOf } from '@/lib/media/beat-detect'
import { awaitRender, renderKey } from '@/lib/plugins/renderer-cache'
@@ -192,10 +193,40 @@ function frameClipFunc(fr: FrameElement): (ctx: Konva.Context) => void {
}
}
+/** v0.15 (R1): browser-side measure for rich text runs (same canvas-2d
+ * metrics the editor's Konva renderer uses — frame parity by sharing
+ * the geometry module, the D7 charts pattern). */
+const videoRichMeasure = createCanvasMeasure()
+
function buildKonvaNode(el: AnyElement, images: Map<string, HTMLImageElement>): Konva.Node {
switch (el.type) {
case 'text': {
const t = el
+ // v0.15 (R1): rich text — one Text node per positioned run from the
+ // shared layout module (curved text stays flat, single-style by design)
+ if ((t.curve ?? 0) === 0) {
+ const richSpans = normalizeSpans(t.spans, t.text)
+ if (richSpans) {
+ const runs = layoutRichLines(t, richSpans, videoRichMeasure)
+ const group = new Konva.Group({ id: t.id, x: t.x, y: t.y })
+ group.height(runs.length ? Math.max(...runs.map((r) => r.y)) + t.fontSize * t.lineHeight : t.fontSize * t.lineHeight)
+ for (const run of runs) {
+ group.add(
+ new Konva.Text({
+ x: run.x,
+ y: run.y,
+ text: run.text,
+ fontSize: t.fontSize,
+ fontFamily: t.fontFamily,
+ fontStyle: `${run.style.italic ? 'italic ' : ''}${run.style.bold ? 'bold' : 'normal'}`,
+ textDecoration: [run.style.underline ? 'underline' : '', run.style.strike ? 'line-through' : ''].filter(Boolean).join(' '),
+ fill: run.style.color,
+ }),
+ )
+ }
+ return group
+ }
+ }
return new Konva.Text({
id: t.id,
x: t.x,
diff --git a/tests/e2e/rich-text.spec.ts b/tests/e2e/rich-text.spec.ts
new file mode 100644
index 0000000..3dc56e4
--- /dev/null
+++ b/tests/e2e/rich-text.spec.ts
@@ -0,0 +1,274 @@
+import { test, expect, type Page } from '@playwright/test'
+import { readFileSync } from 'node:fs'
+
+/**
+ * v0.15 (R1): rich text — acceptance.
+ *
+ * 1. a LEGACY flat text element (no spans) opens losslessly, and
+ * styling a range CREATES the spans without touching the text
+ * (the migration is lazy by construction — SAVED doc truth)
+ * 2. the editing overlay shows what you're styling: the mirror
+ * carries <strong> for the bolded range while the textarea
+ * stays transparent (observed in-DOM)
+ * 3. ONE undo after the editing session reverts spans to null
+ * with the text intact — the session owns exactly one history
+ * entry (beginEditText pushes it; every keystroke and style op
+ * rides updateElementsLive)
+ * 4. the exported SVG renders the runs as real tspans: the bold
+ * range at font-weight="700", the rest at 400
+ * 5. links fail closed in the UI path: javascript: URLs are
+ * stripped on apply; https:// survives; the clear-styling chip
+ * on the properties bar returns the element to flat (spans
+ * null) with text and base fields untouched
+ *
+ * Register budget: ZERO — anonymous anon-commons designs, fresh
+ * browser context per test (the PR #26/#30 lesson).
+ */
+
+interface TextDoc {
+ text?: string
+ spans?: { text: string; bold?: boolean; italic?: boolean; underline?: boolean; strike?: boolean; color?: string; link?: string }[] | null
+}
+
+function textElement(id: string, text: string) {
+ return {
+ id,
+ type: 'text',
+ name: id,
+ x: 90,
+ y: 300,
+ width: 900,
+ height: 120,
+ rotation: 0,
+ opacity: 1,
+ locked: false,
+ visible: true,
+ text,
+ fontSize: 64,
+ fontFamily: 'Poppins',
+ bold: false,
+ italic: false,
+ underline: false,
+ strike: false,
+ uppercase: false,
+ fill: '#1F2226',
+ align: 'center',
+ lineHeight: 1.4,
+ letterSpacing: 0,
+ }
+}
+
+async function createDesign(page: Page, name: string, elements: unknown[]): Promise<string> {
+ const res = await page.request.post('/api/designs', {
+ data: { name, width: 1080, height: 720, pages: [{ id: 'p1', background: { type: 'solid', color: '#FFFFFF' }, elements }] },
+ })
+ expect(res.status(), `create design: ${await res.text()}`).toBeLessThan(300)
+ return ((await res.json()) as { id: string }).id
+}
+
+async function openEditor(page: Page, designId: string) {
+ await page.goto(`/design/${designId}`)
+ await page.addStyleTag({ content: 'nextjs-portal { display: none !important; }' })
+ await expect(page.getByLabel('Design canvas')).toBeVisible({ timeout: 60_000 })
+}
+
+/** the text is actually drawn (pixel truth — the #1F2226 fill on the
+ * biggest canvas; guards the design-load race before any click). */
+async function waitForTextRendered(page: Page) {
+ await page.waitForFunction(
+ () => {
+ const scope = document.querySelector('main[aria-label="Design canvas"]')
+ const canvases = Array.from((scope ?? document).querySelectorAll('canvas'))
+ const biggest = canvases.reduce<HTMLCanvasElement | null>(
+ (best, c) => (!best || c.width * c.height > best.width * best.height ? c : best),
+ null,
+ )
+ if (!biggest) return false
+ try {
+ const ctx = biggest.getContext('2d')
+ if (!ctx) return false
+ const data = ctx.getImageData(0, 0, biggest.width, biggest.height).data
+ for (let i = 0; i < data.length; i += 16) {
+ if (data[i] === 0x1f && data[i + 1] === 0x22 && data[i + 2] === 0x26) return true
+ }
+ return false
+ } catch {
+ return false
+ }
+ },
+ undefined,
+ { timeout: 30_000, polling: 250 },
+ )
+}
+
+async function docText(page: Page, designId: string, id: string): Promise<TextDoc> {
+ const res = await page.request.get(`/api/designs/${designId}`)
+ expect(res.status()).toBe(200)
+ const doc = (await res.json()) as { pages: { elements: TextDoc[] }[] }
+ return doc.pages[0].elements.find((e) => (e as { id?: string }).id === id) ?? {}
+}
+
+async function waitForText(
+ page: Page,
+ designId: string,
+ id: string,
+ pred: (t: TextDoc) => boolean,
+ what: string,
+): Promise<TextDoc> {
+ const start = Date.now()
+ for (;;) {
+ const t = await docText(page, designId, id)
+ if (pred(t)) return t
+ if (Date.now() - start > 45_000) {
+ throw new Error(`rich-text: ${what} — document never reached the expected state (got ${JSON.stringify(t)})`)
+ }
+ await page.waitForTimeout(600)
+ }
+}
+
+/** click (not double) — re-selects the text element after an editing
+ * session without reopening the overlay */
+async function clickText(page: Page) {
+ const box = (await page.getByLabel('Design canvas').boundingBox())!
+ await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2)
+}
+
+/** double-click the text element: the element spans the design's
+ * centre band, and the fitted view centres the design in the canvas
+ * box — so a double-click at the canvas-box centre is always inside
+ * the element's box, regardless of letterboxing. */
+async function dblClickText(page: Page) {
+ const box = (await page.getByLabel('Design canvas').boundingBox())!
+ const cx = box.x + box.width / 2
+ const cy = box.y + box.height / 2
+ await page.mouse.dblclick(cx, cy)
+}
+
+test.describe('Rich text (v0.15 R1)', () => {
+ test.setTimeout(150_000)
+
+ test('flat → bold a range → spans saved, mirror shows it, one undo reverts, SVG carries the runs', async ({ page }) => {
+ const design = await createDesign(page, `cvx_r1_${Date.now().toString(36)}`, [textElement('r1_text', 'Hello rich world')])
+ await openEditor(page, design)
+ await waitForTextRendered(page)
+
+ // ── open the editor overlay on the legacy element ──
+ await dblClickText(page)
+ const editor = page.getByLabel('Edit text')
+ await expect(editor).toBeVisible({ timeout: 10_000 })
+ await expect(editor).toHaveValue('Hello rich world')
+
+ // ── select the first word (Home, then Shift+Right ×5) ──
+ await editor.press('Home')
+ for (let i = 0; i < 5; i++) await editor.press('Shift+ArrowRight')
+
+ // ── the floating toolbar is enabled and mirrors know the range ──
+ const boldBtn = page.getByRole('button', { name: 'Bold selection' })
+ await expect(boldBtn).toBeEnabled()
+
+ // ── apply bold: the styled mirror appears with <strong>Hello</strong> ──
+ await boldBtn.click()
+ await expect(page.getByTestId('rich-mirror').locator('strong')).toHaveText('Hello')
+
+ // ── commit (Escape) — the SAVED document carries the spans,
+ // the text is untouched (migration lossless) ──
+ await editor.press('Escape')
+ await expect(page.getByLabel('Edit text')).toBeHidden({ timeout: 10_000 })
+ const saved = await waitForText(
+ page,
+ design,
+ 'r1_text',
+ (t) => Array.isArray(t.spans) && t.spans.length === 2,
+ 'bold range persisted',
+ )
+ expect(saved.text).toBe('Hello rich world')
+ expect(saved.spans).toEqual([
+ { text: 'Hello', bold: true },
+ { text: ' rich world' },
+ ])
+
+ // ── export SVG: the runs are real tspans with their weights ──
+ await page.getByRole('button', { name: 'Download', exact: true }).click()
+ await page.getByRole('button', { name: /^SVG\b/ }).click()
+ const [download] = await Promise.all([
+ page.waitForEvent('download'),
+ page.getByRole('button', { name: /Download 1 SVG/i }).click(),
+ ])
+ const svg = readFileSync((await download.path())!, 'utf8')
+ expect(svg).toContain('font-weight="700"')
+ expect(svg).toContain('font-weight="400"')
+ expect(svg).toMatch(/>Hello</)
+ expect(svg).toMatch(/> rich world</)
+ await expect(page.getByRole('button', { name: 'Close' })).toBeHidden({ timeout: 10_000 })
+
+ // ── ONE undo reverts the whole editing session: spans null, text intact ──
+ await clickText(page) // re-select (the export dialog had focus)
+ await page.keyboard.press('Control+z')
+ const undone = await waitForText(page, design, 'r1_text', (t) => !t.spans, 'undo cleared spans')
+ expect(undone.text).toBe('Hello rich world')
+ })
+
+ test('links fail closed (javascript: stripped, https: kept) and the Clear chip flattens', async ({ page }) => {
+ const design = await createDesign(page, `cvx_r1b_${Date.now().toString(36)}`, [textElement('r1_link', 'Visit the docs today')])
+ await openEditor(page, design)
+ await waitForTextRendered(page)
+
+ await dblClickText(page)
+ const editor = page.getByLabel('Edit text')
+ await expect(editor).toBeVisible({ timeout: 10_000 })
+
+ // select "docs" (chars 10..14)
+ await editor.press('Home')
+ for (let i = 0; i < 14; i++) await editor.press('ArrowRight')
+ for (let i = 0; i < 4; i++) await editor.press('Shift+ArrowRight')
+
+ // ── hostile href: applied, but sanitizeLink strips it (fail closed) ──
+ await page.getByRole('button', { name: 'Link selection' }).click()
+ const linkInput = page.getByLabel('Link URL')
+ await expect(linkInput).toBeVisible()
+ await linkInput.fill('javascript:alert(1)')
+ await page.getByRole('button', { name: 'Apply link' }).click()
+ // the op ran but stored no link → spans exist only if some style was
+ // applied… none was, so the element may be flat again — the hostile
+ // URL must NOT appear anywhere in the saved doc either way
+ await editor.press('Escape')
+ await expect(page.getByLabel('Edit text')).toBeHidden({ timeout: 10_000 })
+ const afterHostile = await waitForText(
+ page,
+ design,
+ 'r1_link',
+ (t) => JSON.stringify(t).indexOf('javascript:') === -1 && t.text === 'Visit the docs today',
+ 'hostile link never stored',
+ )
+ expect(afterHostile.spans ?? null).toBeNull()
+
+ // ── real link: styled run with the sanitized href ──
+ await dblClickText(page)
+ await expect(page.getByLabel('Edit text')).toBeVisible({ timeout: 10_000 })
+ await editor.press('Home')
+ for (let i = 0; i < 14; i++) await editor.press('ArrowRight')
+ for (let i = 0; i < 4; i++) await editor.press('Shift+ArrowRight')
+ await page.getByRole('button', { name: 'Link selection' }).click()
+ await page.getByLabel('Link URL').fill('https://example.com/docs')
+ await page.getByRole('button', { name: 'Apply link' }).click()
+ await editor.press('Escape')
+ await expect(page.getByLabel('Edit text')).toBeHidden({ timeout: 10_000 })
+ const linked = await waitForText(
+ page,
+ design,
+ 'r1_link',
+ (t) => Array.isArray(t.spans) && t.spans.some((s) => s.link === 'https://example.com/docs'),
+ 'https link stored',
+ )
+ expect(linked.text).toBe('Visit the docs today')
+
+ // ── the properties-bar chip clears the rich styling (one patch,
+ // text + base fields untouched) ──
+ await clickText(page) // ensure the element is selected (chip needs selection)
+ const chip = page.getByTestId('clear-rich-text')
+ await expect(chip).toBeVisible({ timeout: 10_000 })
+ await chip.click()
+ const cleared = await waitForText(page, design, 'r1_link', (t) => !t.spans, 'chip cleared spans')
+ expect(cleared.text).toBe('Visit the docs today')
+ })
+})