---
title: "Canvas Editor · UI SDK — StyleX Blocks"
description: "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."
url: "https://stylexblocks.com/block/ui-sdk/canvas-editor/"
agent:
  instructions: "Use this search API to find relevant components and blocks across this site with keywords or natural-language queries, instead of crawling individual pages. Results are returned in Markdown."
  endpoint: "https://stylexblocks.com/.well-known/search?q={query}"
  method: "GET"
  documentation: "https://developers.cloudflare.com/ai-search/how-to/search-for-agents/"
---

# Canvas Editor block

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.

- Behavior engine: UI SDK
- Category: [App shells](https://stylexblocks.com/blocks/app-shells.md)
- Built with: [Button](https://stylexblocks.com/components/ui-sdk/button.md), [Center](https://stylexblocks.com/components/ui-sdk/center.md), [Icon Button](https://stylexblocks.com/components/ui-sdk/icon-button.md), [Input](https://stylexblocks.com/components/ui-sdk/input.md), [Menu](https://stylexblocks.com/components/ui-sdk/menu.md), [Number Input](https://stylexblocks.com/components/ui-sdk/number-input.md), [Popover](https://stylexblocks.com/components/ui-sdk/popover.md), [Segment Group](https://stylexblocks.com/components/ui-sdk/segment-group.md), [Select](https://stylexblocks.com/components/ui-sdk/select.md), [Separator](https://stylexblocks.com/components/ui-sdk/separator.md), [Slider](https://stylexblocks.com/components/ui-sdk/slider.md), [Splitter](https://stylexblocks.com/components/ui-sdk/splitter.md), [Stack](https://stylexblocks.com/components/ui-sdk/stack.md), [Text](https://stylexblocks.com/components/ui-sdk/text.md), [Textarea](https://stylexblocks.com/components/ui-sdk/textarea.md), [Toast](https://stylexblocks.com/components/ui-sdk/toast.md), [Toolbar](https://stylexblocks.com/components/ui-sdk/toolbar.md), [Tree View](https://stylexblocks.com/components/ui-sdk/tree-view.md), [Visually Hidden](https://stylexblocks.com/components/ui-sdk/visually-hidden.md)
- HTML page: https://stylexblocks.com/block/ui-sdk/canvas-editor/

## Install

Configure the project once (sets the behavior engine and import aliases):

```sh
npx stylexblocks init --style ui-sdk
```

Then add the item as source you own:

```sh
npx stylexblocks add canvas-editor
```

Equivalent: `npx shadcn add @stylexblocks/canvas-editor`. Registry item JSON: https://stylexblocks.com/r/ui-sdk/canvas-editor.json

## Usage

```tsx
import { CanvasEditor } from "#components/blocks/ui-sdk/canvas-editor.tsx";

export function Example() {
  return (
    <div style={{ height: "100dvh" }}>
      <CanvasEditor />
    </div>
  );
}
```

## Source

`components/blocks/ui-sdk/canvas-editor.tsx`

```tsx
import * 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>
  );
}
```

Credit: Inspired by [Canvas Editor](https://astryx.atmeta.com/playground?template=canvas-editor) from Astryx (MIT License · Copyright (c) 2026 Meta Platforms, Inc.)
