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.
TypeScript canva-alternativecanvasdesigndesign-tooldrag-and-dropeditorgraphic-designkonvanextjsopen-sourcereactself-hostedtemplatestypescript
feat(v0.14): data-bound charts — native bar/line/donut/scatter element, one geometry module for all three renderers, toolbar data editor, MCP add_chart + series patches, video-export table/frame/embed parity fix (D7)
Ashiq Hussain Mir283ebc0496c9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e3f9d01..867d587 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,45 @@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.14.4] — 2026-11-05++### Added++- **Daily-driver depth, part 5 — data-bound charts (D7).** Charts+ were one-shot decorations (the Apps panel exploded them into loose+ rects and lines — edit one bar and the "chart" was gone). They are+ now a native `chart` element whose data stays editable.+ - **Four kinds, one element** — bar (grouped or stacked), line+ (optional Catmull-Rom smoothing), donut (first series, centre+ total, adjustable hole) and scatter (flat x,y pairs on numeric+ axes). The toolbar converts between kinds in place; converting+ out of scatter reuses the y values so nothing is lost.+ - **One geometry module, three renderers** —+ `src/lib/chart-geometry.ts` turns the element into pure vector+ primitives; the editor (react-konva), the video exporter (Konva)+ and the SVG exporter (strings) are thin adapters over the same+ list, so all three render identical geometry by construction.+ Smooth lines are sampled in the geometry itself; anchored text+ uses the same wide-box trick in both Konva and SVG.+ - **Editable after creation** — the toolbar's "Edit data" popover+ is a spreadsheet: category labels, per-series values, series+ names and colours, add/remove labels and series (typing updates+ live; structural edits are one undo step each — the house+ pattern). Plus grid / values / legend toggles, text size and+ panel colours.+ - **Everywhere a chart should be** — Elements panel "Charts" tab,+ the Apps rail (now adding the native element), the layers panel,+ SVG exports (annular-sector arc paths for donuts), video exports+ — and while wiring the video exporter, tables, frames and embed+ cards stopped vanishing from video exports entirely (they+ previously fell through to an empty group; a pre-existing parity+ gap closed while here).+ - **Safe + agent-ready** — pasted charts run the hostile-input+ gauntlet (kind whitelist with bar fallback, ≤ 6 series / 24+ labels / finite clamped values, hole clamped); MCP gains+ `add_chart` and `update_element` understands `series`,+ `labels`, `kind`, `barMode`, `hole` and the display toggles.+## [0.14.3] — 2026-11-05### Addeddiff --git a/README.md b/README.mdindex e436285..3ed6895 100644--- a/README.md+++ b/README.md@@ -414,6 +414,10 @@ is right here.posters, logos, YouTube thumbnails- **Backgrounds** — solid colors, curated palettes and gradient presets- **Uploads** — drag-and-drop your own images (a persistent library since v0.14: uploads survive reload and follow your account)+- **Charts** — data-bound bar / line / donut / scatter charts: add one from+ the Elements panel, edit labels, values and series in the toolbar's+ spreadsheet editor, convert between kinds in place — geometry stays+ live in the editor, video exports and SVG exports- **Undo / redo** — full history stack with keyboard shortcuts- **Autosave** — designs persist to the database automatically- **Export** — PNG & JPG at 1× / 2× / 3× quality, current page or all pages,@@ -976,6 +980,18 @@ tool descriptions so agents pick the right format.`ON DELETE SET NULL`), and trashed designs return to theirfolder on restore. Foreign folder ids are flat 404s everywhere(no cross-account probe) *(v0.14.2)*+- [x] Charts (v0.14 D7) — a native, data-bound `chart` element+ (bar/line/donut/scatter) replaces the old one-shot exploded+ charts: one pure geometry module drives the editor, video+ exports and SVG exports (parity by construction), the toolbar+ edits labels/values/series in a spreadsheet popover and converts+ kinds in place, donuts take the first series with a centre+ total, scatter uses flat x,y pairs on numeric axes, pasted+ charts run the hostile-input gauntlet (kind whitelist, series+ caps), and MCP gains `add_chart` + series support in+ `update_element`. While wiring the video exporter, tables,+ frames and embed cards stopped vanishing from video exports+ (a pre-existing parity gap) *(v0.14.4)*- [ ] Mobile editor polish — touch-first selection handles, gesturezoom/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.jsonindex 0aa09fa..9b5dd92 100644--- a/package.json+++ b/package.json@@ -1,8 +1,8 @@{"name": "canvix",- "version": "0.14.3",+ "version": "0.14.4","private": false,- "description": "Canvix — free & open-source graphic design tool. A community-built Canva alternative.",+ "description": "Canvix \u2014 free & open-source graphic design tool. A community-built Canva alternative.","scripts": {"dev": "next dev -p 3000 2>&1 | tee dev.log","build": "node scripts/build.mjs",diff --git a/src/components/editor/PropertiesBar.tsx b/src/components/editor/PropertiesBar.tsxindex ec95d3e..a9cf4b8 100644--- a/src/components/editor/PropertiesBar.tsx+++ b/src/components/editor/PropertiesBar.tsx@@ -10,10 +10,12 @@ import {FlipHorizontal, FlipVertical, Sun, Contrast, Palette, RotateCcw, Replace, Lock, LockOpen,Layers, SquareDashed, Crop, Spline, Table2, Rows3, Columns3, Trash, Upload, ExternalLink,Music, Film, Play, Repeat, Volume2, VolumeX, SlidersHorizontal, Activity, Puzzle, LayoutGrid, Wand2,+ BarChart3, LineChart, PieChart, ScatterChart,} from 'lucide-react'import { useEditorStore, selectedElements, currentPageData } from '@/store/editor-store'-import type { AudioElement, EmbedElement, FrameElement, ImageElement, LineElement, PluginElement, ShapeElement, StickerElement, TableElement, TextElement, VideoElement, AnyElement, FrameShape } from '@/lib/types'-import { FRAME_SHAPES, isGroup } from '@/lib/types'+import type { AudioElement, ChartElement, ChartSeries, EmbedElement, FrameElement, ImageElement, LineElement, PluginElement, ShapeElement, StickerElement, TableElement, TextElement, VideoElement, AnyElement, FrameShape, ChartKind } from '@/lib/types'+import { FRAME_SHAPES, isGroup, CHART_KINDS, CHART_KIND_LABELS } from '@/lib/types'+import { CHART_PALETTE, MAX_CHART_LABELS, MAX_CHART_SERIES, CHART_VALUE_LIMIT } from '@/lib/chart-geometry'import { TEXT_EFFECTS } from '@/lib/types'import { beatSourceOf } from '@/lib/media/beat-detect'import { cn } from '@/lib/utils'@@ -67,6 +69,7 @@ export function ContextToolbar({ variant = 'topbar' }: { variant?: 'topbar' | 'mconst table = first.type === 'table' ? (first as TableElement) : nullconst frame = first.type === 'frame' ? (first as FrameElement) : nullconst embed = first.type === 'embed' ? (first as EmbedElement) : null+ const chart = first.type === 'chart' ? (first as ChartElement) : nullconst plugin = first.type === 'plugin' ? (first as PluginElement) : nullconst audio = first.type === 'audio' ? (first as AudioElement) : nullconst video = first.type === 'video' ? (first as VideoElement) : null@@ -393,6 +396,15 @@ export function ContextToolbar({ variant = 'topbar' }: { variant?: 'topbar' | 'm<Divider /><PositionPopover ids={ids} count={1} element={first} /></>+ ) : chart ? (+ <>+ <span className="text-[12px] font-semibold text-white/85 px-2 shrink-0 flex items-center gap-1.5">+ <BarChart3 size={13} /> {CHART_KIND_LABELS[chart.kind]}+ </span>+ <ChartToolbar chart={chart} ids={ids} />+ <Divider />+ <PositionPopover ids={ids} count={1} element={first} />+ </>) : plugin ? (<><span className="text-[12px] font-semibold text-white/85 px-2 shrink-0 flex items-center gap-1.5">@@ -1034,3 +1046,322 @@ function PluginToolbar({ plugin, ids }: { plugin: PluginElement; ids: string[] }</>)}++// ── v0.14 (D7): chart toolbar — kind switcher, data editor, options ──++const CHART_KIND_ICONS: Record<ChartKind, typeof BarChart3> = {+ bar: BarChart3,+ line: LineChart,+ donut: PieChart,+ scatter: ScatterChart,+}++function ChartToolbar({ chart, ids }: { chart: ChartElement; ids: string[] }) {+ const update = useEditorStore((s) => s.updateElements)+ const updateLive = useEditorStore((s) => s.updateElementsLive)++ /** convert in place — scatter keeps labels empty; scatter→other reuses+ * the y values as data so nothing is lost in the round trip */+ const switchKind = (k: ChartKind) => {+ if (k === chart.kind) return+ const patch: Partial<ChartElement> = { kind: k }+ if (k === 'scatter') {+ patch.labels = []+ } else if (chart.kind === 'scatter' && !chart.labels.length) {+ const n = Math.max(2, Math.floor((chart.series[0]?.values.length ?? 0) / 2))+ patch.labels = Array.from({ length: n }, (_, i) => `Item ${i + 1}`)+ patch.series = chart.series.map((sr) => ({ ...sr, values: sr.values.filter((_, j) => j % 2 === 1) }))+ }+ update(ids, patch)+ }++ return (+ <>+ {CHART_KINDS.map((k) => {+ const Icon = CHART_KIND_ICONS[k]+ return (+ <TBtn key={k} onClick={() => switchKind(k)} title={CHART_KIND_LABELS[k]} ariaLabel={`Convert to ${CHART_KIND_LABELS[k]}`} dataActive={chart.kind === k}>+ <Icon size={15} />+ </TBtn>+ )+ })}+ <Divider />+ <ToolbarPopover+ width={540}+ trigger={(open) => (+ <button className="cv-tbtn gap-1 !px-2.5" data-active={open} aria-label="Edit chart data" title="Edit chart data">+ <Table2 size={14} /> <span className="text-[12px] hidden lg:inline">Edit data</span>+ </button>+ )}+ >+ <ChartDataEditor chart={chart} ids={ids} />+ </ToolbarPopover>+ <ToolbarPopover+ trigger={(open) => (+ <button className="cv-tbtn gap-1 !px-2.5" data-active={open} aria-label="Chart options" title="Chart options">+ <SlidersHorizontal size={14} /> <span className="text-[12px] hidden lg:inline">Options</span>+ </button>+ )}+ >+ <div className="text-[12px] font-bold text-white/90 mb-2">Chart options</div>+ {chart.kind === 'bar' && (+ <div className="flex items-center gap-2 mb-2">+ <span className="text-[11px] text-white/60 w-16">Bars</span>+ <ChartToggle label="Group" active={chart.barMode !== 'stack'} onClick={() => update(ids, { barMode: 'group' })} />+ <ChartToggle label="Stack" active={chart.barMode === 'stack'} onClick={() => update(ids, { barMode: 'stack' })} />+ </div>+ )}+ {chart.kind === 'donut' && (+ <SliderRow+ label="Hole size"+ value={Math.round(chart.hole * 100)}+ min={0}+ max={85}+ step={1}+ onChange={(v) => updateLive(ids, { hole: v / 100 })}+ onCommit={() => update(ids, { hole: chart.hole })}+ format={(v) => `${v}%`}+ />+ )}+ {chart.kind === 'line' && (+ <div className="flex items-center gap-2 mb-2">+ <span className="text-[11px] text-white/60 w-16">Line</span>+ <ChartToggle label="Smooth" active={chart.smooth} onClick={() => update(ids, { smooth: !chart.smooth })} />+ </div>+ )}+ <div className="flex items-center gap-2 mb-2 flex-wrap">+ <ChartToggle label="Grid" active={chart.showGrid} onClick={() => update(ids, { showGrid: !chart.showGrid })} />+ <ChartToggle label="Values" active={chart.showValues} onClick={() => update(ids, { showValues: !chart.showValues })} />+ <ChartToggle label="Legend" active={chart.showLegend} onClick={() => update(ids, { showLegend: !chart.showLegend })} />+ </div>+ <div className="flex items-center gap-2 mb-2">+ <span className="text-[11px] text-white/60">Panel</span>+ <ColorMenu value={chart.fill} onChange={(c, committed) => committed ? update(ids, { fill: c }) : updateLive(ids, { fill: c })} title="Chart background" />+ <span className="text-[11px] text-white/60 ml-2">Text</span>+ <ColorMenu value={chart.textColor} onChange={(c, committed) => committed ? update(ids, { textColor: c }) : updateLive(ids, { textColor: c })} title="Text colour" />+ </div>+ <SliderRow+ label="Text size"+ value={chart.fontSize}+ min={8}+ max={24}+ step={1}+ onChange={(v) => updateLive(ids, { fontSize: v })}+ onCommit={() => update(ids, { fontSize: chart.fontSize })}+ />+ </ToolbarPopover>+ <ToolbarPopover trigger={(open) => (+ <button className="cv-tbtn" data-active={open} aria-label="Transparency" title="Transparency">+ <Percent size={14} />+ </button>+ )}>+ <SliderRow label="Transparency" value={Math.round(chart.opacity * 100)} min={0} max={100} step={1}+ onChange={(v) => updateLive(ids, { opacity: v / 100 })}+ onCommit={() => update(ids, { opacity: chart.opacity })}+ format={(v) => `${100 - v}% transparent`} />+ </ToolbarPopover>+ </>+ )+}++function ChartToggle({ label, active, onClick }: { label: string; active: boolean; onClick: () => void }) {+ return (+ <button+ onClick={onClick}+ aria-pressed={active}+ className={cn(+ 'h-7 rounded-md px-2.5 text-[11px] border transition-colors shrink-0',+ active ? 'bg-[#7630D7] border-[#7630D7] text-white' : 'bg-white/[0.05] border-white/10 text-white/60 hover:text-white'+ )}+ >+ {label}+ </button>+ )+}++/** number input with a typing draft — "-" and partial numbers never+ * snap back mid-edit, valid numbers commit live (the house pattern) */+function ChartNumInput({ value, onCommit, ariaLabel, className }: { value: number; onCommit: (n: number) => void; ariaLabel: string; className?: string }) {+ const [draft, setDraft] = useState<string | null>(null)+ return (+ <input+ type="text"+ inputMode="decimal"+ aria-label={ariaLabel}+ value={draft ?? String(value)}+ onChange={(e) => {+ const raw = e.target.value+ setDraft(raw)+ if (raw === '' || raw === '-' || raw === '.' || raw === '-.') return+ const n = Number(raw)+ if (Number.isFinite(n)) onCommit(Math.max(-CHART_VALUE_LIMIT, Math.min(CHART_VALUE_LIMIT, n)))+ }}+ onBlur={() => setDraft(null)}+ onKeyDown={(e) => {+ if (e.key === 'Enter') (e.target as HTMLInputElement).blur()+ }}+ className={cn('w-14 bg-white/[0.06] rounded-md px-1.5 py-1 text-[12px] text-white/90 border border-white/10 focus:border-[#7630D7] outline-none tabular-nums', className)}+ />+ )+}++const CV_INPUT_CLS = 'bg-white/[0.06] rounded-md px-1.5 py-1 text-[12px] text-white/90 border border-white/10 focus:border-[#7630D7] outline-none'++function ChartDataEditor({ chart, ids }: { chart: ChartElement; ids: string[] }) {+ const update = useEditorStore((s) => s.updateElements)+ const updateLive = useEditorStore((s) => s.updateElementsLive)+ const scatter = chart.kind === 'scatter'++ // typing = live (house pattern — table cells do the same);+ // structural ops = one undo step each+ const setLabels = (labels: string[]) => updateLive(ids, { labels })+ const setSeries = (series: ChartSeries[]) => updateLive(ids, { series })+ const setSeriesField = (i: number, patch: Partial<ChartSeries>) =>+ setSeries(chart.series.map((sr, j) => (j === i ? { ...sr, ...patch } : sr)))++ const setLabel = (i: number, v: string) => {+ const labels = [...chart.labels]+ labels[i] = v.slice(0, 24)+ setLabels(labels)+ }+ const addLabel = () => {+ if (chart.labels.length >= MAX_CHART_LABELS) return+ update(ids, {+ labels: [...chart.labels, `Item ${chart.labels.length + 1}`],+ series: chart.series.map((sr) => ({ ...sr, values: [...sr.values, 0] })),+ })+ }+ const removeLabel = () => {+ if (chart.labels.length <= 1) return+ update(ids, {+ labels: chart.labels.slice(0, -1),+ series: chart.series.map((sr) => ({ ...sr, values: sr.values.slice(0, -1) })),+ })+ }+ const addSeries = () => {+ if (chart.series.length >= MAX_CHART_SERIES) return+ const values = scatter ? [10, 20, 30, 40] : chart.labels.map((_, i) => 20 + i * 5)+ update(ids, {+ series: [...chart.series, { name: `Series ${chart.series.length + 1}`, color: CHART_PALETTE[chart.series.length % CHART_PALETTE.length], values }],+ })+ }+ const removeSeries = (i: number) => {+ if (chart.series.length <= 1) return+ update(ids, { series: chart.series.filter((_, j) => j !== i) })+ }+ const setValue = (si: number, vi: number, n: number) => {+ const values = [...chart.series[si].values]+ values[vi] = n+ setSeriesField(si, { values })+ }+ const addPoint = (si: number) => {+ const values = [...chart.series[si].values]+ if (values.length >= 48) return+ const lastX = values.length >= 2 ? values[values.length - 2] : 0+ values.push(Math.round(lastX + 10), 50)+ setSeriesField(si, { values })+ }+ const removePoint = (si: number, pi: number) => {+ if (chart.series[si].values.length <= 4) return+ const values = [...chart.series[si].values]+ values.splice(pi * 2, 2)+ setSeriesField(si, { values })+ }++ return (+ <div>+ <div className="text-[12px] font-bold text-white/90 mb-2">Chart data</div>+ {scatter ? (+ <div className="max-h-[320px] overflow-y-auto cv-scroll-dark pr-1">+ {chart.series.map((sr, si) => (+ <div key={si} className="mb-3 pb-2 border-b border-white/[0.07] last:border-b-0">+ <div className="flex items-center gap-1.5 mb-1.5">+ <ColorMenu value={sr.color} onChange={(c, committed) => committed ? update(ids, { series: chart.series.map((x, j) => (j === si ? { ...x, color: c } : x)) }) : setSeriesField(si, { color: c })} title={`Series ${si + 1} colour`} />+ <input value={sr.name} onChange={(e) => setSeriesField(si, { name: e.target.value.slice(0, 40) })} aria-label={`Series ${si + 1} name`} className={cn(CV_INPUT_CLS, 'w-28')} />+ {chart.series.length > 1 && (+ <TBtn onClick={() => removeSeries(si)} title="Remove series" ariaLabel={`Remove series ${si + 1}`} danger className="!h-7 !w-7">+ <Trash2 size={12} />+ </TBtn>+ )}+ </div>+ {Array.from({ length: Math.floor(sr.values.length / 2) }, (_, pi) => (+ <div key={pi} className="flex items-center gap-1.5 mb-1">+ <span className="w-4 text-[10px] text-white/35 text-right">x</span>+ <ChartNumInput value={sr.values[pi * 2] ?? 0} onCommit={(n) => setValue(si, pi * 2, n)} ariaLabel={`Series ${si + 1} point ${pi + 1} x`} />+ <span className="w-4 text-[10px] text-white/35 text-right">y</span>+ <ChartNumInput value={sr.values[pi * 2 + 1] ?? 0} onCommit={(n) => setValue(si, pi * 2 + 1, n)} ariaLabel={`Series ${si + 1} point ${pi + 1} y`} />+ <TBtn onClick={() => removePoint(si, pi)} title="Remove point" ariaLabel={`Remove point ${pi + 1}`} disabled={sr.values.length <= 4} className="!h-6 !w-6">+ <Minus size={11} />+ </TBtn>+ </div>+ ))}+ <button onClick={() => addPoint(si)} disabled={sr.values.length >= 48} className="btn-cv h-7 px-3 text-[11px] mt-1">+ + Point+ </button>+ </div>+ ))}+ <p className="text-[10px] text-white/35">Each point is an x, y pair on numeric axes.</p>+ </div>+ ) : (+ <div>+ <div className="max-h-[240px] overflow-auto cv-scroll-dark">+ <table className="border-collapse text-[12px]">+ <thead>+ <tr>+ <th className="sticky left-0 bg-[#1B1D24] z-10 pr-2 pb-2 text-left text-white/40 font-medium text-[10px] w-[128px]">Series \ Labels</th>+ {chart.labels.map((l, i) => (+ <th key={i} className="px-1 pb-2">+ <input value={l} onChange={(e) => setLabel(i, e.target.value)} aria-label={`Label ${i + 1}`} className={cn(CV_INPUT_CLS, 'w-16')} />+ </th>+ ))}+ <th className="pl-1 pb-2 w-[52px]">+ <TBtn onClick={addLabel} title="Add label" ariaLabel="Add label" disabled={chart.labels.length >= MAX_CHART_LABELS} className="!h-6 !w-6">+ <Plus size={11} />+ </TBtn>+ </th>+ <th className="pb-2 w-[36px]">+ <TBtn onClick={removeLabel} title="Remove last label" ariaLabel="Remove last label" disabled={chart.labels.length <= 1} className="!h-6 !w-6">+ <Minus size={11} />+ </TBtn>+ </th>+ </tr>+ </thead>+ <tbody>+ {chart.series.map((sr, si) => (+ <tr key={si}>+ <td className="sticky left-0 bg-[#1B1D24] z-10 pr-2 pb-2">+ <div className="flex items-center gap-1">+ <ColorMenu value={sr.color} onChange={(c, committed) => committed ? update(ids, { series: chart.series.map((x, j) => (j === si ? { ...x, color: c } : x)) }) : setSeriesField(si, { color: c })} title={`Series ${si + 1} colour`} />+ <input value={sr.name} onChange={(e) => setSeriesField(si, { name: e.target.value.slice(0, 40) })} aria-label={`Series ${si + 1} name`} className={cn(CV_INPUT_CLS, 'w-16')} />+ {chart.series.length > 1 && (+ <TBtn onClick={() => removeSeries(si)} title="Remove series" ariaLabel={`Remove series ${si + 1}`} danger className="!h-6 !w-6">+ <Trash2 size={11} />+ </TBtn>+ )}+ </div>+ </td>+ {chart.labels.map((_, vi) => (+ <td key={vi} className="px-1 pb-2">+ <ChartNumInput value={sr.values[vi] ?? 0} onCommit={(n) => setValue(si, vi, n)} ariaLabel={`Series ${si + 1} value ${vi + 1}`} />+ </td>+ ))}+ <td />+ <td />+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ </div>+ )}+ <div className="flex items-center gap-2 mt-2">+ <button onClick={addSeries} disabled={chart.series.length >= MAX_CHART_SERIES} className="btn-cv h-7 px-3 text-[11px]">+ + Series+ </button>+ <span className="text-[10px] text-white/35">+ {scatter ? 'One x,y point per row.' : chart.kind === 'donut' ? 'Donut renders the first series.' : 'Values update the chart live.'}+ </span>+ </div>+ </div>+ )+}diff --git a/src/components/editor/add-element.ts b/src/components/editor/add-element.tsindex b0737e5..5c6c523 100644--- a/src/components/editor/add-element.ts+++ b/src/components/editor/add-element.ts@@ -9,7 +9,9 @@ import {createTableElement,createFrameElement,createEmbedElement,+ createChartElement,type AnyElement,+ type ChartKind,type FrameShape,} from '@/lib/types'import { useEditorStore } from '@/store/editor-store'@@ -155,6 +157,15 @@ export function addEmbed(url: string, title?: string) {addCentered(createEmbedElement(withProto, { width: 340, height: 214, ...(title ? { title } : {}) }))}+// ── v0.14 (D7): data-bound charts ──────────────────────────++/** Add a native chart — data stays editable from the context toolbar. */+export function addChart(kind: ChartKind) {+ const w = kind === 'donut' ? 380 : kind === 'scatter' ? 520 : 560+ const h = kind === 'donut' ? 380 : 360+ addCentered(createChartElement(kind, { width: w, height: h }))+}+/** If a page point lands inside a frame element, fill that frame with the image (canva drop-to-fill). */export function fillFrameAt(pageX: number, pageY: number, src: string, naturalWidth: number, naturalHeight: number): boolean {const state = useEditorStore.getState()diff --git a/src/components/editor/apps/ChartsApp.tsx b/src/components/editor/apps/ChartsApp.tsxindex 5ce4726..301c3d8 100644--- a/src/components/editor/apps/ChartsApp.tsx+++ b/src/components/editor/apps/ChartsApp.tsx@@ -1,30 +1,39 @@'use client'-import { BarChart3, LineChart, PieChart } from 'lucide-react'-import { useEditorStore } from '@/store/editor-store'-import { createShapeElement, createTextElement, createLineElement, type AnyElement } from '@/lib/types'-import { AppHeader, type AppPanelProps } from './registry'-import { toast } from '@/hooks/use-toast'+// ─────────────────────────────────────────────────────────────+// ChartsApp (v0.14, D7) — the Apps-panel rail for charts.+//+// Until v0.14 charts were one-shot: this app exploded a chart into+// loose rects/lines/text (edit a bar and the "chart" was gone).+// The rail now adds ONE native, data-bound chart element — the+// sample data is editable from the context toolbar (Edit data:+// labels, values, series, colours, kind) and re-renders in the+// editor, video exports and SVG exports.+// ─────────────────────────────────────────────────────────────-const PALETTE = ['#7630D7', '#02C0CC', '#FF5C8A', '#FFD166', '#22C55E', '#3B82F6', '#F97316', '#EF4444']-const DATA = [42, 68, 55, 90, 37, 74]+import { BarChart3, LineChart, PieChart, ScatterChart } from 'lucide-react'+import { addChart } from '../add-element'+import { AppHeader, type AppPanelProps } from './registry'+import { CHART_KIND_LABELS, type ChartKind } from '@/lib/types'-function chartBase(w: number, h: number) {- const state = useEditorStore.getState()- return { x: Math.round((state.width - w) / 2), y: Math.round((state.height - h) / 2) }-}+const ROWS: { kind: ChartKind; icon: typeof BarChart3; desc: string }[] = [+ { kind: 'bar', icon: BarChart3, desc: 'Grouped or stacked — edit every value' },+ { kind: 'line', icon: LineChart, desc: 'Trend lines with dots, optional smoothing' },+ { kind: 'donut', icon: PieChart, desc: 'Ring with centre total and legend' },+ { kind: 'scatter', icon: ScatterChart, desc: 'XY points on numeric axes' },+]export function ChartsApp({ onClose }: AppPanelProps) {return (<div><AppHeader icon={BarChart3} title="Charts" onClose={onClose} /><p className="text-[11px] text-white/45 leading-relaxed mb-3">- Charts are added as native elements — every bar, dot and label stays fully editable on the canvas.+ Charts are native data-bound elements — select one on the canvas and hit <span className="text-white/70">Edit data</span> in the toolbar to change labels, values and colours.</p><div className="space-y-2">- <ChartRow icon={BarChart3} name="Bar chart" desc="6 bars, colourful, editable" onAdd={addBarChart} />- <ChartRow icon={LineChart} name="Line chart" desc="Trend line with vertex dots" onAdd={addLineChart} />- <ChartRow icon={PieChart} name="Donut chart" desc="Progress ring + centre label" onAdd={addDonut} />+ {ROWS.map((r) => (+ <ChartRow key={r.kind} icon={r.icon} name={CHART_KIND_LABELS[r.kind]} desc={r.desc} onAdd={() => addChart(r.kind)} />+ ))}</div></div>)@@ -56,85 +65,3 @@ function ChartRow({ icon: Icon, name, desc, onAdd }: { icon: typeof BarChart3; n</div>)}--function addBarChart() {- const store = useEditorStore.getState()- store.pushHistory()- const W = 700, H = 420, padL = 40, padB = 46, padT = 20- const max = Math.max(...DATA)- const n = DATA.length- const bandW = (W - padL - 12) / n- const barW = bandW * 0.6- const { x, y } = chartBase(W, H)- const els: AnyElement[] = []-- // baseline- els.push(createLineElement({ x: x + padL, y: y + H - padB, width: W - padL - 12, height: 0, stroke: '#9CA3AF', strokeWidth: 3 }))- DATA.forEach((v, i) => {- const barH = Math.round(((H - padB - padT) * v) / max)- const bx = x + padL + i * bandW + (bandW - barW) / 2- const by = y + H - padB - barH- els.push(createShapeElement('rect', { x: Math.round(bx), y: by, width: Math.round(barW), height: barH, fill: PALETTE[i % PALETTE.length], cornerRadius: 8 }))- // label- els.push(createTextElement({ x: Math.round(bx), y: y + H - padB + 10, width: Math.round(barW), text: `Q${i + 1}`, fontSize: 22, fill: '#6B7280', align: 'center' }))- })- els.forEach((el) => store.addElement(el))- toast({ title: 'Bar chart added — edit any bar like a shape' })-}--function addLineChart() {- const store = useEditorStore.getState()- store.pushHistory()- const W = 700, H = 380, padL = 30, padB = 40, padT = 20- const max = Math.max(...DATA)- const { x, y } = chartBase(W, H)- const pts = DATA.map((v, i) => {- const px = padL + (i * (W - padL - 20)) / (DATA.length - 1)- const py = padT + (1 - v / max) * (H - padB - padT)- return { px: Math.round(px), py: Math.round(py) }- })- pts.forEach((p, i) => {- if (i === 0) return- const a = pts[i - 1]- const dx = p.px - a.px- const dy = p.py - a.py- const len = Math.round(Math.hypot(dx, dy))- const angle = Math.round((Math.atan2(dy, dx) * 180) / Math.PI)- store.addElement(createLineElement({ x: x + a.px, y: y + a.py, width: len, height: 0, rotation: angle, stroke: '#02C0CC', strokeWidth: 6 }))- // vertex dot- store.addElement(createShapeElement('ellipse', { x: x + p.px - 9, y: y + p.py - 9, width: 18, height: 18, fill: '#02C0CC' }))- })- toast({ title: 'Line chart added' })-}--function addDonut() {- const store = useEditorStore.getState()- store.pushHistory()- const { x, y } = chartBase(320, 320)- const segments = 12- const filled = 8- const cx = x + 160, cy = y + 160, r = 110- for (let i = 0; i < segments; i++) {- const a0 = (i / segments) * Math.PI * 2 - Math.PI / 2- const chord = 2 * r * Math.sin(Math.PI / segments)- const midA = a0 + Math.PI / segments- const len = Math.round(chord * 0.82)- const ang = Math.round((midA * 180) / Math.PI)- const px = cx + r * Math.cos(midA) - len / 2- const py = cy + r * Math.sin(midA)- store.addElement(- createLineElement({- x: Math.round(px),- y: Math.round(py),- width: len,- height: 0,- rotation: ang,- stroke: i < filled ? '#7630D7' : '#2A2C35',- strokeWidth: 34,- })- )- }- // center label- store.addElement(createTextElement({ x: x + 60, y: y + 130, width: 200, text: '68%', fontSize: 64, bold: true, fill: '#FFFFFF', align: 'center' }))- toast({ title: 'Donut chart added — tweak segments as lines' })-}diff --git a/src/components/editor/canvas/chart-node.tsx b/src/components/editor/canvas/chart-node.tsxnew file mode 100644index 0000000..445b32d--- /dev/null+++ b/src/components/editor/canvas/chart-node.tsx@@ -0,0 +1,88 @@+'use client'++// ─────────────────────────────────────────────────────────────+// chart-node (v0.14, D7) — the editor renderer for the data-bound+// chart element. A thin adapter: ALL geometry comes from+// lib/chart-geometry.ts (see that module's header for the parity+// contract with video-export.ts and svg-export.ts).+// ─────────────────────────────────────────────────────────────++import { Arc, Circle, Group, Line, Rect, Text } from 'react-konva'+import { chartPrimitives, type ChartPrimitive } from '@/lib/chart-geometry'+import type { ChartElement } from '@/lib/types'++/** Konva.Text positions its box TOP; chart primitives carry baselines.+ * 0.78 ≈ Inter's ascent — labels land within a pixel of the SVG export. */+const KONVA_TEXT_ASCENT = 0.78++function textProps(p: Extract<ChartPrimitive, { kind: 'text' }>) {+ const base = {+ y: p.y - p.size * KONVA_TEXT_ASCENT,+ text: p.text,+ fontSize: p.size,+ fontFamily: p.family,+ fill: p.fill,+ fontStyle: p.bold ? '700' : '400',+ perfectDrawEnabled: false as const,+ }+ // anchored text without measuring: center/right inside a wide box+ // offset from the anchor (SVG uses text-anchor — see svg-export.ts)+ if (p.anchor === 'middle') return { ...base, x: p.x - 2000, width: 4000, align: 'center' as const }+ if (p.anchor === 'end') return { ...base, x: p.x - 1000, width: 1000, align: 'right' as const }+ return { ...base, x: p.x }+}++function PrimNode({ p }: { p: ChartPrimitive }) {+ switch (p.kind) {+ case 'rect':+ return (+ <Rect+ x={p.x}+ y={p.y}+ width={p.w}+ height={p.h}+ cornerRadius={p.r ?? 0}+ fill={p.fill}+ stroke={p.stroke}+ strokeWidth={p.strokeWidth ?? 1}+ />+ )+ case 'line':+ return <Line points={[p.x1, p.y1, p.x2, p.y2]} stroke={p.stroke} strokeWidth={p.width} dash={p.dash} lineCap="round" />+ case 'polyline':+ return <Line points={p.points} stroke={p.stroke} strokeWidth={p.width} lineCap="round" lineJoin="round" />+ case 'circle':+ return <Circle x={p.cx} y={p.cy} radius={p.r} fill={p.fill} stroke={p.stroke} strokeWidth={p.strokeWidth ?? 1} />+ case 'arc':+ // Konva.Arc: sweep `angle` from `rotation` (degrees, 0 = 3 o'clock,+ // clockwise — the same convention as the geometry's radians)+ return (+ <Arc+ x={p.cx}+ y={p.cy}+ innerRadius={p.rIn}+ outerRadius={p.rOut}+ angle={((p.a1 - p.a0) * 180) / Math.PI}+ rotation={(p.a0 * 180) / Math.PI}+ fill={p.fill}+ />+ )+ case 'text':+ return <Text {...textProps(p)} />+ }+}++export function ChartNode({ el, common }: { el: ChartElement; common: Record<string, unknown> }) {+ const prims = chartPrimitives(el)+ return (+ <Group {...common} clip={undefined}>+ {/* invisible hit area — a fully transparent fill is not hittable+ in Konva, and charts with fill="transparent" must still be+ selectable/draggable like every other element */}+ <Rect width={el.width} height={el.height} fill="rgba(0,0,0,0.001)" />+ {prims.map((p, i) => (+ <PrimNode key={i} p={p} />+ ))}+ </Group>+ )+}diff --git a/src/components/editor/canvas/element-node.tsx b/src/components/editor/canvas/element-node.tsxindex 912aff7..b8727a8 100644--- a/src/components/editor/canvas/element-node.tsx+++ b/src/components/editor/canvas/element-node.tsx@@ -7,6 +7,7 @@ import type { KonvaEventObject } from 'konva/lib/Node'import type {AnyElement,AudioElement,+ ChartElement,EmbedElement,FrameElement,GroupElement,@@ -27,6 +28,7 @@ import { useLoadedImage } from './use-loaded-image'import { isImageFilterId, clampFilterIntensity, applyPresetToImageData } from '@/lib/image-filters'import { CurvedTextNode, EmbedNode, FrameNode, TableNode, type TableCellRef } from './v06-nodes'import { PluginNode } from './PluginNode'+import { ChartNode } from './chart-node'export interface ElementNodeProps {element: AnyElement@@ -650,6 +652,12 @@ function ElementNodeImpl({ element: el, interactive, hiding, hideCell, registerNreturn <EmbedNode el={em} common={common} />}+ // v0.14 (D7): data-bound chart — geometry from lib/chart-geometry.ts+ case 'chart': {+ const ch = el as ChartElement+ return <ChartNode el={ch} common={common} />+ }+// v0.13 (P4): plugin-owned elements — pixels delegated to the// plugin's registered renderer via the cache; every failure// state degrades to a placeholder card, never data lossdiff --git a/src/components/editor/panels/ElementsPanel.tsx b/src/components/editor/panels/ElementsPanel.tsxindex a12313e..3652931 100644--- a/src/components/editor/panels/ElementsPanel.tsx+++ b/src/components/editor/panels/ElementsPanel.tsx@@ -3,10 +3,10 @@import { useMemo, useState } from 'react'import { Square, Circle, Triangle, Star, Minus, ArrowRight, MoveHorizontal, Search, Hexagon, Pentagon, Diamond, CircleDashed, Frame, Youtube, MapPin, Link2 } from 'lucide-react'import { GRAPHICS, STICKER_GROUPS } from '@/lib/editor-utils'-import { addEmbed, addFrame, addGraphic, addLine, addShape, addSticker, addTable, type TableStyle } from '../add-element'+import { addChart, addEmbed, addFrame, addGraphic, addLine, addShape, addSticker, addTable, type TableStyle } from '../add-element'import { cn } from '@/lib/utils'import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'-import { FRAME_SHAPES } from '@/lib/types'+import { FRAME_SHAPES, type ChartKind } from '@/lib/types'function GraphicIcon({ path }: { path: string }) {return (@@ -51,11 +51,68 @@ const CATEGORY_TABS = [{ value: 'lines', label: 'Lines' },{ value: 'graphics', label: 'Graphics' },{ value: 'stickers', label: 'Stickers' },+ { value: 'charts', label: 'Charts' },{ value: 'tables', label: 'Tables' },{ value: 'frames', label: 'Frames' },{ value: 'embeds', label: 'Embeds' },] as const+/** v0.14 (D7): chart tiles — small pure-SVG minis (decorative, not live). */+const CHART_TILES: { kind: ChartKind; label: string; mini: React.ReactNode }[] = [+ {+ kind: 'bar',+ label: 'Bar',+ mini: (+ <svg viewBox="0 0 56 40" className="h-10 w-14" aria-hidden="true">+ <rect x="4" y="14" width="8" height="22" rx="2" fill="#7630D7" />+ <rect x="16" y="8" width="8" height="28" rx="2" fill="#02C0CC" />+ <rect x="28" y="18" width="8" height="18" rx="2" fill="#FF5C8A" />+ <rect x="40" y="4" width="8" height="32" rx="2" fill="#FFD166" />+ </svg>+ ),+ },+ {+ kind: 'line',+ label: 'Line',+ mini: (+ <svg viewBox="0 0 56 40" className="h-10 w-14" aria-hidden="true">+ <polyline points="4,30 18,22 30,26 44,10 52,14" fill="none" stroke="#7630D7" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" />+ <circle cx="4" cy="30" r="3" fill="#7630D7" />+ <circle cx="18" cy="22" r="3" fill="#7630D7" />+ <circle cx="30" cy="26" r="3" fill="#7630D7" />+ <circle cx="44" cy="10" r="3" fill="#7630D7" />+ <circle cx="52" cy="14" r="3" fill="#7630D7" />+ </svg>+ ),+ },+ {+ kind: 'donut',+ label: 'Donut',+ mini: (+ <svg viewBox="0 0 56 40" className="h-10 w-14" aria-hidden="true">+ <circle cx="28" cy="20" r="14" fill="none" stroke="#7630D7" strokeWidth="8" strokeDasharray="44 88" transform="rotate(-90 28 20)" />+ <circle cx="28" cy="20" r="14" fill="none" stroke="#02C0CC" strokeWidth="8" strokeDasharray="30 88" strokeDashoffset="-44" transform="rotate(-90 28 20)" />+ <circle cx="28" cy="20" r="14" fill="none" stroke="#FFD166" strokeWidth="8" strokeDasharray="14 88" strokeDashoffset="-74" transform="rotate(-90 28 20)" />+ </svg>+ ),+ },+ {+ kind: 'scatter',+ label: 'Scatter',+ mini: (+ <svg viewBox="0 0 56 40" className="h-10 w-14" aria-hidden="true">+ <circle cx="8" cy="32" r="3" fill="#02C0CC" />+ <circle cx="16" cy="24" r="3" fill="#02C0CC" />+ <circle cx="22" cy="30" r="3" fill="#02C0CC" />+ <circle cx="30" cy="16" r="3" fill="#02C0CC" />+ <circle cx="38" cy="22" r="3" fill="#02C0CC" />+ <circle cx="46" cy="8" r="3" fill="#02C0CC" />+ <circle cx="50" cy="18" r="3" fill="#02C0CC" />+ </svg>+ ),+ },+]+/** One shared class ⇒ identical height, padding, type size and states on every tab.* text-white/65 on the white@5% bar = 7.38:1 (WCAG AA, was ~1.3:1 via text-foreground). */const CATEGORY_TAB_CLS =@@ -192,6 +249,27 @@ export function ElementsPanel() {))}</TabsContent>+ {/* v0.14 (D7): data-bound charts */}+ <TabsContent value="charts" className="flex-1 overflow-y-auto cv-scroll-dark p-4 mt-0">+ <p className="text-[11px] text-white/45 leading-relaxed mb-3">+ Charts are data-bound elements — select one on the canvas and use <span className="text-white/70">Edit data</span> in the toolbar to change labels, values, colours and kind.+ </p>+ <SectionTitle>Types</SectionTitle>+ <div className="grid grid-cols-2 gap-2">+ {CHART_TILES.map((t) => (+ <button+ key={t.kind}+ onClick={() => addChart(t.kind)}+ className="flex flex-col items-center gap-1.5 rounded-xl border border-white/10 bg-white/[0.03] p-3 h-[92px] hover:border-[#7630D7] hover:bg-[#7630D7]/10 transition-all"+ aria-label={`Add ${t.label} chart`}+ >+ {t.mini}+ <span className="text-[11px] text-white/55">{t.label}</span>+ </button>+ ))}+ </div>+ </TabsContent>+{/* v0.6: native tables */}<TabsContent value="tables" className="flex-1 overflow-y-auto cv-scroll-dark p-4 mt-0"><p className="text-[11px] text-white/45 leading-relaxed mb-3">diff --git a/src/components/editor/panels/LayersPanel.tsx b/src/components/editor/panels/LayersPanel.tsxindex c30006d..aa685b0 100644--- a/src/components/editor/panels/LayersPanel.tsx+++ b/src/components/editor/panels/LayersPanel.tsx@@ -1,10 +1,11 @@'use client'import { useState } from 'react'-import { ChevronUp, ChevronDown, ChevronsUp, ChevronsDown, Lock, LockOpen, Eye, EyeOff, Trash2, Type, Image as ImageIcon, Square, Minus, Smile, PenTool, Group as GroupIcon, Table2, Frame as FrameIcon, ExternalLink } from 'lucide-react'+import { ChevronUp, ChevronDown, ChevronsUp, ChevronsDown, Lock, LockOpen, Eye, EyeOff, Trash2, Type, Image as ImageIcon, Square, Minus, Smile, PenTool, Group as GroupIcon, Table2, Frame as FrameIcon, ExternalLink, BarChart3 } from 'lucide-react'import { useEditorStore, currentPageData } from '@/store/editor-store'import { cn } from '@/lib/utils'import type { AnyElement } from '@/lib/types'+import { CHART_KIND_LABELS } from '@/lib/types'function elementIcon(el: AnyElement) {switch (el.type) {@@ -18,6 +19,7 @@ function elementIcon(el: AnyElement) {case 'table': return Table2case 'frame': return FrameIconcase 'embed': return ExternalLink+ case 'chart': return BarChart3default: return Square}}@@ -34,6 +36,7 @@ function elementLabel(el: AnyElement): string {if (el.type === 'table') return 'Table'if (el.type === 'frame') return el.src ? 'Frame' : 'Empty frame'if (el.type === 'embed') return 'Embed card'+ if (el.type === 'chart') return CHART_KIND_LABELS[el.kind] ?? 'Chart'return el.type.charAt(0).toUpperCase() + el.type.slice(1)}diff --git a/src/lib/chart-geometry.test.ts b/src/lib/chart-geometry.test.tsnew file mode 100644index 0000000..695565a--- /dev/null+++ b/src/lib/chart-geometry.test.ts@@ -0,0 +1,263 @@+import { describe, it, expect } from 'vitest'+import {+ chartPrimitives,+ formatChartNumber,+ isChartKind,+ clampChartHole,+ sanitizeChartLabels,+ sanitizeChartSeries,+ MAX_CHART_LABELS,+ MAX_CHART_SERIES,+ type ChartPrimitive,+} from '@/lib/chart-geometry'+import { createChartElement, type ChartElement, type ChartSeries } from '@/lib/types'++// ── helpers ──────────────────────────────────────────────────++function chart(over: Partial<ChartElement> = {}): ChartElement {+ const el = createChartElement(over.kind ?? 'bar', over)+ return { ...el, ...over }+}++function ofKind<T extends ChartPrimitive['kind']>(prims: ChartPrimitive[], kind: T): Extract<ChartPrimitive, { kind: T }>[] {+ return prims.filter((p): p is Extract<ChartPrimitive, { kind: T }> => p.kind === kind)+}++/** every number in every primitive must be finite — the renderers+ * would emit `NaN` attributes otherwise (the classic geometry bug) */+function expectAllFinite(prims: ChartPrimitive[]): void {+ const walk = (v: unknown): void => {+ if (typeof v === 'number') expect(Number.isFinite(v), `non-finite coordinate: ${v}`).toBe(true)+ else if (Array.isArray(v)) v.forEach(walk)+ else if (v && typeof v === 'object') Object.values(v).forEach(walk)+ }+ prims.forEach(walk)+}++// ── number formatting ────────────────────────────────────────++describe('formatChartNumber', () => {+ it('compacts large magnitudes', () => {+ expect(formatChartNumber(12_340)).toBe('12.3k')+ expect(formatChartNumber(1500000)).toBe('1.5M')+ expect(formatChartNumber(2_400_000_000)).toBe('2.4B')+ expect(formatChartNumber(-42_000)).toBe('-42k')+ })+ it('keeps small numbers exact-ish', () => {+ expect(formatChartNumber(42)).toBe('42')+ expect(formatChartNumber(12.34)).toBe('12.3')+ expect(formatChartNumber(-7)).toBe('-7')+ expect(formatChartNumber(0)).toBe('0')+ })+})++// ── untrusted-input sanitizers (paste + MCP share these) ─────++describe('sanitizeChartSeries / sanitizeChartLabels', () => {+ it('drops junk, caps counts, clamps magnitudes', () => {+ const hostile = [+ { name: 42, color: 'javascript:alert(1)', values: [1, 'x', NaN, 2e12, -2e12] },+ 'not-an-object',+ null,+ { name: 'ok', color: '#02C0CC', values: [1, 2, 3] },+ ]+ const out = sanitizeChartSeries(hostile, false)+ expect(out).toHaveLength(2)+ expect(out[0].name).toBe('Series 1')+ expect(out[0].color).toMatch(/^#/) // palette fallback, not the javascript: string+ expect(out[0].values).toEqual([1, 1e9, -1e9]) // non-finite dropped, ±2e12 clamped to the 1e9 cap+ expect(out[1].values).toEqual([1, 2, 3])+ })++ it('caps series at the limit', () => {+ const many = Array.from({ length: 12 }, (_, i) => ({ name: `s${i}`, values: [i] }))+ expect(sanitizeChartSeries(many, false)).toHaveLength(MAX_CHART_SERIES)+ })++ it('caps values per shape and keeps scatter pairs even', () => {+ const values = Array.from({ length: 60 }, (_, i) => i)+ const bar = sanitizeChartSeries([{ name: 'a', values }], false)+ expect(bar[0].values).toHaveLength(MAX_CHART_LABELS)+ const scatter = sanitizeChartSeries([{ name: 'a', values }], true)+ expect(scatter[0].values.length).toBeLessThanOrEqual(48)+ expect(scatter[0].values.length % 2).toBe(0)+ })++ it('labels: strings only, sliced', () => {+ expect(sanitizeChartLabels(['ok', 7, null, 'x'.repeat(60), ...Array.from({ length: 40 }, () => 'y')])).toEqual([+ 'ok',+ 'x'.repeat(24),+ ...Array.from({ length: 22 }, () => 'y'),+ ])+ })+})++describe('isChartKind / clampChartHole', () => {+ it('whitelists the four kinds', () => {+ expect(isChartKind('bar')).toBe(true)+ expect(isChartKind('line')).toBe(true)+ expect(isChartKind('donut')).toBe(true)+ expect(isChartKind('scatter')).toBe(true)+ expect(isChartKind('EVIL')).toBe(false)+ expect(isChartKind({})).toBe(false)+ })+ it('clamps the hole ratio', () => {+ expect(clampChartHole(0.9)).toBe(0.85)+ expect(clampChartHole(-1)).toBe(0)+ expect(clampChartHole('junk')).toBe(0.62)+ expect(clampChartHole(0.5)).toBe(0.5)+ })+})++// ── geometry: bar ────────────────────────────────────────────++describe('chartPrimitives — bar', () => {+ const el = chart({ kind: 'bar', width: 560, height: 360, showLegend: false })+ const prims = chartPrimitives(el)++ it('emits a background panel, one rect per (label × series), axis lines and category labels', () => {+ expect(ofKind(prims, 'rect')[0]).toMatchObject({ x: 0, y: 0, w: 560, h: 360, r: 12 })+ const barRects = ofKind(prims, 'rect').slice(1)+ expect(barRects).toHaveLength(4 * 2) // 4 quarters × 2 series+ const texts = ofKind(prims, 'text')+ expect(texts.some((t) => t.text === 'Q1')).toBe(true)+ expect(texts.some((t) => t.text === 'Q4')).toBe(true)+ expect(ofKind(prims, 'line').length).toBeGreaterThan(0)+ })++ it('a bigger value in the SAME chart draws a taller bar', () => {+ const p = chartPrimitives(chart({ showLegend: false, series: [{ name: 'a', color: '#7630D7', values: [10, 20] }] }))+ const hs = ofKind(p, 'rect').slice(1).map((r) => (r as { h: number }).h)+ expect(hs[1]).toBeGreaterThan(hs[0])+ })++ it('stack mode renders per-label segments, not per-series bars', () => {+ const stacked = chartPrimitives(chart({ barMode: 'stack', showLegend: false }))+ const barRects = ofKind(stacked, 'rect').slice(1)+ expect(barRects).toHaveLength(4 * 2) // every (label, series) still has a segment+ const segs = barRects.filter((r) => (r as { h: number }).h > 0)+ expect(segs.length).toBeGreaterThan(0)+ })++ it('showValues adds one value label per bar', () => {+ const withValues = chartPrimitives(chart({ showValues: true }))+ const texts = ofKind(withValues, 'text').map((t) => t.text)+ expect(texts).toContain('128')+ expect(texts).toContain('190')+ })++ it('never emits non-finite coordinates', () => {+ const hostile = chart({+ width: 560,+ height: 360,+ series: [{ name: 'a', color: '#7630D7', values: [1, 2, 3] }, { name: 'b', color: '#02C0CC', values: [1, 2, 3] }],+ })+ expectAllFinite(chartPrimitives(hostile))+ })+})++// ── geometry: line ───────────────────────────────────────────++describe('chartPrimitives — line', () => {+ it('one polyline + dots per series, category labels on the x axis', () => {+ const prims = chartPrimitives(chart({ kind: 'line' }))+ expect(ofKind(prims, 'polyline')).toHaveLength(2)+ // 6 labels × 2 series of dots+ expect(ofKind(prims, 'circle')).toHaveLength(12)+ expect(ofKind(prims, 'text').some((t) => t.text === 'Jan')).toBe(true)+ })++ it('smooth sampling densifies the polyline but keeps the endpoints', () => {+ const smooth = chartPrimitives(chart({ kind: 'line', smooth: true }))+ const straight = chartPrimitives(chart({ kind: 'line', smooth: false }))+ const sp = ofKind(smooth, 'polyline')[0] as { points: number[] }+ const rp = ofKind(straight, 'polyline')[0] as { points: number[] }+ expect(sp.points.length).toBeGreaterThan(rp.points.length)+ expect(sp.points[0]).toBe(rp.points[0])+ expect(sp.points[sp.points.length - 1]).toBeCloseTo(rp.points[rp.points.length - 1], 6)+ })+})++// ── geometry: donut ──────────────────────────────────────────++describe('chartPrimitives — donut', () => {+ const el = chart({ kind: 'donut', hole: 0.5 })+ const prims = chartPrimitives(el)++ it('sweeps 2π across the segments and honors the hole ratio', () => {+ const arcs = ofKind(prims, 'arc')+ expect(arcs.length).toBeGreaterThan(0)+ const sweep = arcs.reduce((a, s) => a + ((s as { a1: number }).a1 - (s as { a0: number }).a0), 0)+ expect(sweep).toBeCloseTo(Math.PI * 2, 5)+ const first = arcs[0] as { rIn: number; rOut: number }+ expect(first.rIn).toBeCloseTo(first.rOut * 0.5, 5)+ })++ it('renders the total in the centre and the first series only', () => {+ const texts = ofKind(prims, 'text').map((t) => t.text)+ expect(texts).toContain('125') // 32+41+18+22+12+ // a second series exists on the element but donut uses series[0]+ const two = chartPrimitives(chart({ kind: 'donut', series: [+ { name: 'a', color: '#7630D7', values: [1, 1] },+ { name: 'b', color: '#02C0CC', values: [5, 5] },+ ] }))+ expect(ofKind(two, 'text').map((t) => t.text)).toContain('2')+ })++ it('a single 100% slice splits into two half arcs (renderer-safe)', () => {+ const prims2 = chartPrimitives(chart({ kind: 'donut', labels: ['only'], series: [{ name: 'a', color: '#7630D7', values: [10] }] }))+ const arcs = ofKind(prims2, 'arc')+ expect(arcs).toHaveLength(2)+ expect((arcs[0] as { a1: number }).a1 - (arcs[0] as { a0: number }).a0).toBeCloseTo(Math.PI, 5)+ })++ it('value labels are percentages of the whole', () => {+ const prims3 = chartPrimitives(chart({ kind: 'donut', showValues: true }))+ const texts = ofKind(prims3, 'text').map((t) => t.text)+ expect(texts).toContain('26%') // 32/125+ expect(texts).toContain('10%') // 12/125+ })+})++// ── geometry: scatter ────────────────────────────────────────++describe('chartPrimitives — scatter', () => {+ it('one dot per (x,y) pair with numeric axes', () => {+ const prims = chartPrimitives(chart({ kind: 'scatter' }))+ expect(ofKind(prims, 'circle')).toHaveLength(8)+ const texts = ofKind(prims, 'text').map((t) => t.text)+ expect(texts.some((t) => /^-?\d+(\.\d+)?$/.test(t))).toBe(true)+ })++ it('scales to the data range (non-zero origin allowed)', () => {+ const prims = chartPrimitives(chart({+ kind: 'scatter',+ series: [{ name: 'a', color: '#02C0CC', values: [100, 100, 200, 200, 300, 300] }],+ }))+ const xs = ofKind(prims, 'circle').map((c) => (c as { cx: number }).cx)+ expect(Math.min(...xs)).toBeGreaterThan(0)+ expectAllFinite(prims)+ })+})++// ── degenerate + honest states ───────────────────────────────++describe('chartPrimitives — honest degradation', () => {+ it('empty series/labels → a visible "No data" hint, no crash', () => {+ for (const kind of ['bar', 'line', 'donut', 'scatter'] as const) {+ const prims = chartPrimitives(chart({ kind, labels: [], series: [] as ChartSeries[] }))+ expect(ofKind(prims, 'text').some((t) => t.text === 'No data')).toBe(true)+ expectAllFinite(prims)+ }+ })++ it('tiny elements degrade instead of drawing unreadable geometry', () => {+ const prims = chartPrimitives(chart({ kind: 'bar', width: 30, height: 30 }))+ expect(ofKind(prims, 'text').some((t) => t.text === 'No data')).toBe(true)+ })++ it('transparent fill skips the background rect', () => {+ const prims = chartPrimitives(chart({ fill: 'transparent', showLegend: false }))+ expect(ofKind(prims, 'rect')).toHaveLength(8) // bars only+ })+})diff --git a/src/lib/chart-geometry.ts b/src/lib/chart-geometry.tsnew file mode 100644index 0000000..59a633e--- /dev/null+++ b/src/lib/chart-geometry.ts@@ -0,0 +1,536 @@+// ─────────────────────────────────────────────────────────────+// chart-geometry (v0.14, D7) — the ONE pure layout module for the+// data-bound chart element.+//+// chartPrimitives(element) turns a ChartElement into a flat list of+// vector primitives in ELEMENT-LOCAL coordinates (origin = element+// top-left; adapters add x/y/rotation/opacity). Three thin adapters+// map the same list:+//+// editor src/components/editor/canvas/chart-node.tsx (react-konva)+// video export src/lib/video-export.ts buildKonvaNode (Konva)+// SVG export src/lib/svg-export.ts serializeElement (SVG strings)+//+// → geometric parity across all three renderers BY CONSTRUCTION.+//+// Text handling: primitives carry a baseline `y` + anchor+// ('start' | 'middle' | 'end'). SVG maps that to text-anchor; the+// Konva adapters center/right-align inside a wide box offset from the+// anchor so both renderers agree without measuring text. The Konva+// box top = baseline − 0.78 × size (documented approximation of the+// Inter ascent — labels sit within a pixel of the SVG rendering).+//+// Documented approximations (same spirit as image-filters.ts):+// • donut renders the FIRST series — multi-ring donuts are out of+// scope for v1; the data editor says so+// • stacked bars run two cursors: positives stack up from zero,+// negatives stack down from zero+// • smooth lines are Catmull-Rom splines sampled HERE (16 points+// per segment), not by the renderer — every renderer draws+// identical pixels+// • scatter ignores showValues (per-point labels are noise);+// bar/line/donut honor it+// ─────────────────────────────────────────────────────────────++import type { ChartElement, ChartKind, ChartSeries } from '@/lib/types'++// ── caps (every untrusted boundary enforces these) ───────────++export const MAX_CHART_SERIES = 6+export const MAX_CHART_LABELS = 24+/** scatter values are flat [x,y,…] pairs — 24 points max */+export const MAX_CHART_SCATTER_NUMBERS = 48+export const CHART_VALUE_LIMIT = 1e9++/** fallback series colors (also the MCP/paste fallback) */+export const CHART_PALETTE = ['#7630D7', '#02C0CC', '#FF5C8A', '#FFD166', '#22C55E', '#3B82F6'] as const++export function isChartKind(v: unknown): v is ChartKind {+ return v === 'bar' || v === 'line' || v === 'donut' || v === 'scatter'+}++/** donut hole ratio 0–0.85, junk → 0.62 */+export function clampChartHole(v: unknown): number {+ const n = typeof v === 'number' && Number.isFinite(v) ? v : 0.62+ return Math.min(0.85, Math.max(0, n))+}++/** labels: strings only, ≤ MAX_CHART_LABELS, each ≤ 24 chars */+export function sanitizeChartLabels(raw: unknown): string[] {+ if (!Array.isArray(raw)) return []+ return raw+ .filter((l): l is string => typeof l === 'string')+ .slice(0, MAX_CHART_LABELS)+ .map((l) => l.slice(0, 24))+}++function hexColor(v: unknown, fallback: string): string {+ return typeof v === 'string' && /^#[0-9a-fA-F]{3,8}$/.test(v) ? v : fallback+}++/**+ * Series from untrusted input (paste envelope, MCP patch): ≤ 6 series,+ * finite values clamped to ±1e9, ≤ 24 values per series (bar/line/donut)+ * or ≤ 48 flat numbers kept even-length (scatter). Never throws.+ */+export function sanitizeChartSeries(raw: unknown, scatter: boolean): ChartSeries[] {+ if (!Array.isArray(raw)) return []+ const out: ChartSeries[] = []+ for (const item of raw.slice(0, MAX_CHART_SERIES)) {+ if (!item || typeof item !== 'object') continue+ const s = item as Record<string, unknown>+ const name = typeof s.name === 'string' ? s.name.slice(0, 40) : `Series ${out.length + 1}`+ const color = hexColor(s.color, CHART_PALETTE[out.length % CHART_PALETTE.length])+ const values: number[] = []+ if (Array.isArray(s.values)) {+ for (const v of s.values.slice(0, scatter ? MAX_CHART_SCATTER_NUMBERS : MAX_CHART_LABELS)) {+ if (typeof v === 'number' && Number.isFinite(v)) {+ values.push(Math.max(-CHART_VALUE_LIMIT, Math.min(CHART_VALUE_LIMIT, v)))+ }+ }+ // scatter pairs must stay even-length+ if (scatter && values.length % 2 === 1) values.pop()+ }+ out.push({ name, color, values })+ }+ return out+}++// ── primitives ───────────────────────────────────────────────++export type ChartPrimitive =+ | { kind: 'rect'; x: number; y: number; w: number; h: number; r?: number; fill: string; stroke?: string; strokeWidth?: number }+ | { kind: 'line'; x1: number; y1: number; x2: number; y2: number; stroke: string; width: number; dash?: number[] }+ | { kind: 'polyline'; points: number[]; stroke: string; width: number }+ | { kind: 'circle'; cx: number; cy: number; r: number; fill: string; stroke?: string; strokeWidth?: number }+ | { kind: 'arc'; cx: number; cy: number; rIn: number; rOut: number; a0: number; a1: number; fill: string }+ | {+ kind: 'text'+ x: number+ /** baseline */+ y: number+ text: string+ size: number+ family: string+ fill: string+ bold?: boolean+ anchor: 'start' | 'middle' | 'end'+ }++// ── small pure helpers ───────────────────────────────────────++const GRID_COLOR = '#E4E6EB'+const AXIS_COLOR = '#D1D5DB'++/** compact human numbers: 1.2k / 3.4M / 2B / 12.5 */+export function formatChartNumber(v: number): string {+ const a = Math.abs(v)+ const trim = (n: number): string => String(Math.round(n * 10) / 10)+ if (a >= 1e9) return `${trim(v / 1e9)}B`+ if (a >= 1e6) return `${trim(v / 1e6)}M`+ if (a >= 1e4) return `${trim(v / 1e3)}k`+ if (a >= 100) return String(Math.round(v))+ if (Number.isInteger(v)) return String(v)+ return String(Math.round(v * 10) / 10)+}++/** truncate a label to fit `maxChars` (≥ 2) with an honest ellipsis */+function fitLabel(s: string, maxChars: number): string {+ if (maxChars < 2) return s.length ? `${s.slice(0, 1)}…` : ''+ return s.length > maxChars ? `${s.slice(0, maxChars - 1)}…` : s+}++interface TickScale {+ lo: number+ hi: number+ ticks: number[]+}++/** nice round ticks for a value range (1-2-5 decades); zero-span padded */+function niceScale(min: number, max: number, count: number, includeZero: boolean): TickScale {+ let lo = Number.isFinite(min) ? min : 0+ let hi = Number.isFinite(max) ? max : 1+ if (includeZero) {+ if (lo > 0) lo = 0+ if (hi < 0) hi = 0+ }+ if (hi - lo === 0 || !Number.isFinite(hi - lo)) {+ const pad = Math.max(1, Math.abs(hi) * 0.5)+ lo -= pad+ hi += pad+ }+ const rawStep = (hi - lo) / Math.max(1, count)+ const mag = Math.pow(10, Math.floor(Math.log10(rawStep)))+ const norm = rawStep / mag+ const step = (norm < 1.5 ? 1 : norm < 3 ? 2 : norm < 7 ? 5 : 10) * mag+ const tLo = Math.floor(lo / step) * step+ const tHi = Math.ceil(hi / step) * step+ const ticks: number[] = []+ for (let t = tLo; t <= tHi + step / 2; t += step) {+ ticks.push(Math.round(t * 1e6) / 1e6)+ if (ticks.length > 12) break+ }+ return { lo: tLo, hi: tHi, ticks }+}++/** uniform Catmull-Rom through pts, sampled `per` points per segment */+function catmullRomSampled(pts: { x: number; y: number }[], per = 16): number[] {+ if (pts.length < 3) return pts.flatMap((p) => [p.x, p.y])+ const out: number[] = [pts[0].x, pts[0].y]+ for (let i = 0; i < pts.length - 1; i += 1) {+ const p0 = pts[i - 1] ?? pts[i]+ const p1 = pts[i]+ const p2 = pts[i + 1]+ const p3 = pts[i + 2] ?? pts[i + 1]+ for (let s = 1; s <= per; s += 1) {+ const t = s / per+ const t2 = t * t+ const t3 = t2 * t+ const x = 0.5 * (2 * p1.x + (-p0.x + p2.x) * t + (2 * p0.x - 5 * p1.x + 4 * p2.x - p3.x) * t2 + (-p0.x + 3 * p1.x - 3 * p2.x + p3.x) * t3)+ const y = 0.5 * (2 * p1.y + (-p0.y + p2.y) * t + (2 * p0.y - 5 * p1.y + 4 * p2.y - p3.y) * t2 + (-p0.y + 3 * p1.y - 3 * p2.y + p3.y) * t3)+ out.push(x, y)+ }+ }+ return out+}++interface Point {+ x: number+ y: number+}++interface Plot {+ x: number+ y: number+ w: number+ h: number+}++// ── shared furniture: grid, axes, legend ─────────────────────++function legendPrimitives(el: ChartElement, cx: number, topY: number): ChartPrimitive[] {+ const out: ChartPrimitive[] = []+ if (!el.showLegend || el.series.length < 2) return out+ const size = Math.min(13, Math.max(9, el.fontSize))+ const chip = size * 0.72+ const gap = 14+ const items = el.series.map((s, i) => {+ const label = s.name || `Series ${i + 1}`+ return { label, color: s.color, w: label.length * size * 0.58 + chip + 6 }+ })+ const totalW = items.reduce((a, b) => a + b.w + gap, -gap)+ let lx = cx - totalW / 2+ const baseline = topY + size+ for (const it of items) {+ out.push({ kind: 'rect', x: lx, y: baseline - chip + 1, w: chip, h: chip, r: 3, fill: it.color })+ out.push({ kind: 'text', x: lx + chip + 6, y: baseline, text: it.label, size, family: el.fontFamily, fill: el.textColor, anchor: 'start' })+ lx += it.w + gap+ }+ return out+}++function yAxisPrimitives(el: ChartElement, plot: Plot, scale: TickScale): ChartPrimitive[] {+ const out: ChartPrimitive[] = []+ const span = scale.hi - scale.lo || 1+ const py = (v: number): number => plot.y + plot.h * (1 - (v - scale.lo) / span)+ for (const t of scale.ticks) {+ const y = py(t)+ if (el.showGrid) {+ out.push({ kind: 'line', x1: plot.x, y1: y, x2: plot.x + plot.w, y2: y, stroke: GRID_COLOR, width: 1 })+ }+ out.push({+ kind: 'text',+ x: plot.x - 8,+ y: y + el.fontSize * 0.36,+ text: formatChartNumber(t),+ size: el.fontSize,+ family: el.fontFamily,+ fill: el.textColor,+ anchor: 'end',+ })+ }+ out.push({ kind: 'line', x1: plot.x, y1: plot.y, x2: plot.x, y2: plot.y + plot.h, stroke: AXIS_COLOR, width: 1 })+ return out+}++function noDataPrimitives(el: ChartElement): ChartPrimitive[] {+ return [+ {+ kind: 'text',+ x: el.width / 2,+ y: el.height / 2 + el.fontSize * 0.36,+ text: 'No data',+ size: Math.max(12, el.fontSize),+ family: el.fontFamily,+ fill: el.textColor,+ anchor: 'middle',+ },+ ]+}++// ── per-kind geometry (all element-local) ────────────────────++function barPrimitives(el: ChartElement): ChartPrimitive[] {+ const out: ChartPrimitive[] = []+ if (!el.series.length || !el.labels.length) return noDataPrimitives(el)+ const legendH = el.showLegend && el.series.length > 1 ? el.fontSize + 18 : 0+ const scale = barScale(el)+ const labelW = Math.max(...scale.ticks.map((t) => formatChartNumber(t).length), 1) * el.fontSize * 0.6 + 6+ const plot: Plot = {+ x: labelW + 8,+ y: 8,+ w: el.width - labelW - 18,+ h: el.height - 16 - el.fontSize - 12 - legendH,+ }+ if (plot.w < 40 || plot.h < 40) return noDataPrimitives(el)+ out.push(...yAxisPrimitives(el, plot, scale))+ const span = scale.hi - scale.lo || 1+ const py = (v: number): number => plot.y + plot.h * (1 - (v - scale.lo) / span)+ const zeroY = py(Math.min(Math.max(0, scale.lo), scale.hi))+ out.push({ kind: 'line', x1: plot.x, y1: zeroY, x2: plot.x + plot.w, y2: zeroY, stroke: AXIS_COLOR, width: 1.5 })++ const n = el.labels.length+ const bandW = plot.w / n+ const maxChars = Math.max(2, Math.floor(bandW / (el.fontSize * 0.55)))+ const valueSize = Math.max(9, Math.min(el.fontSize, 13))++ if (el.barMode === 'stack') {+ const seriesW = Math.min(bandW * 0.6, 120)+ for (let b = 0; b < n; b += 1) {+ const bx = plot.x + b * bandW + (bandW - seriesW) / 2+ const barW = Math.max(2, seriesW - 1)+ let pos = 0+ let neg = 0+ for (const s of el.series) {+ const v = s.values[b] ?? 0+ if (!v) continue+ const y0 = v > 0 ? py(pos) : py(neg)+ const y1 = v > 0 ? py(pos + v) : py(neg + v)+ out.push({ kind: 'rect', x: bx, y: Math.min(y0, y1), w: barW, h: Math.max(1, Math.abs(y1 - y0)), r: Math.min(3, barW / 2), fill: s.color })+ if (v > 0) pos += v+ else neg += v+ }+ const topY = Math.min(py(pos), py(neg))+ if (el.showValues) {+ out.push({ kind: 'text', x: bx + barW / 2, y: topY - 5, text: formatChartNumber(pos + neg), size: valueSize, family: el.fontFamily, fill: el.textColor, anchor: 'middle' })+ }+ out.push({ kind: 'text', x: bx + seriesW / 2, y: plot.y + plot.h + el.fontSize, text: fitLabel(el.labels[b], maxChars), size: el.fontSize, family: el.fontFamily, fill: el.textColor, anchor: 'middle' })+ }+ } else {+ const seriesW = bandW * 0.68+ const barW = Math.max(2, seriesW / el.series.length - 1)+ for (let b = 0; b < n; b += 1) {+ const bandX = plot.x + b * bandW + (bandW - seriesW) / 2+ el.series.forEach((s, si) => {+ const v = s.values[b] ?? 0+ const bx = bandX + si * (seriesW / el.series.length)+ const y1 = py(v)+ out.push({ kind: 'rect', x: bx, y: Math.min(y1, zeroY), w: barW, h: Math.max(1, Math.abs(y1 - zeroY)), r: Math.min(4, barW / 2), fill: s.color })+ if (el.showValues) {+ out.push({ kind: 'text', x: bx + barW / 2, y: Math.min(y1, zeroY) - 5, text: formatChartNumber(v), size: valueSize, family: el.fontFamily, fill: el.textColor, anchor: 'middle' })+ }+ })+ out.push({ kind: 'text', x: bandX + seriesW / 2, y: plot.y + plot.h + el.fontSize, text: fitLabel(el.labels[b], maxChars), size: el.fontSize, family: el.fontFamily, fill: el.textColor, anchor: 'middle' })+ }+ }+ out.push(...legendPrimitives(el, el.width / 2, plot.y + plot.h + el.fontSize + 10))+ return out+}++function barScale(el: ChartElement): TickScale {+ let min = Infinity+ let max = -Infinity+ for (const s of el.series) for (const v of s.values) {+ if (!Number.isFinite(v)) continue+ min = Math.min(min, v)+ max = Math.max(max, v)+ }+ if (!Number.isFinite(min) || !Number.isFinite(max)) return niceScale(0, 1, 4, true)+ return niceScale(min, max, 4, true)+}++function linePrimitives(el: ChartElement): ChartPrimitive[] {+ const out: ChartPrimitive[] = []+ if (!el.series.length || el.labels.length < 2) return noDataPrimitives(el)+ const scale = barScale(el)+ const legendH = el.showLegend && el.series.length > 1 ? el.fontSize + 18 : 0+ const labelW = Math.max(...scale.ticks.map((t) => formatChartNumber(t).length), 1) * el.fontSize * 0.6 + 6+ const plot: Plot = {+ x: labelW + 8,+ y: 10,+ w: el.width - labelW - 18,+ h: el.height - 18 - el.fontSize - 12 - legendH,+ }+ if (plot.w < 40 || plot.h < 40 || el.labels.length < 2) return noDataPrimitives(el)+ out.push(...yAxisPrimitives(el, plot, scale))+ out.push({ kind: 'line', x1: plot.x, y1: plot.y + plot.h, x2: plot.x + plot.w, y2: plot.y + plot.h, stroke: AXIS_COLOR, width: 1.5 })++ const count = el.labels.length+ const stepX = plot.w / Math.max(1, count - 1)+ const span = scale.hi - scale.lo || 1+ const py = (v: number): number => plot.y + plot.h * (1 - (v - scale.lo) / span)+ const maxChars = Math.max(2, Math.floor((stepX + 4) / (el.fontSize * 0.55)))+ const valueSize = Math.max(9, Math.min(el.fontSize, 13))++ el.series.forEach((s) => {+ const pts: (Point & { v: number })[] = []+ for (let i = 0; i < count; i += 1) {+ const v = s.values[i]+ if (typeof v !== 'number' || !Number.isFinite(v)) continue+ pts.push({ x: plot.x + i * stepX, y: py(v), v })+ }+ if (pts.length === 0) return+ const flat = el.smooth && pts.length > 2 ? catmullRomSampled(pts) : pts.flatMap((p) => [p.x, p.y])+ out.push({ kind: 'polyline', points: flat, stroke: s.color, width: 3 })+ const dotR = count > 16 ? 2.5 : count > 10 ? 3.5 : 4.5+ for (const p of pts) {+ out.push({ kind: 'circle', cx: p.x, cy: p.y, r: dotR, fill: '#FFFFFF', stroke: s.color, strokeWidth: 2 })+ if (el.showValues) {+ out.push({ kind: 'text', x: p.x, y: p.y - dotR - 5, text: formatChartNumber(p.v), size: valueSize, family: el.fontFamily, fill: el.textColor, anchor: 'middle' })+ }+ }+ })++ for (let i = 0; i < count; i += 1) {+ out.push({ kind: 'text', x: plot.x + i * stepX, y: plot.y + plot.h + el.fontSize, text: fitLabel(el.labels[i], maxChars), size: el.fontSize, family: el.fontFamily, fill: el.textColor, anchor: 'middle' })+ }+ out.push(...legendPrimitives(el, el.width / 2, plot.y + plot.h + el.fontSize + 10))+ return out+}++function donutPrimitives(el: ChartElement): ChartPrimitive[] {+ const out: ChartPrimitive[] = []+ const s = el.series[0]+ if (!s || !el.labels.length) return noDataPrimitives(el)+ const legendH = el.showLegend && el.series.length > 1 ? el.fontSize + 18 : 0+ const cx = el.width / 2+ const cy = (el.height - legendH) / 2+ const rOut = Math.max(10, Math.min(cx, cy) - 10)+ const rIn = rOut * clampChartHole(el.hole)+ const weights = el.labels.map((_, i) => Math.max(0, s.values[i] ?? 0))+ const total = weights.reduce((a, b) => a + b, 0)+ if (total <= 0) return noDataPrimitives(el)++ let a = -Math.PI / 2+ const labelR = (rIn + rOut) / 2+ for (let i = 0; i < weights.length; i += 1) {+ const w = weights[i]+ if (w <= 0) continue+ const sweep = (w / total) * Math.PI * 2+ const a0 = a+ const a1 = a + sweep+ if (sweep >= Math.PI * 2 - 1e-6) {+ // a single 100% slice — two half arcs so every renderer closes it+ out.push({ kind: 'arc', cx, cy, rIn, rOut, a0, a1: a0 + sweep / 2, fill: s.color })+ out.push({ kind: 'arc', cx, cy, rIn, rOut, a0: a0 + sweep / 2, a1, fill: s.color })+ } else {+ out.push({ kind: 'arc', cx, cy, rIn, rOut, a0, a1, fill: s.color })+ }+ if (el.showValues && rOut - rIn > 18) {+ const mid = a0 + sweep / 2+ const pct = Math.round((w / total) * 100)+ out.push({+ kind: 'text',+ x: cx + Math.cos(mid) * labelR,+ y: cy + Math.sin(mid) * labelR + el.fontSize * 0.36,+ text: `${pct}%`,+ size: el.fontSize,+ family: el.fontFamily,+ fill: '#FFFFFF',+ bold: true,+ anchor: 'middle',+ })+ }+ a = a1+ }+ // centre total+ out.push({+ kind: 'text',+ x: cx,+ y: cy + el.fontSize * 0.5,+ text: formatChartNumber(total),+ size: Math.max(14, Math.round(el.fontSize * 1.7)),+ family: el.fontFamily,+ fill: el.textColor,+ bold: true,+ anchor: 'middle',+ })+ out.push(...legendPrimitives(el, el.width / 2, el.height - legendH + 6))+ return out+}++function scatterPrimitives(el: ChartElement): ChartPrimitive[] {+ const out: ChartPrimitive[] = []+ const pts = scatterPoints(el)+ if (!pts.length) return noDataPrimitives(el)+ const xs = pts.map((p) => p.x)+ const ys = pts.map((p) => p.y)+ const xScale = niceScale(Math.min(...xs), Math.max(...xs), 4, false)+ const yScale = niceScale(Math.min(...ys), Math.max(...ys), 4, false)+ const legendH = el.showLegend && el.series.length > 1 ? el.fontSize + 18 : 0+ const labelW = Math.max(...yScale.ticks.map((t) => formatChartNumber(t).length), 1) * el.fontSize * 0.6 + 6+ const plot: Plot = {+ x: labelW + 8,+ y: 10,+ w: el.width - labelW - 18,+ h: el.height - 18 - el.fontSize - 12 - legendH,+ }+ if (plot.w < 40 || plot.h < 40) return noDataPrimitives(el)+ const px = (v: number): number => plot.x + ((v - xScale.lo) / (xScale.hi - xScale.lo || 1)) * plot.w+ const py = (v: number): number => plot.y + plot.h * (1 - (v - yScale.lo) / (yScale.hi - yScale.lo || 1))++ out.push(...yAxisPrimitives(el, plot, yScale))+ if (el.showGrid) {+ for (const t of xScale.ticks) {+ out.push({ kind: 'line', x1: px(t), y1: plot.y, x2: px(t), y2: plot.y + plot.h, stroke: GRID_COLOR, width: 1 })+ }+ }+ out.push({ kind: 'line', x1: plot.x, y1: plot.y + plot.h, x2: plot.x + plot.w, y2: plot.y + plot.h, stroke: AXIS_COLOR, width: 1.5 })+ out.push({ kind: 'line', x1: plot.x, y1: plot.y, x2: plot.x, y2: plot.y + plot.h, stroke: AXIS_COLOR, width: 1.5 })++ for (const t of xScale.ticks) {+ out.push({ kind: 'text', x: px(t), y: plot.y + plot.h + el.fontSize, text: formatChartNumber(t), size: el.fontSize, family: el.fontFamily, fill: el.textColor, anchor: 'middle' })+ }+ const dotR = pts.length > 40 ? 3.5 : 5+ for (const p of pts) {+ out.push({ kind: 'circle', cx: px(p.x), cy: py(p.y), r: dotR, fill: p.color, stroke: '#FFFFFF', strokeWidth: 1.5 })+ }+ out.push(...legendPrimitives(el, el.width / 2, plot.y + plot.h + el.fontSize + 10))+ return out+}++interface ScatterPoint extends Point {+ color: string+}++function scatterPoints(el: ChartElement): ScatterPoint[] {+ const out: ScatterPoint[] = []+ for (const s of el.series) {+ for (let i = 0; i + 1 < s.values.length; i += 2) {+ const x = s.values[i]+ const y = s.values[i + 1]+ if (Number.isFinite(x) && Number.isFinite(y)) out.push({ x, y, color: s.color })+ }+ }+ return out.slice(0, MAX_CHART_SCATTER_NUMBERS)+}++// ── the public entry ─────────────────────────────────────────++/** Full geometry for a chart element, element-local coordinates. */+export function chartPrimitives(el: ChartElement): ChartPrimitive[] {+ const out: ChartPrimitive[] = []+ if (el.fill !== 'transparent') {+ out.push({ kind: 'rect', x: 0, y: 0, w: el.width, h: el.height, r: 12, fill: el.fill })+ }+ const body: ChartPrimitive[] =+ el.kind === 'donut'+ ? donutPrimitives(el)+ : el.kind === 'line'+ ? linePrimitives(el)+ : el.kind === 'scatter'+ ? scatterPrimitives(el)+ : barPrimitives(el)+ out.push(...body)+ return out+}diff --git a/src/lib/clipboard/system-clipboard.test.ts b/src/lib/clipboard/system-clipboard.test.tsindex a6dbc3b..ba3de1b 100644--- a/src/lib/clipboard/system-clipboard.test.ts+++ b/src/lib/clipboard/system-clipboard.test.ts@@ -52,6 +52,20 @@ function imageEl(overrides: Record<string, unknown> = {}) {}}+function chartEl(overrides: Record<string, unknown> = {}) {+ return {+ type: 'chart',+ x: 40,+ y: 40,+ width: 560,+ height: 360,+ kind: 'bar',+ labels: ['Q1', 'Q2'],+ series: [{ name: 'Revenue', color: '#7630D7', values: [10, 20] }],+ ...overrides,+ }+}+describe('envelope round-trip', () => {it('serialize → parse survives with identical content', () => {const els = [textEl() as unknown as AnyElement]@@ -136,6 +150,49 @@ describe('sanitizePastedElements — the untrusted-input gauntlet', () => {expect(rec.filterIntensity).toBe(0) // -20 clamps to 0, not 100 (finite input is clamped, not defaulted)})+ it('v0.14 (D7): chart fields survive a paste whitelisted + capped', () => {+ const out = sanitizePastedElements([chartEl({ hole: 0.7, barMode: 'stack' })])+ const rec = out[0] as unknown as Record<string, unknown>+ expect(rec.kind).toBe('bar')+ expect(rec.labels).toEqual(['Q1', 'Q2'])+ expect(rec.series).toEqual([{ name: 'Revenue', color: '#7630D7', values: [10, 20] }])+ expect(rec.hole).toBe(0.7)+ expect(rec.barMode).toBe('stack')+ })++ it('v0.14 (D7): hostile chart payloads reset to safe defaults', () => {+ const out = sanitizePastedElements([+ chartEl({+ kind: 'EVIL',+ labels: ['ok', 7, 'x'.repeat(60)],+ series: [+ { name: 'a', color: 'javascript:alert(1)', values: [1, 'x', 2e12] },+ 'junk',+ null,+ ],+ barMode: 'diagonal',+ hole: 5,+ showValues: 'yes',+ }),+ ])+ const rec = out[0] as unknown as Record<string, unknown>+ expect(rec.kind).toBe('bar') // junk kind falls back, never reaches the geometry switch+ expect(rec.labels).toEqual(['ok', 'x'.repeat(24)])+ expect(rec.series).toEqual([{ name: 'a', color: '#7630D7', values: [1, 1e9] }])+ expect(rec.barMode).toBe('group')+ expect(rec.hole).toBe(0.85)+ expect(rec.showValues).toBe(false)+ })++ it('v0.14 (D7): scatter pastes keep even-length pair arrays', () => {+ const out = sanitizePastedElements([+ chartEl({ kind: 'scatter', labels: ['drop', 'me'], series: [{ name: 'p', color: '#02C0CC', values: [1, 2, 3, 4, 5] }] }),+ ])+ const rec = out[0] as unknown as Record<string, unknown>+ expect(rec.labels).toEqual(['drop', 'me']) // labels are kept: harmless for scatter, preserved for kind round-trips+ expect(rec.series).toEqual([{ name: 'p', color: '#02C0CC', values: [1, 2, 3, 4] }]) // odd length trimmed+ })+it('caps the element count', () => {const many = Array.from({ length: MAX_PASTE_ELEMENTS + 200 }, () => textEl({ id: 'x' }))expect(sanitizePastedElements(many)).toHaveLength(MAX_PASTE_ELEMENTS)diff --git a/src/lib/clipboard/system-clipboard.ts b/src/lib/clipboard/system-clipboard.tsindex 907c605..30802ee 100644--- a/src/lib/clipboard/system-clipboard.ts+++ b/src/lib/clipboard/system-clipboard.ts@@ -18,12 +18,13 @@import type { AnyElement, ElementType } from '@/lib/types'import { isImageFilterId, clampFilterIntensity } from '@/lib/image-filters'+import { isChartKind, clampChartHole, sanitizeChartLabels, sanitizeChartSeries } from '@/lib/chart-geometry'export const CANVIX_MIME = 'application/x-canvix'const KNOWN_TYPES: ReadonlySet<string> = new Set(['text', 'rect', 'ellipse', 'triangle', 'star', 'line', 'path', 'stroke',- 'image', 'sticker', 'group', 'table', 'frame', 'embed', 'audio', 'video', 'plugin',+ 'image', 'sticker', 'group', 'table', 'frame', 'embed', 'audio', 'video', 'plugin', 'chart',])export const MAX_PASTE_ELEMENTS = 50@@ -111,6 +112,21 @@ export function sanitizePastedElements(raw: unknown): AnyElement[] {s.filter = isImageFilterId(s.filter) ? s.filter : 'none's.filterIntensity = clampFilterIntensity(s.filterIntensity)}+ // v0.14 (D7): chart fields are whitelisted + capped — a pasted+ // 'EVIL' kind or a 60-series payload never enters the store+ if (s.type === 'chart') {+ const kind = isChartKind(s.kind) ? s.kind : 'bar'+ const scatter = kind === 'scatter'+ s.kind = kind+ s.labels = sanitizeChartLabels(s.labels)+ s.series = sanitizeChartSeries(s.series, scatter)+ s.barMode = s.barMode === 'stack' ? 'stack' : 'group'+ s.hole = clampChartHole(s.hole)+ s.smooth = s.smooth !== false+ s.showGrid = s.showGrid !== false+ s.showValues = s.showValues === true+ s.showLegend = s.showLegend !== false+ }// groups carry children through the same gauntletif (s.type === 'group' && Array.isArray(s.children)) {s.children = sanitizePastedElements(s.children)diff --git a/src/lib/mcp/server.test.ts b/src/lib/mcp/server.test.tsindex 9c0bf89..8391f63 100644--- a/src/lib/mcp/server.test.ts+++ b/src/lib/mcp/server.test.ts@@ -40,7 +40,7 @@ describe('JSON-RPC id echo', () => {expect(Array.isArray(tools)).toBe(true)expect(tools.length).toBeGreaterThanOrEqual(20)const names = tools.map((t) => t.name)- for (const expected of ['create_design', 'add_text', 'add_shape', 'add_image', 'export_design']) {+ for (const expected of ['create_design', 'add_text', 'add_shape', 'add_image', 'add_chart', 'update_element', 'export_design']) {expect(names).toContain(expected)}for (const t of tools) {diff --git a/src/lib/mcp/server.ts b/src/lib/mcp/server.tsindex 48e5ab7..ecaabda 100644--- a/src/lib/mcp/server.ts+++ b/src/lib/mcp/server.ts@@ -148,7 +148,7 @@ export function handleInitialize(msg: JsonRpcRequest): JsonRpcResponse {},instructions:'Canvix is a self-hosted, open-source design tool. Every tool creates or edits REAL, editable designs: ' +- 'create/generate designs, add text/shapes/images/tables/embeds, restyle, animate, comment and export (svg/png/json). ' ++ 'create/generate designs, add text/shapes/images/tables/charts/embeds, restyle, animate, comment and export (svg/png/json). ' +'Start with get_capabilities, then list_templates / search_designs. Edits made here appear live to humans in the editor.',},}diff --git a/src/lib/mcp/tools.ts b/src/lib/mcp/tools.tsindex 6dc8ab5..61e8828 100644--- a/src/lib/mcp/tools.ts+++ b/src/lib/mcp/tools.ts@@ -18,10 +18,13 @@ import {createImageElement,createTableElement,createEmbedElement,+ createChartElement,createPage,type AnyElement,type PageData,+ type ChartKind,} from '@/lib/types'+import { isChartKind, sanitizeChartLabels, sanitizeChartSeries, clampChartHole, CHART_PALETTE } from '@/lib/chart-geometry'export const SERVER_VERSION = '0.6.1'@@ -196,6 +199,10 @@ function summarizeElement(el: AnyElement) {base.kind = el.kind} else if (el.type === 'frame') {base.hasImage = Boolean(el.src)+ } else if (el.type === 'chart') {+ base.kind = el.kind+ base.labels = el.labels.slice(0, 12)+ base.series = el.series.map((sr) => ({ name: sr.name, values: sr.values.slice(0, 12) }))}return base}@@ -208,6 +215,10 @@ function pageTextContent(page: PageData): string[] {if (el.type === 'text') out.push(el.text)if (el.type === 'table') out.push(...el.cells.map((c) => c.text).filter((t) => t.trim()))if (el.type === 'embed' && el.title) out.push(el.title)+ if (el.type === 'chart') {+ out.push(...el.labels.filter(Boolean))+ out.push(...el.series.map((sr) => sr.name).filter(Boolean))+ }if (el.type === 'group') {for (const c of el.children) {if (c.type === 'text' && c.visible) out.push(c.text)@@ -728,6 +739,102 @@ export function buildTools(deps: ToolDeps): ToolDef[] {},}+ const addChart: ToolDef = {+ name: 'add_chart',+ description:+ 'Add a native data-bound chart element (bar/line/donut/scatter) to a design page. Series data stays editable in the editor toolbar and via update_element. Scatter uses flat [x,y,...] point arrays and no labels; the other kinds take one value per label.',+ inputSchema: {+ type: 'object',+ properties: {+ design_id: { type: 'string' },+ page: { type: 'number', minimum: 0 },+ kind: { type: 'string', enum: ['bar', 'line', 'donut', 'scatter'] },+ x: { type: 'number' },+ y: { type: 'number' },+ width: { type: 'number' },+ height: { type: 'number' },+ labels: { type: 'array', items: { type: 'string' }, description: 'Category labels (bar/line/donut; omit for scatter)' },+ series: {+ type: 'array',+ items: {+ type: 'object',+ properties: {+ name: { type: 'string' },+ color: { type: 'string', description: 'hex colour, e.g. #7630D7' },+ values: { type: 'array', items: { type: 'number' } },+ },+ },+ description: 'Data series (max 6); values follow the kind shape. Omit for sensible sample data.',+ },+ bar_mode: { type: 'string', enum: ['group', 'stack'] },+ hole: { type: 'number', minimum: 0, maximum: 0.85, description: 'donut inner-radius ratio' },+ smooth: { type: 'boolean' },+ show_grid: { type: 'boolean' },+ show_values: { type: 'boolean' },+ show_legend: { type: 'boolean' },+ },+ required: ['design_id', 'kind'],+ },+ handler: async (args) => {+ const designId = asString(args.design_id)+ const kindRaw = asString(args.kind)+ if (!isChartKind(kindRaw)) return fail('kind must be one of bar | line | donut | scatter.')+ const kind = kindRaw as ChartKind+ const scatter = kind === 'scatter'+ let labels = args.labels !== undefined ? sanitizeChartLabels(args.labels) : []+ let seriesIn = args.series !== undefined ? sanitizeChartSeries(args.series, scatter) : []+ // friendly completion: labels without series → one sample series;+ // series without labels → Item N categories (non-scatter kinds)+ if (!scatter && labels.length > 0 && seriesIn.length === 0) {+ seriesIn = [{ name: 'Series 1', color: CHART_PALETTE[0], values: labels.map((_, i) => 20 + i * 5) }]+ }+ if (!scatter && labels.length === 0 && seriesIn.length > 0) {+ const n = Math.max(1, ...seriesIn.map((sr) => sr.values.length))+ labels = Array.from({ length: n }, (_, i) => `Item ${i + 1}`)+ }+ const hasData = seriesIn.length > 0 && (scatter || labels.length > 0)+ return mutateDesign(designId, (pages, w, h) => {+ const pageIndex = clamp(asInt(args.page, 0), 0, pages.length - 1)+ const page = pageAt(pages, pageIndex)+ if (!page) return null+ const chartW = clamp(asNumber(args.width, kind === 'donut' ? 380 : 560), 120, w)+ const chartH = clamp(asNumber(args.height, kind === 'donut' ? 380 : 360), 120, h)+ const el = createChartElement(kind, {+ x: clamp(asNumber(args.x, (w - chartW) / 2), -w, w),+ y: clamp(asNumber(args.y, h * 0.3), -h, h),+ width: chartW,+ height: chartH,+ ...(hasData+ ? {+ labels,+ series: seriesIn.map((sr, i) => ({+ ...sr,+ color: /^#[0-9a-fA-F]{3,8}$/.test(sr.color) ? sr.color : CHART_PALETTE[i % CHART_PALETTE.length],+ })),+ }+ : {}),+ ...(args.bar_mode !== undefined ? { barMode: args.bar_mode === 'stack' ? ('stack' as const) : ('group' as const) } : {}),+ ...(args.hole !== undefined ? { hole: clampChartHole(args.hole) } : {}),+ ...(args.smooth !== undefined ? { smooth: args.smooth === true } : {}),+ ...(args.show_grid !== undefined ? { showGrid: args.show_grid === true } : {}),+ ...(args.show_values !== undefined ? { showValues: args.show_values === true } : {}),+ ...(args.show_legend !== undefined ? { showLegend: args.show_legend === true } : {}),+ })+ const next = pages.map((p, i) => (i === pageIndex ? { ...p, elements: [...p.elements, el] } : p))+ return {+ pages: next,+ summary: {+ added: `chart (${kind})`,+ element_id: el.id,+ page: pageIndex,+ labels: el.labels.length,+ series: el.series.map((sr) => sr.name),+ },+ }+ })+ },+ }+const addEmbed: ToolDef = {name: 'add_embed',description: 'Add an embed link card (YouTube / Google Maps / generic link) to a design page. The card is native vector content that opens the URL in previews and shared views.',@@ -1089,6 +1196,7 @@ export function buildTools(deps: ToolDeps): ToolDef[] {addShape,addImage,addTable,+ addChart,addEmbed,setBackground,updateElement,@@ -1110,6 +1218,7 @@ const IMAGE_KEYS = new Set([...COMMON_KEYS, 'src', 'radius', 'brightness', 'contconst TABLE_KEYS = new Set([...COMMON_KEYS, 'rows', 'cols', 'cells', 'colWidths', 'rowHeight', 'borderColor', 'borderWidth', 'headerFill', 'textColor', 'fontSize', 'fontFamily'])const FRAME_KEYS = new Set([...COMMON_KEYS, 'frameShape', 'src', 'radius'])const EMBED_KEYS = new Set([...COMMON_KEYS, 'url', 'title', 'tint'])+const CHART_KEYS = new Set([...COMMON_KEYS, 'kind', 'labels', 'series', 'barMode', 'hole', 'smooth', 'showGrid', 'showValues', 'showLegend', 'fill', 'textColor', 'fontSize'])function sanitizePatch(patch: Record<string, unknown>, el: AnyElement, pageW: number, pageH: number): Record<string, unknown> {const allowed =@@ -1118,6 +1227,7 @@ function sanitizePatch(patch: Record<string, unknown>, el: AnyElement, pageW: nu: el.type === 'table' ? TABLE_KEYS: el.type === 'frame' ? FRAME_KEYS: el.type === 'embed' ? EMBED_KEYS+ : el.type === 'chart' ? CHART_KEYS: el.type === 'line' ? new Set([...COMMON_KEYS, 'stroke', 'strokeWidth', 'dashed']): SHAPE_KEYS@@ -1177,6 +1287,26 @@ function sanitizePatch(patch: Record<string, unknown>, el: AnyElement, pageW: nucase 'url':out.url = isHttpsUrl(value) ? value : ((el as { url?: string }).url ?? '')break+ // v0.14 (D7): chart data patches — series/labels run the same+ // whitelisting as pastes; the effective kind decides the shape+ case 'kind': {+ if (isChartKind(value)) out.kind = value+ break+ }+ case 'labels':+ out.labels = sanitizeChartLabels(value)+ break+ case 'series': {+ const effective = (out.kind ?? (el as { kind?: unknown }).kind) === 'scatter'+ out.series = sanitizeChartSeries(value, effective)+ break+ }+ case 'barMode':+ out.barMode = value === 'stack' ? 'stack' : 'group'+ break+ case 'hole':+ out.hole = clampChartHole(value)+ breakcase 'fontFamily': {const f = asString(value, '')out.fontFamily = FONTS.some((x) => (typeof x === "string" ? x : x.family) === f) ? f : 'Inter'diff --git a/src/lib/svg-export.ts b/src/lib/svg-export.tsindex bbf1836..dd0f6bc 100644--- a/src/lib/svg-export.ts+++ b/src/lib/svg-export.ts@@ -14,6 +14,7 @@import type {AnyElement,+ ChartElement,EmbedElement,FrameElement,GradientFill,@@ -28,6 +29,7 @@ import type {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 type { PluginElement } from '@/lib/types'import { getRenderEntry, renderKey } from '@/lib/plugins/renderer-cache'@@ -528,6 +530,49 @@ ${filt.overlay}` : imagereturn `${open}\n${content}\n </g>`}+ case 'chart': {+ // v0.14 (D7): primitives → SVG. Geometry identical to the editor+ // and video export by construction (lib/chart-geometry.ts).+ const ch = el as ChartElement+ const f = (n: number): string => (Math.round(n * 10) / 10).toString()+ const parts: string[] = []+ for (const p of chartPrimitives(ch)) {+ switch (p.kind) {+ case 'rect':+ parts.push(` <rect x="${f(p.x)}" y="${f(p.y)}" width="${f(p.w)}" height="${f(p.h)}"${p.r ? ` rx="${f(p.r)}"` : ''} fill="${p.fill}"${p.stroke ? ` stroke="${p.stroke}" stroke-width="${f(p.strokeWidth ?? 1)}"` : ''} />`)+ break+ case 'line':+ parts.push(` <line x1="${f(p.x1)}" y1="${f(p.y1)}" x2="${f(p.x2)}" y2="${f(p.y2)}" stroke="${p.stroke}" stroke-width="${f(p.width)}"${p.dash ? ` stroke-dasharray="${p.dash.join(' ')}"` : ''} />`)+ break+ case 'polyline':+ parts.push(` <polyline points="${p.points.map(f).join(' ')}" fill="none" stroke="${p.stroke}" stroke-width="${f(p.width)}" stroke-linecap="round" stroke-linejoin="round" />`)+ break+ case 'circle':+ parts.push(` <circle cx="${f(p.cx)}" cy="${f(p.cy)}" r="${f(p.r)}" fill="${p.fill}"${p.stroke ? ` stroke="${p.stroke}" stroke-width="${f(p.strokeWidth ?? 1)}"` : ''} />`)+ break+ case 'arc': {+ // annular sector path (clockwise in the y-down system)+ const x0 = p.cx + p.rOut * Math.cos(p.a0)+ const y0 = p.cy + p.rOut * Math.sin(p.a0)+ const x1 = p.cx + p.rOut * Math.cos(p.a1)+ const y1 = p.cy + p.rOut * Math.sin(p.a1)+ const x2 = p.cx + p.rIn * Math.cos(p.a1)+ const y2 = p.cy + p.rIn * Math.sin(p.a1)+ const x3 = p.cx + p.rIn * Math.cos(p.a0)+ const y3 = p.cy + p.rIn * Math.sin(p.a0)+ const large = p.a1 - p.a0 > Math.PI ? 1 : 0+ parts.push(` <path d="M ${f(x0)} ${f(y0)} A ${f(p.rOut)} ${f(p.rOut)} 0 ${large} 1 ${f(x1)} ${f(y1)} L ${f(x2)} ${f(y2)} A ${f(p.rIn)} ${f(p.rIn)} 0 ${large} 0 ${f(x3)} ${f(y3)} Z" fill="${p.fill}" />`)+ break+ }+ case 'text':+ parts.push(` <text x="${f(p.x)}" y="${f(p.y)}" font-family="${esc(p.family)}" font-size="${f(p.size)}"${p.bold ? ' font-weight="700"' : ''} fill="${p.fill}" text-anchor="${p.anchor}">${esc(p.text)}</text>`)+ break+ }+ }+ const transform = `translate(${ch.x} ${ch.y})${ch.rotation ? ` rotate(${ch.rotation})` : ''}`+ return `<g transform="${transform}"${opacityAttr(ch)}${shadowAttrs(ch, ctx)}>\n${parts.join('\n')}\n </g>`+ }+case 'embed': {const em = el as EmbedElementconst { bandH, iconR } = embedLayout(em.width, em.height)diff --git a/src/lib/types.ts b/src/lib/types.tsindex 674290f..cc8daa3 100644--- a/src/lib/types.ts+++ b/src/lib/types.ts@@ -20,6 +20,7 @@ export type ElementType =| 'audio'| 'video'| 'plugin'+ | 'chart'export type TextAlign = 'left' | 'center' | 'right' | 'justify'@@ -276,6 +277,54 @@ export interface EmbedElement extends BaseElement {tint: string}+// ── v0.14 D7: data-bound charts ───────────────────────────────++export const CHART_KINDS = ['bar', 'line', 'donut', 'scatter'] as const+export type ChartKind = (typeof CHART_KINDS)[number]++export const CHART_KIND_LABELS: Record<ChartKind, string> = {+ bar: 'Bar chart',+ line: 'Line chart',+ donut: 'Donut chart',+ scatter: 'Scatter chart',+}++/** One data series. `values` holds one number per `labels` entry+ * (bar/line/donut); scatter stores flat [x0,y0,x1,y1,…] pairs instead+ * (labels stays empty). Both shapes are capped + whitelisted on every+ * untrusted boundary (paste, MCP) — see lib/chart-geometry.ts. */+export interface ChartSeries {+ name: string+ color: string+ values: number[]+}++/** v0.14 (D7): native data-bound chart element — the geometry lives in+ * lib/chart-geometry.ts (one pure module; the editor, the video+ * exporter and the SVG exporter all map the same primitives). */+export interface ChartElement extends BaseElement {+ type: 'chart'+ kind: ChartKind+ /** category labels (bar/line/donut); scatter keeps this empty */+ labels: string[]+ series: ChartSeries[]+ /** bar layout: series side-by-side or stacked */+ barMode: 'group' | 'stack'+ /** donut inner-radius ratio 0–0.85 */+ hole: number+ /** line: Catmull-Rom smoothed segments */+ smooth: boolean+ showGrid: boolean+ /** numeric value labels on bars / dots / slices */+ showValues: boolean+ showLegend: boolean+ /** panel background ('transparent' allowed) */+ fill: string+ textColor: string+ fontFamily: string+ fontSize: number+}+// ── v0.11: audio/video elements + Beat Sync ──────────────────/** Hard caps keeping collab ops + saved documents small: the waveform and@@ -394,6 +443,7 @@ export type AnyElement =| AudioElement| VideoElement| PluginElement+ | ChartElementexport type Background =| { type: 'solid'; color: string }@@ -699,6 +749,72 @@ export function detectEmbedKind(url: string): EmbedKind {}}+/** v0.14 (D7): chart factory — seeds real-looking sample data per kind so+ * the canvas never shows an empty shell; every field stays editable. */+export function createChartElement(+ kind: ChartKind,+ init: BaseInit & Partial<ChartElement> = {}+): ChartElement {+ const effectiveKind = init.kind ?? kind+ const sample = sampleChartData(effectiveKind)+ return {+ ...baseElement('chart', { width: 560, height: 360, ...init }),+ type: 'chart',+ labels: sample.labels,+ series: sample.series,+ barMode: 'group',+ hole: 0.62,+ smooth: true,+ showGrid: true,+ showValues: false,+ showLegend: true,+ fill: '#FFFFFF',+ textColor: '#3A3F4B',+ fontFamily: 'Inter',+ fontSize: 13,+ ...init,+ kind: effectiveKind,+ }+}++/** Default per-kind sample data (also the MCP add_chart fallback). */+export function sampleChartData(kind: ChartKind): { labels: string[]; series: ChartSeries[] } {+ switch (kind) {+ case 'bar':+ return {+ labels: ['Q1', 'Q2', 'Q3', 'Q4'],+ series: [+ { name: 'Revenue', color: '#7630D7', values: [128, 155, 141, 190] },+ { name: 'Costs', color: '#02C0CC', values: [86, 92, 90, 104] },+ ],+ }+ case 'line':+ return {+ labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],+ series: [+ { name: 'Visitors', color: '#7630D7', values: [420, 510, 480, 610, 580, 690] },+ { name: 'Signups', color: '#FF5C8A', values: [120, 150, 140, 180, 175, 210] },+ ],+ }+ case 'donut':+ return {+ labels: ['Design', 'Code', 'Review', 'Test', 'Ship'],+ series: [{ name: 'Hours', color: '#7630D7', values: [32, 41, 18, 22, 12] }],+ }+ case 'scatter':+ return {+ labels: [],+ series: [+ {+ name: 'Cohort',+ color: '#02C0CC',+ values: [12, 34, 18, 52, 24, 47, 31, 66, 38, 58, 45, 74, 52, 81, 58, 77],+ },+ ],+ }+ }+}+/** v0.11: audio factory — media-store src + the analysis baked in at upload. */export function createAudioElement(src: string,@@ -849,3 +965,6 @@ export function isFrame(el: AnyElement): el is FrameElement {export function isEmbed(el: AnyElement): el is EmbedElement {return el.type === 'embed'}+export function isChart(el: AnyElement): el is ChartElement {+ return el.type === 'chart'+}diff --git a/src/lib/video-export.ts b/src/lib/video-export.tsindex 0a021fe..108388e 100644--- a/src/lib/video-export.ts+++ b/src/lib/video-export.ts@@ -12,8 +12,10 @@// ─────────────────────────────────────────────────────────────import Konva from 'konva'-import type { AnyElement, AudioElement, ImageElement, PageData, PluginElement, VideoElement } from '@/lib/types'+import type { AnyElement, AudioElement, ChartElement, EmbedElement, FrameElement, ImageElement, PageData, PluginElement, TableElement, VideoElement } from '@/lib/types'import { imageHasFilters, renderFilteredCanvas } from '@/lib/image-filters'+import { chartPrimitives } from '@/lib/chart-geometry'+import { embedLayout, hexPoints, hostOf, tableGeometry, youtubeThumbUrl } from '@/lib/v06-geometry'import { animateElementAt, pageHoldDuration } from '@/lib/animations'import { beatEnvelopeAt, beatSourceOf } from '@/lib/media/beat-detect'import { awaitRender, renderKey } from '@/lib/plugins/renderer-cache'@@ -107,7 +109,13 @@ async function collectImages(pages: PageData[]): Promise<Map<string, HTMLImageElfor (const el of els) {if (el.type === 'image') sources.push(el.src)else if (el.type === 'video') sources.push(el.poster) // v0.11: poster dataURL- else if (el.type === 'group') walk(el.children)+ else if (el.type === 'frame' && el.src) sources.push(el.src) // v0.14 D7 parity: frames render in video+ else if (el.type === 'embed') {+ // v0.14 D7 parity: youtube thumbs attempted via the CORS loader —+ // a blocked thumb degrades to the tinted band (same as SVG export)+ const t = el.kind === 'youtube' ? youtubeThumbUrl(el.url) : null+ if (t) sources.push(t)+ } else if (el.type === 'group') walk(el.children)}}for (const p of pages) walk(p.elements)@@ -144,6 +152,46 @@ async function collectImages(pages: PageData[]): Promise<Map<string, HTMLImageEl// ── Konva node builders (geometry mirrors element-node.tsx) ──+/** clip function for a frame shape (mirrors v06-nodes frameClip) */+function frameClipFunc(fr: FrameElement): (ctx: Konva.Context) => void {+ return (ctx: Konva.Context) => {+ const w = fr.width+ const h = fr.height+ if (fr.frameShape === 'ellipse' || fr.frameShape === 'circle') {+ const rx = fr.frameShape === 'circle' ? Math.min(w, h) / 2 : w / 2+ const ry = fr.frameShape === 'circle' ? Math.min(w, h) / 2 : h / 2+ ctx.beginPath()+ ctx.ellipse(w / 2, h / 2, rx, ry, 0, 0, Math.PI * 2, false)+ ctx.closePath()+ } else if (fr.frameShape === 'triangle') {+ ctx.beginPath()+ ctx.moveTo(0, h)+ ctx.lineTo(w / 2, 0)+ ctx.lineTo(w, h)+ ctx.closePath()+ } else if (fr.frameShape === 'hexagon') {+ const pts = hexPoints(w, h)+ ctx.beginPath()+ ctx.moveTo(pts[0][0], pts[0][1])+ for (let i = 1; i < pts.length; i += 1) ctx.lineTo(pts[i][0], pts[i][1])+ ctx.closePath()+ } else {+ const rr = Math.min(fr.radius, w / 2, h / 2)+ ctx.beginPath()+ ctx.moveTo(rr, 0)+ ctx.lineTo(w - rr, 0)+ ctx.quadraticCurveTo(w, 0, w, rr)+ ctx.lineTo(w, h - rr)+ ctx.quadraticCurveTo(w, h, w - rr, h)+ ctx.lineTo(rr, h)+ ctx.quadraticCurveTo(0, h, 0, h - rr)+ ctx.lineTo(0, rr)+ ctx.quadraticCurveTo(0, 0, rr, 0)+ ctx.closePath()+ }+ }+}+function buildKonvaNode(el: AnyElement, images: Map<string, HTMLImageElement>): Konva.Node {switch (el.type) {case 'text': {@@ -431,6 +479,197 @@ function buildKonvaNode(el: AnyElement, images: Map<string, HTMLImageElement>):group.add(play)return group}+ // ── v0.14 (D7): charts + the table/frame/embed parity fix ──+ // these previously fell through to the default (empty group) —+ // tables, frames and embed cards simply VANISHED from video+ // exports. Geometry mirrors the editor nodes (v06-nodes.tsx).++ case 'chart': {+ const ch = el as ChartElement+ const group = new Konva.Group({ id: ch.id, x: ch.x, y: ch.y, rotation: ch.rotation ?? 0, opacity: ch.opacity ?? 1 })+ for (const p of chartPrimitives(ch)) {+ switch (p.kind) {+ case 'rect':+ group.add(new Konva.Rect({ x: p.x, y: p.y, width: p.w, height: p.h, cornerRadius: p.r ?? 0, fill: p.fill, ...(p.stroke ? { stroke: p.stroke, strokeWidth: p.strokeWidth ?? 1 } : {}) }))+ break+ case 'line':+ group.add(new Konva.Line({ points: [p.x1, p.y1, p.x2, p.y2], stroke: p.stroke, strokeWidth: p.width, ...(p.dash ? { dash: p.dash } : {}), lineCap: 'round' }))+ break+ case 'polyline':+ group.add(new Konva.Line({ points: p.points, stroke: p.stroke, strokeWidth: p.width, lineCap: 'round', lineJoin: 'round' }))+ break+ case 'circle':+ group.add(new Konva.Circle({ x: p.cx, y: p.cy, radius: p.r, fill: p.fill, ...(p.stroke ? { stroke: p.stroke, strokeWidth: p.strokeWidth ?? 1 } : {}) }))+ break+ case 'arc':+ // Konva.Arc: sweep `angle` from `rotation` (degrees, 0 = 3 o'clock)+ group.add(new Konva.Arc({ x: p.cx, y: p.cy, innerRadius: p.rIn, outerRadius: p.rOut, angle: ((p.a1 - p.a0) * 180) / Math.PI, rotation: (p.a0 * 180) / Math.PI, fill: p.fill }))+ break+ case 'text': {+ const props: Record<string, unknown> = {+ y: p.y - p.size * 0.78,+ text: p.text,+ fontSize: p.size,+ fontFamily: p.family,+ fill: p.fill,+ fontStyle: p.bold ? '700' : '400',+ }+ if (p.anchor === 'middle') {+ props.x = p.x - 2000+ props.width = 4000+ props.align = 'center'+ } else if (p.anchor === 'end') {+ props.x = p.x - 1000+ props.width = 1000+ props.align = 'right'+ } else {+ props.x = p.x+ }+ group.add(new Konva.Text(props))+ break+ }+ }+ }+ return group+ }++ case 'table': {+ const tb = el as TableElement+ const group = new Konva.Group({ id: tb.id, x: tb.x, y: tb.y, rotation: tb.rotation ?? 0, opacity: tb.opacity ?? 1 })+ const geo = tableGeometry(tb)+ for (let idx = 0; idx < tb.rows * tb.cols; idx += 1) {+ const r = Math.floor(idx / tb.cols)+ const c = idx % tb.cols+ const cell = tb.cells[idx] ?? { text: '' }+ const isHeader = r === 0+ const cellFill = cell.fill ?? (isHeader ? tb.headerFill : tb.fill)+ group.add(+ new Konva.Rect({+ x: geo.colX[c],+ y: r * geo.rowH,+ width: geo.colW[c],+ height: geo.rowH,+ ...(cellFill !== 'transparent' ? { fill: cellFill } : {}),+ stroke: tb.borderColor,+ strokeWidth: tb.borderWidth,+ }),+ )+ if (cell.text) {+ group.add(+ new Konva.Text({+ x: geo.colX[c] + 10,+ y: r * geo.rowH,+ width: Math.max(8, geo.colW[c] - 20),+ height: geo.rowH,+ text: cell.text,+ fontSize: tb.fontSize,+ fontFamily: tb.fontFamily,+ fontStyle: cell.bold || isHeader ? 'bold' : 'normal',+ fill: isHeader ? (tb.headerTextColor ?? '#FFFFFF') : tb.textColor,+ verticalAlign: 'middle',+ wrap: 'none',+ ellipsis: true,+ }),+ )+ }+ }+ return group+ }++ case 'frame': {+ const fr = el as FrameElement+ const group = new Konva.Group({ id: fr.id, x: fr.x, y: fr.y, rotation: fr.rotation ?? 0, opacity: fr.opacity ?? 1 })+ const img = fr.src ? images.get(fr.src) : undefined+ if (img && fr.naturalWidth > 0 && fr.naturalHeight > 0) {+ const scale = Math.max(fr.width / fr.naturalWidth, fr.height / fr.naturalHeight)+ const dw = fr.naturalWidth * scale+ const dh = fr.naturalHeight * scale+ group.clipFunc(frameClipFunc(fr))+ group.add(new Konva.Image({ image: img, x: (fr.width - dw) / 2, y: (fr.height - dh) / 2, width: dw, height: dh }))+ } else {+ const stroke = 'rgba(255,255,255,0.85)'+ if (fr.frameShape === 'ellipse' || fr.frameShape === 'circle') {+ const rx = fr.frameShape === 'circle' ? Math.min(fr.width, fr.height) / 2 : fr.width / 2+ const ry = fr.frameShape === 'circle' ? Math.min(fr.width, fr.height) / 2 : fr.height / 2+ group.add(new Konva.Ellipse({ x: fr.width / 2, y: fr.height / 2, radiusX: rx, radiusY: ry, fill: fr.fill, fillOpacity: 0.16, stroke, strokeWidth: 2, dash: [8, 6] }))+ } else if (fr.frameShape === 'triangle') {+ group.add(new Konva.Line({ points: [0, fr.height, fr.width / 2, 0, fr.width, fr.height], closed: true, fill: fr.fill, fillOpacity: 0.16, stroke, strokeWidth: 2, dash: [8, 6] }))+ } else if (fr.frameShape === 'hexagon') {+ group.add(new Konva.Line({ points: hexPoints(fr.width, fr.height).flat(), closed: true, fill: fr.fill, fillOpacity: 0.16, stroke, strokeWidth: 2, dash: [8, 6] }))+ } else {+ group.add(new Konva.Rect({ width: fr.width, height: fr.height, cornerRadius: fr.radius, fill: fr.fill, fillOpacity: 0.16, stroke, strokeWidth: 2, dash: [8, 6] }))+ }+ }+ return group+ }++ case 'embed': {+ const em = el as EmbedElement+ const group = new Konva.Group({ id: em.id, x: em.x, y: em.y, rotation: em.rotation ?? 0, opacity: em.opacity ?? 1 })+ const { bandH, iconR } = embedLayout(em.width, em.height)+ const cx = em.width / 2+ const cy = bandH / 2+ group.add(new Konva.Rect({ width: em.width, height: em.height, cornerRadius: 14, fill: '#15171C' }))+ const thumbUrl = em.kind === 'youtube' ? youtubeThumbUrl(em.url) : null+ const thumb = thumbUrl ? images.get(thumbUrl) : undefined+ if (thumb) {+ group.add(new Konva.Image({ image: thumb, y: 0, width: em.width, height: bandH, crop: { x: 45, y: 0, width: 270, height: 157 } }))+ } else {+ group.add(new Konva.Rect({ y: 0, width: em.width, height: bandH, cornerRadius: [14, 14, 0, 0], fill: em.tint, opacity: 0.28 }))+ }+ if (em.kind === 'youtube') {+ group.add(new Konva.Ellipse({ x: cx, y: cy, radiusX: iconR, radiusY: iconR, fill: 'rgba(255,255,255,0.92)' }))+ group.add(new Konva.Line({ points: [cx - iconR * 0.32, cy - iconR * 0.42, cx - iconR * 0.32, cy + iconR * 0.42, cx + iconR * 0.46, cy], closed: true, fill: '#FF0033' }))+ } else if (em.kind === 'map') {+ group.add(new Konva.Ellipse({ x: cx, y: cy, radiusX: iconR, radiusY: iconR, fill: 'rgba(255,255,255,0.95)' }))+ group.add(new Konva.Ellipse({ x: cx, y: cy - iconR * 0.12, radiusX: iconR * 0.34, radiusY: iconR * 0.46, fill: '#34A853' }))+ group.add(new Konva.Line({ points: [cx - iconR * 0.24, cy + iconR * 0.1, cx, cy + iconR * 0.58, cx + iconR * 0.24, cy + iconR * 0.1], closed: true, fill: '#34A853' }))+ } else {+ const sc = iconR * 0.8+ group.add(new Konva.Ellipse({ x: cx, y: cy, radiusX: iconR, radiusY: iconR, fill: 'rgba(255,255,255,0.14)', stroke: 'rgba(255,255,255,0.9)', strokeWidth: 2.5 }))+ group.add(+ new Konva.Path({+ data: `M ${cx - sc * 0.4} ${cy + sc * 0.4} L ${cx + sc * 0.42} ${cy - sc * 0.42} M ${cx - sc * 0.05} ${cy - sc * 0.42} L ${cx + sc * 0.42} ${cy - sc * 0.42} L ${cx + sc * 0.42} ${cy + sc * 0.05}`,+ stroke: '#FFFFFF',+ strokeWidth: Math.max(2, iconR * 0.16),+ lineCap: 'round',+ lineJoin: 'round',+ }),+ )+ }+ group.add(+ new Konva.Text({+ x: 14,+ y: bandH + 10,+ width: Math.max(8, em.width - 28),+ height: 18,+ text: hostOf(em.url).toUpperCase(),+ fontSize: Math.max(9, Math.round(em.height * 0.055)),+ fontFamily: 'Inter',+ fill: 'rgba(255,255,255,0.55)',+ letterSpacing: 1.2,+ wrap: 'none',+ ellipsis: true,+ }),+ )+ group.add(+ new Konva.Text({+ x: 14,+ y: bandH + 30,+ width: Math.max(8, em.width - 28),+ height: Math.max(16, em.height - bandH - 40),+ text: em.title ?? em.url,+ fontSize: Math.max(11, Math.round(em.height * 0.07)),+ fontFamily: 'Inter',+ fontStyle: '600',+ fill: '#FFFFFF',+ wrap: 'word',+ ellipsis: true,+ }),+ )+ return group+ }+case 'group': {const g = elconst group = new Konva.Group({ id: g.id, x: g.x, y: g.y, rotation: g.rotation ?? 0 })diff --git a/tests/e2e/charts.spec.ts b/tests/e2e/charts.spec.tsnew file mode 100644index 0000000..8938e04--- /dev/null+++ b/tests/e2e/charts.spec.ts@@ -0,0 +1,253 @@+import { test, expect, type Page } from '@playwright/test'+import { readFileSync } from 'node:fs'++/**+ * v0.14 (D7): the data-bound chart element — acceptance.+ *+ * 1. adding a bar chart from the Elements panel lands a REAL chart+ * element (API truth: kind/labels/series), rendered on the canvas+ * 2. "Edit data" in the toolbar changes labels + values → the+ * document updates, and the canvas pixels move+ * 3. the toolbar converts the kind in place (bar → donut)+ * 4. data persists across a reload+ * 5. the SVG export carries the real geometry — category labels and+ * series colours as a bar chart; annular arc paths + the centre+ * total as a donut+ * 6. line + scatter charts land with their own data shapes; a+ * HOSTILE clipboard envelope pastes as a sanitized chart (junk+ * kind → bar fallback, caps applied, id remapped)+ *+ * Register budget: ONE registration per run (the second test logs in+ * with the shared account — the PR #26 discipline).+ */++let SHARED_ACCOUNT: { username: string; password: string } | null = null++async function register(page: Page, tag: string): Promise<string> {+ const username = `d7_${tag}_${Date.now().toString(36)}`+ const password = `D7-E2e-${username}-17!q`+ const res = await page.request.post('/api/auth/register', { data: { username, password } })+ expect(res.status(), `register ${username}`).toBeLessThan(300)+ if (!SHARED_ACCOUNT) SHARED_ACCOUNT = { username, password }+ return username+}++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 })+}++interface DocChart {+ id: string+ type: string+ kind?: string+ labels?: string[]+ series?: { name: string; color: string; values: number[] }[]+ barMode?: string+ hole?: number+ smooth?: boolean+}++async function docCharts(page: Page, designId: string): Promise<DocChart[]> {+ const res = await page.request.get(`/api/designs/${designId}`)+ expect(res.status()).toBe(200)+ const doc = (await res.json()) as { pages: { elements: DocChart[] }[] }+ return doc.pages[0].elements.filter((e) => e.type === 'chart')+}++/** the main Konva canvas as a data URL (pixel truth; scoped + biggest — the D4 lesson) */+async function canvasSnapshot(page: Page): Promise<string> {+ return page.evaluate(() => {+ 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+ )+ return biggest ? biggest.toDataURL() : ''+ })+}++test.describe('Charts (v0.14 D7)', () => {+ test.setTimeout(180_000)++ test('add bar → edit data → convert to donut → persist → SVG exports', async ({ page }) => {+ const username = await register(page, 'main')+ const design = await createDesign(page, `cvx_d7_${username}`, [])+ await openEditor(page, design)++ // ── add a bar chart from the Elements panel ──+ await page.getByRole('button', { name: 'Elements', exact: true }).first().click()+ await page.getByRole('tab', { name: 'Charts', exact: true }).click()+ await page.getByRole('button', { name: 'Add Bar chart' }).click()++ // API truth: a real chart element with the sample data+ await expect+ .poll(async () => (await docCharts(page, design)).length, { timeout: 45_000 })+ .toBe(1)+ let chart = (await docCharts(page, design))[0]+ expect(chart.kind).toBe('bar')+ expect(chart.labels).toEqual(['Q1', 'Q2', 'Q3', 'Q4'])+ expect(chart.series).toHaveLength(2)+ expect(chart.series?.[0]).toMatchObject({ name: 'Revenue', color: '#7630D7', values: [128, 155, 141, 190] })+ expect(chart.barMode).toBe('group')++ // the canvas actually rendered it (non-blank, and stable)+ const barPixels = await canvasSnapshot(page)+ expect(barPixels.length, 'canvas rendered the chart').toBeGreaterThan(1_000)++ // ── Edit data: a new label + a new value ──+ await page.getByRole('button', { name: 'Edit chart data' }).click()+ const pop = page.locator('.cv-pop').last()+ await expect(pop).toBeVisible()+ await pop.getByLabel('Label 1').fill('2023')+ await pop.getByLabel('Series 1 value 1').fill('200')++ await expect+ .poll(async () => {+ chart = (await docCharts(page, design))[0]+ return chart.labels?.[0] === '2023' && chart.series?.[0].values?.[0] === 200+ }, { timeout: 20_000 })+ .toBe(true)++ // the geometry moved with the data (pixel truth, observed end state)+ const editedPixels = await canvasSnapshot(page)+ expect(editedPixels, 'value edit changed the rendering').not.toBe(barPixels)++ // close the popover (its backdrop intercepts toolbar/export clicks)+ await page.mouse.click(30, 700)++ // ── export SVG as a bar chart: real labels + series colours ──+ 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 barSvg = readFileSync((await download.path())!, 'utf8')+ expect(barSvg).toContain('>2023<') // edited category label+ expect(barSvg).toContain('fill="#7630D7"') // series colour+ expect(barSvg).toContain('>200<') // y-axis tick reaching the edited max+ // the export dialog auto-closes after the download (observed end state)+ await expect(page.getByRole('button', { name: 'Close' })).toBeHidden({ timeout: 10_000 })++ // ── convert to a donut in place ──+ await page.getByRole('button', { name: 'Convert to Donut chart' }).click()+ await expect+ .poll(async () => (await docCharts(page, design))[0].kind, { timeout: 20_000 })+ .toBe('donut')++ const donutPixels = await canvasSnapshot(page)+ expect(donutPixels, 'donut renders different pixels than the bar chart').not.toBe(editedPixels)++ // ── reload — the conversion + edits persist ──+ await page.reload()+ await expect(page.getByLabel('Design canvas')).toBeVisible({ timeout: 60_000 })+ chart = (await docCharts(page, design))[0]+ expect(chart.kind).toBe('donut')+ expect(chart.labels?.[0]).toBe('2023')+ expect(chart.series?.[0].values?.[0]).toBe(200)++ // ── export SVG as a donut: annular arc paths + the centre total ──+ await page.getByRole('button', { name: 'Download', exact: true }).click()+ await page.getByRole('button', { name: /^SVG\b/ }).click()+ const [download2] = await Promise.all([+ page.waitForEvent('download'),+ page.getByRole('button', { name: /Download 1 SVG/i }).click(),+ ])+ const donutSvg = readFileSync((await download2.path())!, 'utf8')+ // annular sector: outer arc + line to inner radius + arc back + close+ expect(donutSvg).toMatch(/<path d="M [0-9.]+ [0-9.]+ A [0-9.]+ [0-9.]+ 0 [01] 1 /)+ expect(donutSvg).toContain('>686<') // centre total: 200+155+141+190+ })++ test('line + scatter shapes land, hostile envelope pastes sanitized', async ({ browser }) => {+ expect(SHARED_ACCOUNT, 'a prior test registered the shared account').not.toBeNull()+ const ctx = await browser.newContext({ permissions: ['clipboard-read', 'clipboard-write'] })+ const page = await ctx.newPage()+ const login = await page.request.post('/api/auth/login', {+ data: { username: SHARED_ACCOUNT!.username, password: SHARED_ACCOUNT!.password },+ })+ expect(login.status(), 'login as the shared account').toBeLessThan(300)++ const design = await createDesign(page, `cvx_d7_b_${SHARED_ACCOUNT!.username}`, [])+ await openEditor(page, design)++ // ── line chart ──+ await page.getByRole('button', { name: 'Elements', exact: true }).first().click()+ await page.getByRole('tab', { name: 'Charts', exact: true }).click()+ await page.getByRole('button', { name: 'Add Line chart' }).click()+ await expect+ .poll(async () => (await docCharts(page, design)).filter((c) => c.kind === 'line').length, { timeout: 45_000 })+ .toBe(1)+ const line = (await docCharts(page, design)).find((c) => c.kind === 'line')+ expect(line?.labels).toEqual(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'])+ expect(line?.series).toHaveLength(2)+ expect(line?.smooth).toBe(true)++ // ── scatter chart (labels stay empty, values are flat x,y pairs) ──+ await page.getByRole('button', { name: 'Add Scatter chart' }).click()+ await expect+ .poll(async () => (await docCharts(page, design)).filter((c) => c.kind === 'scatter').length, { timeout: 45_000 })+ .toBe(1)+ const scatter = (await docCharts(page, design)).find((c) => c.kind === 'scatter')+ expect(scatter?.labels).toEqual([])+ const scatterValues = scatter?.series?.[0]?.values ?? []+ expect(scatterValues.length).toBeGreaterThan(4)+ expect(scatterValues.length % 2).toBe(0)++ // ── hostile envelope on the OS clipboard → native paste ──+ const hostile = {+ app: 'canvix',+ v: 1,+ elements: [+ {+ id: 'hostile_chart_id',+ type: 'chart',+ kind: 'EVIL',+ x: 80,+ y: 80,+ width: 560,+ height: 360,+ labels: ['ok', 7, 'x'.repeat(60)],+ series: [+ { name: 'a', color: 'javascript:alert(1)', values: [1, 'x', 2e12] },+ 'junk',+ { name: 'b', color: '#02C0CC', values: [5, 5, 5] },+ ],+ barMode: 'diagonal',+ hole: 5,+ },+ ],+ }+ await page.evaluate((payload) => navigator.clipboard.writeText(payload), JSON.stringify(hostile))+ await page.keyboard.press('Control+v')++ await expect+ .poll(async () => (await docCharts(page, design)).length, { timeout: 20_000 })+ .toBe(3)+ const pasted = (await docCharts(page, design)).find((c) => c.id !== line?.id && c.id !== scatter?.id)+ expect(pasted, 'the pasted chart exists').toBeTruthy()+ if (pasted) {+ expect(pasted.id).not.toBe('hostile_chart_id') // ids are never trusted+ expect(pasted.kind).toBe('bar') // junk kind falls back, never reaches the renderers+ expect(pasted.labels).toEqual(['ok', 'x'.repeat(24)])+ expect(pasted.series).toEqual([+ { name: 'a', color: '#7630D7', values: [1, 1e9] }, // junk color → palette, non-finite dropped, 2e12 clamped+ { name: 'b', color: '#02C0CC', values: [5, 5, 5] }, // the valid series survives untouched+ ])+ expect(pasted.barMode).toBe('group')+ expect(pasted.hole).toBe(0.85)+ }+ await ctx.close()+ })+})