All blocks
Canvas Editor
Layered artboard workspace with document tabs, a folded desktop command menu, resizable layer and library rail, zoomable poster canvas, and a live inspector for position, typography, HSV color, and CSS image filters.
Built withButtonCenterIcon ButtonInputMenuNumber InputPopoverSegment GroupSelectSeparatorSliderSplitterStackTextTextareaToastToolbarTree ViewVisually Hidden
Canvas editor
Saved · 2 min ago
Text
Headline
Dateline
Images
Photo

October 18–26 · Kyoto
Forms of quiet light
Install
1npx stylexblocks add canvas-editorSource
components/blocks/ui-sdk/canvas-editor.tsx
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277import * as stylex from "@stylexjs/stylex";import { Fragment, useCallback, useMemo, useRef, useState } from "react";import { Button } from "#components/ui/ui-sdk/button.tsx";import { Center } from "#components/ui/ui-sdk/center.tsx";import { IconButton } from "#components/ui/ui-sdk/icon-button.tsx";import { Input } from "#components/ui/ui-sdk/input.tsx";import { Menu } from "#components/ui/ui-sdk/menu.tsx";import { NumberInput } from "#components/ui/ui-sdk/number-input.tsx";import { Popover } from "#components/ui/ui-sdk/popover.tsx";import { SegmentGroup } from "#components/ui/ui-sdk/segment-group.tsx";import { Select } from "#components/ui/ui-sdk/select.tsx";import { Separator } from "#components/ui/ui-sdk/separator.tsx";import { Slider } from "#components/ui/ui-sdk/slider.tsx";import { Splitter } from "#components/ui/ui-sdk/splitter.tsx";import { HStack, VStack } from "#components/ui/ui-sdk/stack.tsx";import { Text } from "#components/ui/ui-sdk/text.tsx";import { Textarea } from "#components/ui/ui-sdk/textarea.tsx";import { Toast, Toaster } from "#components/ui/ui-sdk/toast.tsx";import { Toolbar } from "#components/ui/ui-sdk/toolbar.tsx";import { TreeView } from "#components/ui/ui-sdk/tree-view.tsx";import { VisuallyHidden } from "#components/ui/ui-sdk/visually-hidden.tsx";import { semanticColors } from "@stylexblocks/ui/semantic-tokens/colors.stylex.ts";import { semanticRadii } from "@stylexblocks/ui/semantic-tokens/radii.stylex.ts";import { semanticShadows } from "@stylexblocks/ui/semantic-tokens/shadows.stylex.ts";import { accentPalette, redPalette } from "@stylexblocks/ui/themes/palettes.ts";import { fontSizes } from "@stylexblocks/ui/tokens/font-sizes.stylex.ts";import { fontWeights } from "@stylexblocks/ui/tokens/font-weights.stylex.ts";import { fonts } from "@stylexblocks/ui/tokens/fonts.stylex.ts";import { radii } from "@stylexblocks/ui/tokens/radii.stylex.ts";import { spacing } from "@stylexblocks/ui/tokens/spacing.stylex.ts";import type { StyleOverrideProps } from "#lib/recipe-props.ts";
const FRAME = { width: 1080, height: 1920 };const NARROW_INSPECTOR = "@container canvas-editor (max-width: 820px)";const NARROW_RAIL = "@container canvas-editor (max-width: 600px)";const FOLD_SAVE_NOTE = "@container canvas-editor-header (max-width: 540px)";
const PHOTO_LAYER_SRC = "/images/blocks/canvas-editor/kyoto-dusk.webp";
type LayerKind = "text" | "image";type ThemeMode = "light" | "dark" | "system";type AlignX = "start" | "center" | "end" | "justify";type AlignY = "start" | "center" | "end";type Decoration = "none" | "underline" | "line-through";type Transform = "none" | "capitalize" | "uppercase" | "lowercase";
interface Filters { blur: number; brightness: number; contrast: number; grayscale: number; hue: number; invert: number; opacity: number; saturate: number; sepia: number;}
interface Shadow { x: number; y: number; blur: number; spread: number; color: string;}
interface Layer { id: string; name: string; kind: LayerKind; x: number; y: number; width: number; height: number; rotation: number; paddingInline: number; paddingBlock: number; radius: number; isLocked: boolean; content: string; border?: string; fill?: string; shadow?: Shadow; family?: string; weight?: string; color?: string; size?: number; line?: number; tracking?: number; alignX?: AlignX; alignY?: AlignY; isItalic?: boolean; decoration?: Decoration; transform?: Transform; textShadow?: Shadow; stroke?: number; fit?: string; filters?: Filters;}
interface DocumentTabData { id: string; name: string;}
const NO_SHADOW: Shadow = { x: 0, y: 0, blur: 0, spread: 0, color: "#000000" };
const NO_FILTERS: Filters = { blur: 0, brightness: 100, contrast: 100, grayscale: 0, hue: 0, invert: 0, opacity: 100, saturate: 100, sepia: 0,};
const INITIAL_TABS: DocumentTabData[] = [ { id: "exhibition", name: "Kyoto exhibition" }, { id: "specimen", name: "Type specimen" }, { id: "story", name: "Social story" },];
const INITIAL_LAYERS: Layer[] = [ { id: "headline", name: "Headline", kind: "text", x: 56, y: 136, width: 968, height: 300, rotation: 0, paddingInline: 0, paddingBlock: 0, radius: 0, isLocked: false, content: "Forms of quiet light", fill: "#1b1d2b", family: "Anton", weight: "Regular", color: "#1b1d2b", size: 112, line: 100, tracking: -2, alignX: "start", alignY: "start", isItalic: false, decoration: "none", transform: "uppercase", stroke: 0, }, { id: "dateline", name: "Dateline", kind: "text", x: 56, y: 56, width: 968, height: 56, rotation: 0, paddingInline: 0, paddingBlock: 0, radius: 0, isLocked: false, content: "October 18–26 · Kyoto", family: "Inter Tight", weight: "Medium", color: "#1b1d2b", size: 26, line: 120, tracking: 32, alignX: "center", alignY: "start", isItalic: false, decoration: "none", transform: "uppercase", stroke: 0, }, { id: "photo", name: "Photo", kind: "image", x: 0, y: 0, width: 1080, height: 1920, rotation: 0, paddingInline: 0, paddingBlock: 0, radius: 0, isLocked: true, content: "Autumn pagoda and cedar silhouettes over misty Higashiyama hills", fit: "Cover", filters: NO_FILTERS, },];
const EFFECT_PRESETS: Array<{ label: string; filters: Partial<Filters> }> = [ { label: "Film grain", filters: { contrast: 116, saturate: 88, sepia: 16 } }, { label: "Warm sepia", filters: { sepia: 58, contrast: 112, brightness: 104 } }, { label: "Indigo duotone", filters: { sepia: 50, hue: 195, saturate: 135, contrast: 118 } },];
const FILTERS: Array<{ key: keyof Filters; label: string; max: number; unit: string }> = [ { key: "blur", label: "Blur", max: 20, unit: "px" }, { key: "brightness", label: "Brightness", max: 200, unit: "%" }, { key: "contrast", label: "Contrast", max: 200, unit: "%" }, { key: "grayscale", label: "Grayscale", max: 100, unit: "%" }, { key: "hue", label: "Hue", max: 360, unit: "deg" }, { key: "invert", label: "Invert", max: 100, unit: "%" }, { key: "opacity", label: "Opacity", max: 100, unit: "%" }, { key: "saturate", label: "Saturate", max: 200, unit: "%" }, { key: "sepia", label: "Sepia", max: 100, unit: "%" },];
const ZOOM_OPTIONS = [ { value: "0.25", label: "25%" }, { value: "0.4", label: "40%" }, { value: "0.6", label: "60%" }, { value: "1", label: "100%" },];
const FONT_OPTIONS = ["Anton", "Archivo Black", "Bebas Neue", "Inter Tight"];const WEIGHT_OPTIONS = ["Regular", "Medium", "Semibold", "Bold"];const EXPORT_FORMATS = ["PNG · 1080 × 1920", "JPG · 1080 × 1920", "PDF · print ready"];const INSERT_ITEMS = ["Frame", "Group", "Text", "Image"];
const FONT_STACK: Record<string, string> = { Anton: 'Anton, Impact, Haettenschweiler, "Arial Narrow", sans-serif', "Archivo Black": '"Archivo Black", Impact, "Arial Black", sans-serif', "Bebas Neue": '"Bebas Neue", Impact, "Arial Narrow", sans-serif', "Inter Tight": '"Inter Tight", system-ui, -apple-system, sans-serif',};
const FONT_WEIGHT_MAP: Record<string, number> = { Regular: 400, Medium: 500, Semibold: 600, Bold: 700,};
interface Hsv { h: number; s: number; v: number;}
function hsvToHex({ h, s, v }: Hsv): string { const channel = (n: number) => { const k = (n + h / 60) % 6; const value = (v / 100) * (1 - (s / 100) * Math.max(0, Math.min(k, 4 - k, 1))); return Math.round(value * 255) .toString(16) .padStart(2, "0"); }; return `#${channel(5)}${channel(3)}${channel(1)}`;}
function hexToHsv(hex: string): Hsv { const parsed = /^#?([\da-f]{6})$/i.exec(hex.trim()); if (!parsed) return { h: 0, s: 0, v: 0 }; const int = parseInt(parsed[1]!, 16); const r = ((int >> 16) & 255) / 255; const g = ((int >> 8) & 255) / 255; const b = (int & 255) / 255; const max = Math.max(r, g, b); const span = max - Math.min(r, g, b); let h = 0; if (span !== 0) { if (max === r) h = ((g - b) / span) % 6; else if (max === g) h = (b - r) / span + 2; else h = (r - g) / span + 4; } return { h: (Math.round(h * 60) + 360) % 360, s: max === 0 ? 0 : Math.round((span / max) * 100), v: Math.round(max * 100), };}
function filterCss(f: Filters): string { const parts: string[] = []; if (f.blur) parts.push(`blur(${f.blur}px)`); if (f.brightness !== 100) parts.push(`brightness(${f.brightness}%)`); if (f.contrast !== 100) parts.push(`contrast(${f.contrast}%)`); if (f.grayscale) parts.push(`grayscale(${f.grayscale}%)`); if (f.hue) parts.push(`hue-rotate(${f.hue}deg)`); if (f.invert) parts.push(`invert(${f.invert}%)`); if (f.opacity !== 100) parts.push(`opacity(${f.opacity}%)`); if (f.saturate !== 100) parts.push(`saturate(${f.saturate}%)`); if (f.sepia) parts.push(`sepia(${f.sepia}%)`); return parts.length ? parts.join(" ") : "none";}
function shadowCss(s?: Shadow): string | undefined { if (!s) return undefined; return `${s.x}px ${s.y}px ${s.blur}px ${s.color}`;}
const styles = stylex.create({ root: { backgroundColor: semanticColors.bg, color: semanticColors.fg, containerName: "canvas-editor", containerType: "inline-size", fontFamily: fonts.body, height: "100%", minHeight: 0, overflow: "hidden", width: "100%", }, lightOverride: { colorScheme: "light", }, darkOverride: { colorScheme: "dark", }, header: { backgroundColor: semanticColors.bgSurface, borderBottomColor: semanticColors.border, borderBottomStyle: "solid", borderBottomWidth: "1px", containerName: "canvas-editor-header", containerType: "inline-size", flexShrink: 0, paddingBlock: spacing._1, paddingInline: spacing._1_5, }, shrink0: { flexShrink: 0, }, saveNote: { display: { default: "inline", [FOLD_SAVE_NOTE]: "none" }, whiteSpace: "nowrap", }, tabStrip: { overflowX: "auto", scrollbarWidth: "none", }, tabItem: { backgroundColor: { default: "transparent", ":hover": semanticColors.interactionHover, }, borderRadius: radii.md, color: semanticColors.fgMuted, flexShrink: 0, height: "1.75rem", maxWidth: "10.5rem", minWidth: "6rem", paddingInline: spacing._2, transitionDuration: "120ms", transitionProperty: "background-color, color", }, tabItemActive: { backgroundColor: semanticColors.bgMuted, color: semanticColors.fg, }, tabSelectBtn: { alignItems: "center", backgroundColor: "transparent", borderStyle: "none", color: "inherit", cursor: "pointer", display: "flex", flexGrow: 1, fontFamily: fonts.body, fontSize: fontSizes.xs, fontWeight: fontWeights.medium, gap: spacing._1_5, minWidth: 0, paddingBlock: 0, paddingInline: 0, textAlign: "start", }, tabCloseBtn: { alignItems: "center", backgroundColor: { default: "transparent", ":hover": semanticColors.interactionPressed, }, borderRadius: radii.sm, borderStyle: "none", color: semanticColors.fgSubtle, cursor: "pointer", display: "inline-flex", flexShrink: 0, height: "1.125rem", justifyContent: "center", paddingBlock: 0, paddingInline: 0, width: "1.125rem", }, tabRule: { height: "0.875rem", }, tabRuleHidden: { opacity: 0, }, workspace: { flexGrow: 1, minHeight: 0, width: "100%", }, railPanel: { backgroundColor: semanticColors.bgSurface, display: { default: "flex", [NARROW_RAIL]: "none" }, height: "100%", minHeight: 0, overflowY: "auto", paddingBlock: spacing._2_5, paddingInline: spacing._2_5, }, railHandle: { display: { default: "grid", [NARROW_RAIL]: "none" }, }, inspectorHandle: { display: { default: "grid", [NARROW_INSPECTOR]: "none" }, }, inspectorPanel: { backgroundColor: semanticColors.bgSurface, display: { default: "flex", [NARROW_INSPECTOR]: "none" }, height: "100%", minHeight: 0, overflowY: "auto", }, canvasPanel: { backgroundColor: semanticColors.bgMuted, height: "100%", minHeight: 0, position: "relative", }, canvasScroll: { flexGrow: 1, minHeight: 0, overflow: "auto", paddingBlockEnd: "4.5rem", paddingBlockStart: spacing._6, paddingInline: spacing._6, }, artboardFrame: { backgroundColor: "#ffffff", borderRadius: radii.xs, boxShadow: semanticShadows.lg, colorScheme: "light", flexShrink: 0, overflow: "hidden", position: "relative", }, artboardInner: { height: `${FRAME.height}px`, insetBlockStart: 0, insetInlineStart: 0, overflow: "hidden", position: "absolute", transformOrigin: "top left", width: `${FRAME.width}px`, }, artboardPhoto: { bottom: 0, display: "block", height: "100%", left: 0, position: "absolute", right: 0, top: 0, width: "100%", }, artboardTextColumn: { bottom: 0, boxSizing: "border-box", gap: "24px", height: "100%", left: 0, paddingBlock: "56px", paddingInline: "56px", position: "absolute", right: 0, top: 0, width: "100%", }, artboardTextBase: { marginBlock: 0, marginInline: 0, overflowWrap: "break-word", width: "100%", }, floatingBarWrap: { bottom: spacing._4, insetInline: 0, pointerEvents: "none", position: "absolute", zIndex: 5, }, floatingBar: { backgroundColor: semanticColors.bgElevated, borderColor: semanticColors.border, borderRadius: radii.xl, borderStyle: "solid", borderWidth: "1px", boxShadow: semanticShadows.md, pointerEvents: "auto", }, zoomSelect: { minWidth: "4.75rem", width: "4.75rem", }, lockBtn: { alignItems: "center", backgroundColor: { default: "transparent", ":hover": semanticColors.interactionHover, }, borderRadius: radii.sm, borderStyle: "none", color: semanticColors.fgSubtle, cursor: "pointer", display: "inline-flex", flexShrink: 0, height: "1.25rem", justifyContent: "center", paddingBlock: 0, paddingInline: 0, width: "1.25rem", }, presetList: { listStyleType: "none", marginBlock: 0, marginInline: 0, paddingBlock: 0, paddingInline: 0, }, presetBtn: { alignItems: "center", backgroundColor: { default: "transparent", ":hover": semanticColors.interactionHover, }, borderRadius: radii.md, borderStyle: "none", color: semanticColors.fg, cursor: "pointer", display: "flex", fontFamily: fonts.body, fontSize: fontSizes.xs, fontWeight: fontWeights.medium, gap: spacing._2, paddingBlock: spacing._1_5, paddingInline: spacing._2, textAlign: "start", width: "100%", }, inspectorSection: { borderBottomColor: semanticColors.border, borderBottomStyle: "solid", borderBottomWidth: "1px", paddingBlock: spacing._3, paddingInline: spacing._3, }, rowLabel: { flexShrink: 0, width: "4.5rem", }, rowLabelNarrow: { width: "3.25rem", }, fieldGrow: { flexGrow: 1, minWidth: 0, }, axisField: { alignItems: "center", backgroundColor: semanticColors.bgSurface, borderColor: semanticColors.border, borderRadius: semanticRadii.control, borderStyle: "solid", borderWidth: "1px", display: "flex", flexGrow: 1, gap: spacing._1, height: "1.75rem", minWidth: 0, paddingInline: spacing._1_5, }, axisPrefix: { color: semanticColors.fgSubtle, flexShrink: 0, fontFamily: fonts.mono, fontSize: "0.7rem", fontWeight: fontWeights.medium, }, axisNumeric: { backgroundColor: "transparent", borderStyle: "none", color: semanticColors.fg, fontFamily: fonts.body, fontSize: fontSizes.xs, minWidth: 0, outlineStyle: "none", paddingBlock: 0, paddingInline: 0, width: "100%", }, swatchBtn: { backgroundImage: "linear-gradient(45deg, transparent 45%, var(--sui-colors-border-emphasized, #999) 45% 55%, transparent 55%)", borderColor: semanticColors.borderEmphasized, borderRadius: semanticRadii.control, borderStyle: "solid", borderWidth: "1px", cursor: "pointer", flexShrink: 0, height: "1.75rem", paddingBlock: 0, paddingInline: 0, width: "1.75rem", }, swatchFilled: { backgroundImage: "none", }, popoverBox: { width: "14.5rem", }, hsvPlane: { backgroundImage: "linear-gradient(to top, #000, transparent), linear-gradient(to right, #fff, transparent)", borderRadius: radii.md, cursor: "crosshair", height: "8.5rem", position: "relative", touchAction: "none", width: "100%", }, hsvThumb: { borderColor: "#ffffff", borderRadius: radii.full, borderStyle: "solid", borderWidth: "2px", boxShadow: "0 0 0 1px rgba(0,0,0,0.4)", height: "0.75rem", pointerEvents: "none", position: "absolute", transform: "translate(-50%, -50%)", width: "0.75rem", }, hueTrack: { backgroundImage: "linear-gradient(to right, #f00, #ff0, #0f0, #0ff, #00f, #f0f, #f00)", }, hueIndicator: { backgroundColor: "transparent", }, filterNum: { flexShrink: 0, width: "3.75rem", }, thumbBtn: { backgroundColor: semanticColors.bgMuted, borderColor: semanticColors.borderEmphasized, borderRadius: semanticRadii.control, borderStyle: "solid", borderWidth: "1px", cursor: "pointer", flexShrink: 0, height: "1.75rem", overflow: "hidden", paddingBlock: 0, paddingInline: 0, width: "1.75rem", }, thumbImg: { display: "block", height: "100%", objectFit: "cover", width: "100%", }, segFull: { width: "100%", }, segItem: { flexGrow: 1, }, menuWidth: { minWidth: "13rem", }, scaledFrame: (w: number, h: number) => ({ width: `${w}px`, height: `${h}px` }), scaledArtboard: (scale: number) => ({ transform: `scale(${scale})` }), photoFilter: (filter: string, fit: string) => ({ filter, objectFit: fit.toLowerCase() as "cover" | "contain" | "fill", }), hueFill: (h: number) => ({ backgroundColor: `hsl(${h} 100% 50%)` }), swatchBg: (color: string) => ({ backgroundColor: color }), thumbPos: (s: number, v: number) => ({ insetInlineStart: `${s}%`, insetBlockStart: `${100 - v}%`, }), textLayerDyn: ( fontFamily: string, fontWeight: number, fontSize: number, linePct: number, tracking: number, color: string, stroke: number, textShadow: string | undefined, rotation: number, ) => ({ color, fontFamily, fontSize: `${fontSize}px`, fontWeight, letterSpacing: `${tracking / 100}em`, lineHeight: linePct / 100, textShadow, transform: rotation ? `rotate(${rotation}deg)` : undefined, WebkitTextStrokeWidth: stroke > 0 ? `${stroke}px` : undefined, WebkitTextStrokeColor: stroke > 0 ? color : undefined, }),});
const alignYMap = stylex.create({ start: { justifyContent: "flex-start" }, center: { justifyContent: "center" }, end: { justifyContent: "flex-end" },});
const alignXMap = stylex.create({ start: { textAlign: "start" }, center: { textAlign: "center" }, end: { textAlign: "end" }, justify: { textAlign: "justify" },});
const caseMap = stylex.create({ none: { textTransform: "none" }, capitalize: { textTransform: "capitalize" }, uppercase: { textTransform: "uppercase" }, lowercase: { textTransform: "lowercase" },});
const decorationMap = stylex.create({ none: { textDecorationLine: "none" }, underline: { textDecorationLine: "underline" }, "line-through": { textDecorationLine: "line-through" },});
const slantMap = stylex.create({ normal: { fontStyle: "normal" }, italic: { fontStyle: "italic" },});
function MenuIcon() { return ( <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" aria-hidden="true"> <line x1="4" y1="6" x2="20" y2="6" /> <line x1="4" y1="12" x2="20" y2="12" /> <line x1="4" y1="18" x2="20" y2="18" /> </svg> );}
function FileIcon() { return ( <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"> <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" /> <polyline points="14 2 14 8 20 8" /> </svg> );}
function PlusIcon() { return ( <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden="true"> <line x1="12" y1="5" x2="12" y2="19" /> <line x1="5" y1="12" x2="19" y2="12" /> </svg> );}
function CloseIcon() { return ( <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden="true"> <line x1="18" y1="6" x2="6" y2="18" /> <line x1="6" y1="6" x2="18" y2="18" /> </svg> );}
function DownloadIcon() { return ( <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"> <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" /> <polyline points="7 10 12 15 17 10" /> <line x1="12" y1="15" x2="12" y2="3" /> </svg> );}
function UndoIcon() { return ( <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"> <path d="M9 14 4 9l5-5" /> <path d="M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5 5.5 5.5 0 0 1-5.5 5.5H11" /> </svg> );}
function RedoIcon() { return ( <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"> <path d="m15 14 5-5-5-5" /> <path d="M20 9H9.5A5.5 5.5 0 0 0 4 14.5 5.5 5.5 0 0 0 9.5 20H13" /> </svg> );}
function FrameIcon() { return ( <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" aria-hidden="true"> <line x1="22" y1="6" x2="2" y2="6" /> <line x1="22" y1="18" x2="2" y2="18" /> <line x1="6" y1="2" x2="6" y2="22" /> <line x1="18" y1="2" x2="18" y2="22" /> </svg> );}
function TypeIcon() { return ( <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"> <polyline points="4 7 4 4 20 4 20 7" /> <line x1="9" y1="20" x2="15" y2="20" /> <line x1="12" y1="4" x2="12" y2="20" /> </svg> );}
function ImageIcon() { return ( <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"> <rect x="3" y="3" width="18" height="18" rx="2" /> <circle cx="9" cy="9" r="2" /> <path d="m21 15-3.1-3.1a2 2 0 0 0-2.8 0L6 21" /> </svg> );}
function LockIcon({ locked }: { locked: boolean }) { return locked ? ( <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"> <rect x="4" y="11" width="16" height="10" rx="2" /> <path d="M8 11V7a4 4 0 0 1 8 0v4" /> </svg> ) : ( <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"> <rect x="4" y="11" width="16" height="10" rx="2" /> <path d="M8 11V7a4 4 0 0 1 7.6-1.7" /> </svg> );}
function RotateIcon({ ccw }: { ccw?: boolean }) { return ccw ? ( <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"> <path d="M3 12a9 9 0 1 0 3-6.7L3 8" /> <path d="M3 3v5h5" /> </svg> ) : ( <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"> <path d="M21 12a9 9 0 1 1-3-6.7L21 8" /> <path d="M21 3v5h-5" /> </svg> );}
function FlipIcon({ vertical }: { vertical?: boolean }) { return vertical ? ( <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"> <line x1="3" y1="12" x2="21" y2="12" strokeDasharray="2 2" /> <polygon points="7 8 17 8 12 4" /> <polygon points="7 16 17 16 12 20" /> </svg> ) : ( <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"> <line x1="12" y1="3" x2="12" y2="21" strokeDasharray="2 2" /> <polygon points="8 7 8 17 4 12" /> <polygon points="16 7 16 17 20 12" /> </svg> );}
function SparklePresetIcon() { return ( <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"> <circle cx="12" cy="12" r="9" /> <path d="M12 3v18" /> <path d="M12 8l6 4-6 4" /> </svg> );}
function InspectorRow({ label, narrow, end, children,}: { label: string; narrow?: boolean; end?: boolean; children: React.ReactNode;}) { return ( <HStack gap="2"> <Text render={<span />} size="xs" tone="muted" truncate="true" style={[styles.rowLabel, narrow && styles.rowLabelNarrow]} > {label} </Text> <HStack gap="1" justify={end ? "end" : "start"} style={styles.fieldGrow}> {children} </HStack> </HStack> );}
function AxisInput({ prefix, label, value, onChange,}: { prefix: string; label: string; value: number; onChange: (next: number) => void;}) { return ( <label {...stylex.props(styles.axisField)}> <span {...stylex.props(styles.axisPrefix)} aria-hidden="true"> {prefix} </span> <input type="number" aria-label={label} value={value} onChange={(e) => { const parsed = Number(e.target.value); if (!Number.isNaN(parsed)) onChange(parsed); }} {...stylex.props(styles.axisNumeric)} /> </label> );}
function StepperRow({ label, value, onChange,}: { label: string; value: number; onChange: (next: number) => void;}) { return ( <InspectorRow label={label}> <NumberInput.Root size="xs" variant="outline" value={value} onValueChange={(next) => { if (typeof next === "number" && !Number.isNaN(next)) onChange(next); }} style={styles.fieldGrow} > <NumberInput.Group> <NumberInput.Input aria-label={label} /> <NumberInput.Control /> </NumberInput.Group> </NumberInput.Root> </InspectorRow> );}
function HsvColorPicker({ value, onChange,}: { value: string; onChange: (hex: string) => void;}) { const [hsv, setHsv] = useState<Hsv>(() => hexToHsv(value)); const [draft, setDraft] = useState(value); const planeRef = useRef<HTMLDivElement>(null);
const commit = (next: Hsv) => { setHsv(next); const hex = hsvToHex(next); setDraft(hex); onChange(hex); };
const trackPointer = (clientX: number, clientY: number) => { const rect = planeRef.current?.getBoundingClientRect(); if (!rect || rect.width <= 0 || rect.height <= 0) return; const s = Math.round(Math.max(0, Math.min(1, (clientX - rect.left) / rect.width)) * 100); const v = Math.round((1 - Math.max(0, Math.min(1, (clientY - rect.top) / rect.height))) * 100); commit({ ...hsv, s, v }); };
return ( <> <div ref={planeRef} role="slider" tabIndex={0} aria-label="Saturation and brightness" aria-valuenow={hsv.s} aria-valuemin={0} aria-valuemax={100} onPointerDown={(e) => { e.currentTarget.setPointerCapture(e.pointerId); trackPointer(e.clientX, e.clientY); }} onPointerMove={(e) => { if (e.buttons === 1) trackPointer(e.clientX, e.clientY); }} onKeyDown={(e) => { const step = e.shiftKey ? 10 : 2; if (e.key === "ArrowRight") commit({ ...hsv, s: Math.min(100, hsv.s + step) }); else if (e.key === "ArrowLeft") commit({ ...hsv, s: Math.max(0, hsv.s - step) }); else if (e.key === "ArrowUp") commit({ ...hsv, v: Math.min(100, hsv.v + step) }); else if (e.key === "ArrowDown") commit({ ...hsv, v: Math.max(0, hsv.v - step) }); else return; e.preventDefault(); }} {...stylex.props(styles.hsvPlane, styles.hueFill(hsv.h))} > <span {...stylex.props( styles.hsvThumb, styles.thumbPos(hsv.s, hsv.v), styles.swatchBg(hsvToHex(hsv)), )} /> </div>
<Slider.Root size="sm" min={0} max={360} value={hsv.h} onValueChange={(next) => { const h = Array.isArray(next) ? next[0] ?? 0 : next; commit({ ...hsv, h }); }} > <Slider.Control> <Slider.Track style={styles.hueTrack}> <Slider.Indicator style={styles.hueIndicator} /> <Slider.Thumb aria-label="Hue" /> </Slider.Track> </Slider.Control> </Slider.Root>
<Input size="xs" aria-label="Hex color" value={draft} onChange={(e) => { const next = e.target.value; setDraft(next); if (/^#?[\da-f]{6}$/i.test(next.trim())) { const normalized = next.trim().startsWith("#") ? next.trim() : `#${next.trim()}`; setHsv(hexToHsv(normalized)); onChange(normalized); } }} /> </> );}
function ColorSwatchPopover({ label, value, onChange, children,}: { label: string; value?: string; onChange: (next: string) => void; children?: React.ReactNode;}) { return ( <Popover.Root size="sm"> <Popover.Trigger render={ <button type="button" aria-label={`${label}${value ? `, ${value}` : ", not set"}`} {...stylex.props( styles.swatchBtn, value != null && styles.swatchFilled, value != null && styles.swatchBg(value), )} /> } /> <Popover.Content side="left" align="start" sideOffset={8}> <VStack gap="2.5" style={styles.popoverBox}> <Text render={<span />} size="xs" weight="semibold"> {label} </Text> <HsvColorPicker value={value ?? "#111111"} onChange={onChange} /> {children} </VStack> </Popover.Content> </Popover.Root> );}
function StyleRow({ label, name = label, value, onChange, onClear, children,}: { label: string; name?: string; value?: string; onChange: (next: string) => void; onClear: () => void; children?: React.ReactNode;}) { return ( <InspectorRow label={label}> <Input size="xs" aria-label={name} value={value ?? ""} placeholder="Add…" onChange={(e) => onChange(e.target.value)} style={styles.fieldGrow} /> <ColorSwatchPopover label={name} value={value} onChange={onChange}> {children} </ColorSwatchPopover> <IconButton variant="ghost" size="xs" aria-label={`Clear ${name.toLowerCase()}`} disabled={value === undefined} onClick={onClear} > <CloseIcon /> </IconButton> </InspectorRow> );}
function ShadowFields({ name, shadow, onChange,}: { name: string; shadow: Shadow; onChange: (next: Shadow) => void;}) { return ( <> {( [ ["x", "X"], ["y", "Y"], ["blur", "Blur"], ["spread", "Spread"], ] as const ).map(([key, lbl]) => ( <InspectorRow key={key} label={lbl} narrow> <NumberInput.Root size="xs" variant="outline" value={shadow[key]} onValueChange={(next) => { if (typeof next === "number" && !Number.isNaN(next)) { onChange({ ...shadow, [key]: next }); } }} style={styles.fieldGrow} > <NumberInput.Group> <NumberInput.Input aria-label={`${name} ${lbl.toLowerCase()}`} /> <NumberInput.Control /> </NumberInput.Group> </NumberInput.Root> </InspectorRow> ))} </> );}
export interface CanvasEditorProps extends StyleOverrideProps {}
/** * CanvasEditor — layered 9:16 artboard workspace with document tabs, folded * desktop command menu, resizable layer/library rail, zoomable poster canvas * with floating tools, and a live context-sensitive inspector for text and * image layers (including HSV color pickers and nine CSS image filters). */export function CanvasEditor({ palette, style }: CanvasEditorProps) { const queue = useMemo(() => Toast.createToaster(), []); const demo = useCallback((msg: string) => queue.info(msg), [queue]);
const [layers, setLayers] = useState<Layer[]>(INITIAL_LAYERS); const [selectedId, setSelectedId] = useState("headline"); const [leftTab, setLeftTab] = useState("layers"); const [zoom, setZoom] = useState("0.4"); const [chrome, setChrome] = useState({ left: true, right: true, toolbar: true }); const [appearance, setAppearance] = useState<ThemeMode>("system"); const [tabs, setTabs] = useState<DocumentTabData[]>(INITIAL_TABS); const [activeTab, setActiveTab] = useState(INITIAL_TABS[0]!.id); const [imageName, setImageName] = useState("kyoto-dusk.webp"); const untitledCount = useRef(1); const fileRef = useRef<HTMLInputElement>(null);
const selected = layers.find((l) => l.id === selectedId) ?? layers[0]!; const scale = Number(zoom);
const updateSelected = useCallback( (patch: Partial<Layer>) => { setLayers((curr) => curr.map((l) => (l.id === selectedId ? { ...l, ...patch } : l))); }, [selectedId], );
const closeTab = (id: string) => { setTabs((curr) => { const idx = curr.findIndex((t) => t.id === id); const next = curr.filter((t) => t.id !== id); if (id === activeTab) { const neighbour = next[idx] ?? next[idx - 1]; setActiveTab(neighbour ? neighbour.id : ""); } return next; }); };
const addTab = () => { untitledCount.current += 1; const tab: DocumentTabData = { id: `untitled-${untitledCount.current}`, name: `Untitled ${untitledCount.current}`, }; setTabs((curr) => [...curr, tab]); setActiveTab(tab.id); };
const headline = layers.find((l) => l.id === "headline") ?? layers[0]!; const dateline = layers.find((l) => l.id === "dateline") ?? layers[1]!; const photo = layers.find((l) => l.kind === "image") ?? layers[2]!;
const textLayers = layers.filter((l) => l.kind === "text"); const imageLayers = layers.filter((l) => l.kind === "image");
const defaultSplitLayout = chrome.left && chrome.right ? [20, 52, 28] : chrome.left ? [24, 76] : chrome.right ? [70, 30] : [100];
const renderLayerRow = (layer: Layer) => ( <TreeView.Item key={layer.id} value={layer.id} onClick={() => setSelectedId(layer.id)} data-selected={layer.id === selectedId ? "true" : undefined} > {layer.kind === "text" ? <TypeIcon /> : <ImageIcon />} <HStack gap="1.5" justify="between" style={styles.fieldGrow}> <TreeView.ItemText>{layer.name}</TreeView.ItemText> <button type="button" aria-label={layer.isLocked ? `Unlock ${layer.name}` : `Lock ${layer.name}`} onClick={(e) => { e.stopPropagation(); setLayers((curr) => curr.map((l) => (l.id === layer.id ? { ...l, isLocked: !l.isLocked } : l)), ); }} {...stylex.props(styles.lockBtn)} > <LockIcon locked={layer.isLocked} /> </button> </HStack> </TreeView.Item> );
const leftRail = ( <VStack gap="2.5" style={styles.railPanel}> <SegmentGroup.Root size="sm" value={leftTab} onValueChange={setLeftTab} aria-label="Left panel" style={styles.segFull} > <SegmentGroup.Item value="layers" style={styles.segItem}> Layers </SegmentGroup.Item> <SegmentGroup.Item value="library" style={styles.segItem}> Library </SegmentGroup.Item> </SegmentGroup.Root>
{leftTab === "layers" ? ( <TreeView.Root size="xs" variant="subtle" defaultExpandedValue={["group-text", "group-images"]} palette={accentPalette} > <TreeView.Tree aria-label="Document layers"> {textLayers.length > 0 ? ( <TreeView.Branch value="group-text"> <TreeView.BranchControl> <TreeView.BranchIndicator /> <FrameIcon /> <TreeView.BranchText>Text</TreeView.BranchText> </TreeView.BranchControl> <TreeView.BranchContent> <TreeView.BranchIndentGuide /> {textLayers.map(renderLayerRow)} </TreeView.BranchContent> </TreeView.Branch> ) : null}
{imageLayers.length > 0 ? ( <TreeView.Branch value="group-images"> <TreeView.BranchControl> <TreeView.BranchIndicator /> <FrameIcon /> <TreeView.BranchText>Images</TreeView.BranchText> </TreeView.BranchControl> <TreeView.BranchContent> <TreeView.BranchIndentGuide /> {imageLayers.map(renderLayerRow)} </TreeView.BranchContent> </TreeView.Branch> ) : null} </TreeView.Tree> </TreeView.Root> ) : ( <VStack render={<ul />} gap="1" style={styles.presetList}> {EFFECT_PRESETS.map((preset) => ( <li key={preset.label}> <button type="button" onClick={() => { setLayers((curr) => curr.map((l) => l.kind === "image" ? { ...l, filters: { ...NO_FILTERS, ...preset.filters } } : l, ), ); setSelectedId(photo.id); queue.success(`Applied ${preset.label}`); }} {...stylex.props(styles.presetBtn)} > <SparklePresetIcon /> <span>{preset.label}</span> </button> </li> ))} </VStack> )} </VStack> );
const canvasCenter = ( <VStack gap="0" style={styles.canvasPanel}> <Center style={styles.canvasScroll}> <div dir="ltr" {...stylex.props( styles.artboardFrame, styles.scaledFrame(FRAME.width * scale, FRAME.height * scale), )} > <div {...stylex.props(styles.artboardInner, styles.scaledArtboard(scale))}> <img src={PHOTO_LAYER_SRC} alt={photo.content} {...stylex.props( styles.artboardPhoto, styles.photoFilter(filterCss(photo.filters ?? NO_FILTERS), photo.fit ?? "Cover"), )} /> <VStack gap="6" style={[ styles.artboardTextColumn, alignYMap[headline.alignY ?? "start"], ]} > <p onClick={() => setSelectedId(dateline.id)} {...stylex.props( styles.artboardTextBase, alignXMap[dateline.alignX ?? "center"], caseMap[dateline.transform ?? "uppercase"], decorationMap[dateline.decoration ?? "none"], slantMap[dateline.isItalic ? "italic" : "normal"], styles.textLayerDyn( FONT_STACK[dateline.family ?? "Inter Tight"] ?? FONT_STACK["Inter Tight"]!, FONT_WEIGHT_MAP[dateline.weight ?? "Medium"] ?? 500, dateline.size ?? 26, dateline.line ?? 120, dateline.tracking ?? 32, dateline.color ?? "#111111", dateline.stroke ?? 0, shadowCss(dateline.textShadow), dateline.rotation, ), )} > {dateline.content} </p>
<h2 onClick={() => setSelectedId(headline.id)} {...stylex.props( styles.artboardTextBase, alignXMap[headline.alignX ?? "start"], caseMap[headline.transform ?? "uppercase"], decorationMap[headline.decoration ?? "none"], slantMap[headline.isItalic ? "italic" : "normal"], styles.textLayerDyn( FONT_STACK[headline.family ?? "Anton"] ?? FONT_STACK.Anton!, FONT_WEIGHT_MAP[headline.weight ?? "Regular"] ?? 400, headline.size ?? 112, headline.line ?? 100, headline.tracking ?? -2, headline.color ?? "#111111", headline.stroke ?? 0, shadowCss(headline.textShadow), headline.rotation, ), )} > {headline.content} </h2> </VStack> </div> </div> </Center>
{chrome.toolbar ? ( <Center style={styles.floatingBarWrap}> <Toolbar.Root variant="surface" size="sm" aria-label="Canvas tools" style={styles.floatingBar}> <Toolbar.Button aria-label="Undo" onClick={() => demo("Demo: last change would be undone")}> <UndoIcon /> </Toolbar.Button> <Toolbar.Button aria-label="Redo" onClick={() => demo("Demo: change would be redone")}> <RedoIcon /> </Toolbar.Button> <Toolbar.Separator /> <Toolbar.Button aria-label="Add frame" onClick={() => demo("Demo: a new frame would be added")}> <FrameIcon /> </Toolbar.Button> <Toolbar.Button aria-label="Add text" onClick={() => demo("Demo: a new text layer would be added")}> <TypeIcon /> </Toolbar.Button> <Toolbar.Button aria-label="Add image" onClick={() => demo("Demo: an image picker would open")}> <ImageIcon /> </Toolbar.Button> <Toolbar.Separator /> <Select.Root size="xs" variant="subtle" value={zoom} onValueChange={(next) => { if (typeof next === "string") setZoom(next); }} style={styles.zoomSelect} > <Select.Control> <Select.Trigger aria-label="Zoom"> <Select.Value> {ZOOM_OPTIONS.find((o) => o.value === zoom)?.label ?? "25%"} </Select.Value> </Select.Trigger> <Select.IndicatorGroup> <Select.Icon /> </Select.IndicatorGroup> </Select.Control> <Select.Content side="top"> {ZOOM_OPTIONS.map((opt) => ( <Select.Item key={opt.value} value={opt.value}> <Select.ItemText>{opt.label}</Select.ItemText> <Select.ItemIndicator /> </Select.Item> ))} </Select.Content> </Select.Root> </Toolbar.Root> </Center> ) : null} </VStack> );
const rightInspector = ( <VStack render={<aside />} gap="0" aria-label={`${selected.name} properties`} style={styles.inspectorPanel} > <VStack gap="2.5" style={styles.inspectorSection}> <Text render={<h3 />} size="xs" weight="semibold"> Layout </Text> <InspectorRow label="Padding"> <AxisInput prefix="H" label="Horizontal padding" value={selected.paddingInline} onChange={(next) => updateSelected({ paddingInline: next })} /> <AxisInput prefix="V" label="Vertical padding" value={selected.paddingBlock} onChange={(next) => updateSelected({ paddingBlock: next })} /> </InspectorRow> </VStack>
<VStack gap="2.5" style={styles.inspectorSection}> <Text render={<h3 />} size="xs" weight="semibold"> Layer </Text> <InspectorRow label="Position"> <AxisInput prefix="X" label="Horizontal position" value={selected.x} onChange={(next) => updateSelected({ x: next })} /> <AxisInput prefix="Y" label="Vertical position" value={selected.y} onChange={(next) => updateSelected({ y: next })} /> </InspectorRow> <InspectorRow label="Size"> <AxisInput prefix="W" label="Width" value={selected.width} onChange={(next) => updateSelected({ width: next })} /> <AxisInput prefix="H" label="Height" value={selected.height} onChange={(next) => updateSelected({ height: next })} /> </InspectorRow> </VStack>
<VStack gap="2.5" style={styles.inspectorSection}> <Text render={<h3 />} size="xs" weight="semibold"> Styles </Text> <InspectorRow label="Radius"> <AxisInput prefix="R" label="Corner radius" value={selected.radius} onChange={(next) => updateSelected({ radius: next })} /> </InspectorRow> <StyleRow label="Border" value={selected.border} onChange={(next) => updateSelected({ border: next })} onClear={() => updateSelected({ border: undefined })} /> <StyleRow label="Shadow" name="Box shadow" value={selected.shadow?.color} onChange={(next) => updateSelected({ shadow: { ...(selected.shadow ?? NO_SHADOW), color: next } }) } onClear={() => updateSelected({ shadow: undefined })} > <ShadowFields name="Box shadow" shadow={selected.shadow ?? NO_SHADOW} onChange={(next) => updateSelected({ shadow: next })} /> </StyleRow> <StyleRow label="Fill" value={selected.fill} onChange={(next) => updateSelected({ fill: next })} onClear={() => updateSelected({ fill: undefined })} /> </VStack>
<VStack gap="2.5" style={styles.inspectorSection}> <Text render={<h3 />} size="xs" weight="semibold"> Transforms </Text> <InspectorRow label="Rotate"> <AxisInput prefix="°" label="Rotation" value={selected.rotation} onChange={(next) => updateSelected({ rotation: next })} /> <IconButton variant="ghost" size="xs" aria-label="Rotate counterclockwise" onClick={() => updateSelected({ rotation: (selected.rotation + 270) % 360 })} > <RotateIcon ccw /> </IconButton> <IconButton variant="ghost" size="xs" aria-label="Rotate clockwise" onClick={() => updateSelected({ rotation: (selected.rotation + 90) % 360 })} > <RotateIcon /> </IconButton> </InspectorRow> <InspectorRow label="Flip" end> <IconButton variant="ghost" size="xs" aria-label="Flip horizontally" onClick={() => demo("Demo: layer would flip horizontally")} > <FlipIcon /> </IconButton> <IconButton variant="ghost" size="xs" aria-label="Flip vertically" onClick={() => demo("Demo: layer would flip vertically")} > <FlipIcon vertical /> </IconButton> </InspectorRow> </VStack>
{selected.kind === "text" ? ( <VStack gap="2.5" style={styles.inspectorSection}> <Text render={<h3 />} size="xs" weight="semibold"> Text </Text> <Textarea size="sm" rows={2} aria-label="Text content" value={selected.content} onChange={(e) => updateSelected({ content: e.target.value })} /> <InspectorRow label="Font"> <Select.Root size="xs" value={selected.family ?? "Anton"} onValueChange={(next) => { if (typeof next === "string") updateSelected({ family: next }); }} style={styles.fieldGrow} > <Select.Control> <Select.Trigger aria-label="Font family"> <Select.Value /> </Select.Trigger> <Select.IndicatorGroup> <Select.Icon /> </Select.IndicatorGroup> </Select.Control> <Select.Content> {FONT_OPTIONS.map((font) => ( <Select.Item key={font} value={font}> <Select.ItemText>{font}</Select.ItemText> <Select.ItemIndicator /> </Select.Item> ))} </Select.Content> </Select.Root> </InspectorRow> <InspectorRow label="Weight"> <Select.Root size="xs" value={selected.weight ?? "Regular"} onValueChange={(next) => { if (typeof next === "string") updateSelected({ weight: next }); }} style={styles.fieldGrow} > <Select.Control> <Select.Trigger aria-label="Font weight"> <Select.Value /> </Select.Trigger> <Select.IndicatorGroup> <Select.Icon /> </Select.IndicatorGroup> </Select.Control> <Select.Content> {WEIGHT_OPTIONS.map((w) => ( <Select.Item key={w} value={w}> <Select.ItemText>{w}</Select.ItemText> <Select.ItemIndicator /> </Select.Item> ))} </Select.Content> </Select.Root> </InspectorRow> <InspectorRow label="Color"> <Input size="xs" aria-label="Text color" value={selected.color ?? "#111111"} onChange={(e) => updateSelected({ color: e.target.value })} style={styles.fieldGrow} /> <ColorSwatchPopover label="Text color" value={selected.color ?? "#111111"} onChange={(next) => updateSelected({ color: next })} /> </InspectorRow> <StepperRow label="Size" value={selected.size ?? 112} onChange={(next) => updateSelected({ size: next })} /> <StepperRow label="Line" value={selected.line ?? 100} onChange={(next) => updateSelected({ line: next })} /> <StepperRow label="Spacing" value={selected.tracking ?? 0} onChange={(next) => updateSelected({ tracking: next })} /> <InspectorRow label="Align X"> <SegmentGroup.Root size="xs" aria-label="Horizontal alignment" value={selected.alignX ?? "start"} onValueChange={(next) => updateSelected({ alignX: next as AlignX })} style={styles.segFull} > {(["start", "center", "end", "justify"] as const).map((a) => ( <SegmentGroup.Item key={a} value={a} style={styles.segItem}> {a[0]!.toUpperCase()} </SegmentGroup.Item> ))} </SegmentGroup.Root> </InspectorRow> <InspectorRow label="Align Y"> <SegmentGroup.Root size="xs" aria-label="Vertical alignment" value={selected.alignY ?? "start"} onValueChange={(next) => updateSelected({ alignY: next as AlignY })} style={styles.segFull} > <SegmentGroup.Item value="start" style={styles.segItem}> Top </SegmentGroup.Item> <SegmentGroup.Item value="center" style={styles.segItem}> Mid </SegmentGroup.Item> <SegmentGroup.Item value="end" style={styles.segItem}> Bot </SegmentGroup.Item> </SegmentGroup.Root> </InspectorRow> <InspectorRow label="Style"> <SegmentGroup.Root size="xs" aria-label="Font style" value={selected.isItalic ? "italic" : "normal"} onValueChange={(next) => updateSelected({ isItalic: next === "italic" })} style={styles.segFull} > <SegmentGroup.Item value="normal" style={styles.segItem}> Regular </SegmentGroup.Item> <SegmentGroup.Item value="italic" style={styles.segItem}> Italic </SegmentGroup.Item> </SegmentGroup.Root> </InspectorRow> <InspectorRow label="Decor"> <SegmentGroup.Root size="xs" aria-label="Text decoration" value={selected.decoration ?? "none"} onValueChange={(next) => updateSelected({ decoration: next as Decoration })} style={styles.segFull} > <SegmentGroup.Item value="none" style={styles.segItem}> None </SegmentGroup.Item> <SegmentGroup.Item value="underline" style={styles.segItem}> U </SegmentGroup.Item> <SegmentGroup.Item value="line-through" style={styles.segItem}> S </SegmentGroup.Item> </SegmentGroup.Root> </InspectorRow> <InspectorRow label="Case"> <SegmentGroup.Root size="xs" aria-label="Text transform" value={selected.transform ?? "none"} onValueChange={(next) => updateSelected({ transform: next as Transform })} style={styles.segFull} > <SegmentGroup.Item value="none" style={styles.segItem}> — </SegmentGroup.Item> <SegmentGroup.Item value="capitalize" style={styles.segItem}> Aa </SegmentGroup.Item> <SegmentGroup.Item value="uppercase" style={styles.segItem}> AA </SegmentGroup.Item> <SegmentGroup.Item value="lowercase" style={styles.segItem}> aa </SegmentGroup.Item> </SegmentGroup.Root> </InspectorRow> <StyleRow label="Shadow" name="Text shadow" value={selected.textShadow?.color} onChange={(next) => updateSelected({ textShadow: { ...(selected.textShadow ?? NO_SHADOW), color: next }, }) } onClear={() => updateSelected({ textShadow: undefined })} > <ShadowFields name="Text shadow" shadow={selected.textShadow ?? NO_SHADOW} onChange={(next) => updateSelected({ textShadow: next })} /> </StyleRow> <InspectorRow label="Stroke"> <AxisInput prefix="px" label="Text stroke" value={selected.stroke ?? 0} onChange={(next) => updateSelected({ stroke: Math.max(0, next) })} /> <IconButton variant="ghost" size="xs" aria-label="Clear stroke" disabled={!selected.stroke} onClick={() => updateSelected({ stroke: 0 })} > <CloseIcon /> </IconButton> </InspectorRow> </VStack> ) : ( <> <VStack gap="2.5" style={styles.inspectorSection}> <Text render={<h3 />} size="xs" weight="semibold"> Image </Text> <InspectorRow label="Edit"> <Input size="xs" aria-label="Image source" value={imageName} readOnly style={styles.fieldGrow} /> <input ref={fileRef} type="file" accept="image/*" hidden onChange={(e) => { const file = e.target.files?.[0]; if (file) setImageName(file.name); }} /> <button type="button" aria-label="Replace image" onClick={() => fileRef.current?.click()} {...stylex.props(styles.thumbBtn)} > <img src={PHOTO_LAYER_SRC} alt={`Current image, ${imageName}`} {...stylex.props(styles.thumbImg)} /> </button> </InspectorRow> <InspectorRow label="Fit"> <Select.Root size="xs" value={selected.fit ?? "Cover"} onValueChange={(next) => { if (typeof next === "string") updateSelected({ fit: next }); }} style={styles.fieldGrow} > <Select.Control> <Select.Trigger aria-label="Image fit"> <Select.Value /> </Select.Trigger> <Select.IndicatorGroup> <Select.Icon /> </Select.IndicatorGroup> </Select.Control> <Select.Content> {["Cover", "Contain", "Fill"].map((fit) => ( <Select.Item key={fit} value={fit}> <Select.ItemText>{fit}</Select.ItemText> <Select.ItemIndicator /> </Select.Item> ))} </Select.Content> </Select.Root> </InspectorRow> </VStack>
<VStack gap="2.5" style={styles.inspectorSection}> <Text render={<h3 />} size="xs" weight="semibold"> Filters </Text> {FILTERS.map((filter) => { const current = (selected.filters ?? NO_FILTERS)[filter.key]; const setFilter = (val: number) => updateSelected({ filters: { ...(selected.filters ?? NO_FILTERS), [filter.key]: Math.max(0, Math.min(filter.max, val)), }, }); return ( <InspectorRow key={filter.key} label={filter.label}> <Slider.Root size="sm" min={0} max={filter.max} value={current} palette={accentPalette} onValueChange={(next) => { const val = Array.isArray(next) ? next[0] ?? 0 : next; setFilter(val); }} style={styles.fieldGrow} > <Slider.Control> <Slider.Track> <Slider.Indicator /> <Slider.Thumb aria-label={`${filter.label} slider`} /> </Slider.Track> </Slider.Control> </Slider.Root> <div {...stylex.props(styles.filterNum)}> <AxisInput prefix="" label={filter.label} value={current} onChange={setFilter} /> </div> </InspectorRow> ); })} </VStack> </> )} </VStack> );
return ( <VStack gap="0" palette={palette} style={[ styles.root, appearance === "light" && styles.lightOverride, appearance === "dark" && styles.darkOverride, style, ]} > <VisuallyHidden render={<h1 />}>Canvas editor</VisuallyHidden>
{/* Header bar: folded command menu, document tabs, save note, Export */} <HStack render={<header />} gap="1.5" justify="between" style={styles.header}> <HStack gap="1" style={styles.fieldGrow}> <Menu.Root size="sm"> <Menu.Trigger render={<IconButton variant="ghost" size="xs" aria-label="Editor menu" />}> <MenuIcon /> </Menu.Trigger> <Menu.Content align="start" style={styles.menuWidth}> <Menu.SubmenuRoot> <Menu.SubmenuTrigger> <Menu.ItemText>File</Menu.ItemText> </Menu.SubmenuTrigger> <Menu.SubmenuContent> <Menu.Item onSelect={addTab}> <Menu.ItemText>New poster</Menu.ItemText> <Menu.ItemCommand>⌘N</Menu.ItemCommand> </Menu.Item> <Menu.Item onSelect={() => demo("Demo: file open dialog")}> <Menu.ItemText>Open…</Menu.ItemText> <Menu.ItemCommand>⌘O</Menu.ItemCommand> </Menu.Item> <Menu.Separator /> <Menu.Item onSelect={() => queue.success("Saved Kyoto exhibition")}> <Menu.ItemText>Save</Menu.ItemText> <Menu.ItemCommand>⌘S</Menu.ItemCommand> </Menu.Item> <Menu.SubmenuRoot> <Menu.SubmenuTrigger> <Menu.ItemText>Export</Menu.ItemText> </Menu.SubmenuTrigger> <Menu.SubmenuContent> {EXPORT_FORMATS.map((fmt) => ( <Menu.Item key={fmt} onSelect={() => queue.success(`Exporting ${fmt}`)}> <Menu.ItemText>{fmt}</Menu.ItemText> </Menu.Item> ))} </Menu.SubmenuContent> </Menu.SubmenuRoot> </Menu.SubmenuContent> </Menu.SubmenuRoot>
<Menu.SubmenuRoot> <Menu.SubmenuTrigger> <Menu.ItemText>Edit</Menu.ItemText> </Menu.SubmenuTrigger> <Menu.SubmenuContent> <Menu.Item onSelect={() => demo("Demo: undo")}> <Menu.ItemText>Undo</Menu.ItemText> <Menu.ItemCommand>⌘Z</Menu.ItemCommand> </Menu.Item> <Menu.Item onSelect={() => demo("Demo: redo")}> <Menu.ItemText>Redo</Menu.ItemText> <Menu.ItemCommand>⇧⌘Z</Menu.ItemCommand> </Menu.Item> <Menu.Separator /> <Menu.Item onSelect={() => demo("Demo: duplicate layer")}> <Menu.ItemText>Duplicate</Menu.ItemText> <Menu.ItemCommand>⌘D</Menu.ItemCommand> </Menu.Item> <Menu.Item palette={redPalette} onSelect={() => demo(`Demo: delete ${selected.name}`)} > <Menu.ItemText>Delete {selected.name}</Menu.ItemText> <Menu.ItemCommand>⌫</Menu.ItemCommand> </Menu.Item> </Menu.SubmenuContent> </Menu.SubmenuRoot>
<Menu.SubmenuRoot> <Menu.SubmenuTrigger> <Menu.ItemText>View</Menu.ItemText> </Menu.SubmenuTrigger> <Menu.SubmenuContent> <Menu.CheckboxItem value="left-panel" checked={chrome.left} onCheckedChange={(checked) => setChrome((c) => ({ ...c, left: checked }))} > <Menu.ItemText>Left panel</Menu.ItemText> <Menu.ItemIndicator /> </Menu.CheckboxItem> <Menu.CheckboxItem value="right-panel" checked={chrome.right} onCheckedChange={(checked) => setChrome((c) => ({ ...c, right: checked }))} > <Menu.ItemText>Right panel</Menu.ItemText> <Menu.ItemIndicator /> </Menu.CheckboxItem> <Menu.CheckboxItem value="canvas-tools" checked={chrome.toolbar} onCheckedChange={(checked) => setChrome((c) => ({ ...c, toolbar: checked }))} > <Menu.ItemText>Canvas tools</Menu.ItemText> <Menu.ItemIndicator /> </Menu.CheckboxItem> <Menu.Separator /> <Menu.SubmenuRoot> <Menu.SubmenuTrigger> <Menu.ItemText>Zoom</Menu.ItemText> </Menu.SubmenuTrigger> <Menu.SubmenuContent> <Menu.RadioGroup value={zoom} onValueChange={setZoom}> {ZOOM_OPTIONS.map((opt) => ( <Menu.RadioItem key={opt.value} value={opt.value}> <Menu.ItemText>{opt.label}</Menu.ItemText> <Menu.ItemIndicator /> </Menu.RadioItem> ))} </Menu.RadioGroup> </Menu.SubmenuContent> </Menu.SubmenuRoot> <Menu.SubmenuRoot> <Menu.SubmenuTrigger> <Menu.ItemText>Appearance</Menu.ItemText> </Menu.SubmenuTrigger> <Menu.SubmenuContent> <Menu.RadioGroup value={appearance} onValueChange={(next) => setAppearance(next as ThemeMode)} > <Menu.RadioItem value="light"> <Menu.ItemText>Light</Menu.ItemText> <Menu.ItemIndicator /> </Menu.RadioItem> <Menu.RadioItem value="dark"> <Menu.ItemText>Dark</Menu.ItemText> <Menu.ItemIndicator /> </Menu.RadioItem> <Menu.RadioItem value="system"> <Menu.ItemText>System</Menu.ItemText> <Menu.ItemIndicator /> </Menu.RadioItem> </Menu.RadioGroup> </Menu.SubmenuContent> </Menu.SubmenuRoot> </Menu.SubmenuContent> </Menu.SubmenuRoot>
<Menu.SubmenuRoot> <Menu.SubmenuTrigger> <Menu.ItemText>Object</Menu.ItemText> </Menu.SubmenuTrigger> <Menu.SubmenuContent> <Menu.SubmenuRoot> <Menu.SubmenuTrigger> <Menu.ItemText>Insert</Menu.ItemText> </Menu.SubmenuTrigger> <Menu.SubmenuContent> {INSERT_ITEMS.map((item) => ( <Menu.Item key={item} onSelect={() => demo(`Demo: insert ${item}`)}> <Menu.ItemText>{item}</Menu.ItemText> </Menu.Item> ))} </Menu.SubmenuContent> </Menu.SubmenuRoot> <Menu.Separator /> <Menu.CheckboxItem value="lock-layer" checked={selected.isLocked} onCheckedChange={(checked) => updateSelected({ isLocked: checked })} > <Menu.ItemText>Lock {selected.name}</Menu.ItemText> <Menu.ItemIndicator /> </Menu.CheckboxItem> </Menu.SubmenuContent> </Menu.SubmenuRoot>
<Menu.Separator />
<Menu.SubmenuRoot> <Menu.SubmenuTrigger> <Menu.ItemText>Help</Menu.ItemText> </Menu.SubmenuTrigger> <Menu.SubmenuContent> <Menu.Item onSelect={() => demo("Demo: keyboard shortcuts")}> <Menu.ItemText>Keyboard shortcuts</Menu.ItemText> <Menu.ItemCommand>⌘/</Menu.ItemCommand> </Menu.Item> <Menu.Item onSelect={() => demo("Demo: documentation")}> <Menu.ItemText>Documentation</Menu.ItemText> </Menu.Item> <Menu.Item onSelect={() => demo("Canvas Editor · StyleX Blocks")}> <Menu.ItemText>About this editor</Menu.ItemText> </Menu.Item> </Menu.SubmenuContent> </Menu.SubmenuRoot> </Menu.Content> </Menu.Root>
<HStack role="group" aria-label="Open documents" gap="0.5" style={styles.tabStrip}> {tabs.map((tab, idx) => { const prev = tabs[idx - 1]; const isActive = tab.id === activeTab; const hideRule = prev?.id === activeTab || isActive; return ( <Fragment key={tab.id}> {prev ? ( <Separator orientation="vertical" style={[styles.tabRule, hideRule && styles.tabRuleHidden]} /> ) : null} <HStack gap="1" style={[styles.tabItem, isActive && styles.tabItemActive]}> <button type="button" aria-current={isActive ? "page" : undefined} onClick={() => setActiveTab(tab.id)} {...stylex.props(styles.tabSelectBtn)} > <FileIcon /> <Text render={<span />} size="xs" weight="medium" tone={isActive ? "default" : "muted"} truncate="true" > {tab.name} </Text> </button> <button type="button" aria-label={`Close ${tab.name}`} onClick={() => closeTab(tab.id)} {...stylex.props(styles.tabCloseBtn)} > <CloseIcon /> </button> </HStack> </Fragment> ); })} </HStack>
<IconButton variant="ghost" size="xs" aria-label="New document" onClick={addTab}> <PlusIcon /> </IconButton> </HStack>
<HStack gap="2.5" style={styles.shrink0}> <Text render={<span />} size="xs" tone="subtle" style={styles.saveNote}> Saved · 2 min ago </Text> <Menu.Root size="sm"> <Menu.Trigger render={<Button variant="ghost" size="xs" />}> <DownloadIcon /> Export </Menu.Trigger> <Menu.Content align="end"> {EXPORT_FORMATS.map((fmt) => ( <Menu.Item key={fmt} onSelect={() => queue.success(`Exporting ${fmt}`)}> <Menu.ItemText>{fmt}</Menu.ItemText> </Menu.Item> ))} </Menu.Content> </Menu.Root> </HStack> </HStack>
{/* Resizable 3-pane workspace */} <HStack gap="0" style={styles.workspace}> <Splitter.Root key={`${chrome.left}-${chrome.right}`} defaultSize={defaultSplitLayout} minSize={15} style={styles.workspace} > {chrome.left ? ( <> <Splitter.Panel>{leftRail}</Splitter.Panel> <Splitter.ResizeTrigger aria-label="Resize layers panel" style={styles.railHandle} /> </> ) : null}
<Splitter.Panel>{canvasCenter}</Splitter.Panel>
{chrome.right ? ( <> <Splitter.ResizeTrigger aria-label="Resize properties panel" style={styles.inspectorHandle} /> <Splitter.Panel>{rightInspector}</Splitter.Panel> </> ) : null} </Splitter.Root> </HStack>
<Toaster toaster={queue} /> </VStack> );}
Inspired by the Canvas Editor template from Astryx (MIT License · Copyright (c) 2026 Meta Platforms, Inc.).