Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(templates): add the Canvas Editor page template (#6237)

Ernest4a962032e2fd
diff --git a/.changeset/canvas-editor-template.md b/.changeset/canvas-editor-template.md
new file mode 100644
index 0000000000..ca79fb2df6
--- /dev/null
+++ b/.changeset/canvas-editor-template.md
@@ -0,0 +1,401 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] Add a Canvas Editor page template (#6237)
+@ernestt
+
+A layered-artboard workspace: a File/Edit/View/Object/Help
+menubar over a layer rail and asset library on the left, the artboard centered
+on a muted backdrop under a floating tool bar that sets zoom, and a property
+inspector on the right whose fields retarget to the selected layer. Both rails
+drag to resize.
+
+The inspector is the substance of it. A text layer gets font, weight, colour,
+size, line height, letter spacing, horizontal and vertical alignment, slant,
+decoration, transform, a text shadow and a stroke; an image layer gets fit and
+the nine CSS filters, each on a number and a rail that move together. Colour
+anywhere in the panel opens a real picker. Everything that can reach the
+artboard does — typing in Transform recases the poster, dragging Sepia tints
+the photograph.
+
+It fills a gap next to `Tools - Page Editor`. That one composes a document — a
+palette of blocks dropped into a flow that reflows around them. This one moves
+objects on a fixed 1080 x 1920 frame, where position and size are coordinates
+rather than an order, so the inspector reads X/Y/W/H and the canvas needs a
+zoom control at all.
+
+Two decisions worth knowing if you copy it:
+
+**The artboard is themed, not styled.** The template's `canvasEditorTheme` is
+pinned to `mode="light"` around the artboard, so the poster keeps its palette
+when the editor around it goes dark. The theme carries what belongs to the
+poster as a whole —
+the display face, the leading, the uppercase treatment, the frame margins —
+and the display face is Anton with a fallback chain through the condensed
+grotesques that ship with macOS and Windows. The chain puts Impact ahead of
+Arial Narrow because every face in it is a single-weight black rendered at
+weight 400, and Arial Narrow at 400 reads thin rather than poster-heavy.
+
+Size and tracking are deliberately not tokens: they belong to a layer rather
+than to the poster, so they live on the layer and the inspector edits them
+live. That split is the line worth copying — theme what the surface owns,
+leave per-object properties to the object.
+
+**Zoom is a transform, not a re-layout.** The artboard always lays out at its
+native size and the frame scales the painted result, which keeps the theme's
+numbers in artboard pixels — the same numbers the inspector shows — and keeps
+the poster from reflowing between zoom steps.
+
+**The menubar is one button, not five.** File/Edit/View/Object/Help became
+submenus of a single `DropdownMenu`. A menubar spends the top-left on five
+words that are only read by someone already hunting for a command, and this
+editor has something better to do with that space: the tabs, which are read
+constantly. The commands keep their grouping — the bar became the first
+level of the menu rather than disappearing. The menu takes a `menuWidth`
+because left to itself it matches its trigger, and the trigger is a 28px
+icon button: five one-word rows in a column barely wider than the words,
+with nowhere for the submenu chevrons to sit.
+
+Five smaller things the template works out, in case you hit the same walls:
+
+**A field names itself from inside.** Every inspector control is one input
+with a glyph in its `startIcon` slot — `X`, `Y`, `W`, `H` — rather than an
+`InputGroup` pairing an addon to a field. It reads as a single control, and
+the accessible name stops stuttering ("Horizontal position", not "Horizontal
+position X"). `startIcon` takes an SVG component, so the letters are drawn on
+the same 24px grid Lucide uses and sit interchangeably beside real icons.
+
+**One left edge across the panel.** The label column is a set width, but a
+flex item shrinks before its siblings do, and the fields beside it carry
+StackItem's min-width reset. Without `flexShrink: 0` on the label column the
+row spends its shrinkage there, and every field lands on a slightly different
+edge — which is the one thing an inspector cannot afford.
+
+**Row actions use the shared reveal primitive.** A layer's lock stays hidden
+until the row is pointed at or receives keyboard focus. `useContainerReveal`
+owns the hover, focus, coarse-pointer, and reduced-motion behavior, while
+`TreeListItemData` forwards the returned row props so every nested row keeps
+its reveal state isolated.
+
+**A fixed-height Card scrolls; the artboard has to clip.** Give `Card` a
+`height` and it becomes a scroll container, which is right for a card holding
+more copy than fits. The artboard is the opposite case: it lays out at its
+native 1080 wide at every zoom step and the frame scales the painted result,
+so its content is deliberately larger than its box and the card would offer
+1080px of sideways scroll inside a 432px frame. `overflow: clip` through
+`xstyle` is the fix, and `clip` over `hidden` because nothing here should
+scroll at all — including the quiet scroll `hidden` still performs when
+something inside it takes focus.
+
+**Concentric corners come out of the padding.** The floating tool bar is a
+card with one spacing step of padding, so the controls inside it round to the
+card's radius _less_ that step — written as
+`calc(var(--radius-container) - var(--spacing-1))` rather than a number, so
+it still holds if either token moves. An inner corner cut at the same radius
+as its container reads as a rounder curve crossing a straighter one; matching
+the difference is what strikes both from the same centre. While you are in
+there: a vertical `Divider` is `height: 100%`, and a flex row that centres
+its items gives a percentage height nothing to resolve against, so the rule
+collapses to zero and the bar silently loses its groups. `alignSelf: stretch`
+is what gives it a height.
+
+**The top bar is a `LayoutHeader`, not a `Toolbar`.** It reads like a
+toolbar and it is not one. A toolbar is a set of peer commands that arrow
+keys walk across, and the document tabs break that twice: arrowing off a tab
+landed on that tab's own close button, and a strip of open documents is not
+a band of tools in the first place. It also fought the padding — a toolbar
+sizes its gutters for a band heading content, and app chrome wants to sit
+tighter, which took a `--astryx-section-padding-inline` override and the
+edge compensation that override republished.
+
+`LayoutHeader` is the component for the slot, and `padding={1}` settles all
+of it: 4px on every edge puts the menu button's box exactly where the ghost
+inset used to pull it, so the glyph lands on the same pixel with nothing
+pulled back out. Same 45px bar, same 18px glyph centre, same divider —
+measured before and after — minus a role that was describing the wrong
+thing. The floating canvas tool bar stays a `Toolbar`, because that one
+really is a row of peer commands, and it still roves left to right.
+
+**One icon on three rows is a list nobody reads.** Border, shadow and fill
+all shipped with the same `Palette` swatch, and the three effect presets in
+the library shared it too — six rows, one mark, so the column read as one
+control repeated rather than six different things. Lucide has no `shadow`,
+`fill` or `padding` icon, so the picks came out of reading the pack rather
+than guessing at names: `PaintBucket` for fill, `SquareStack` for shadow
+(two offset squares is a drop shadow), plain `Square` for border,
+`SquareRoundCorner` for per-corner radius so it stops colliding with the
+per-side padding button that was also `SquareDashed`. Two things worth
+knowing if you go looking yourself. Names in that pack can be aliases —
+`FlipHorizontal` re-exports `square-centerline-dashed-horizontal`, which at
+16px is an unreadable dashed box, and the mirrored triangles you actually
+want are `FlipHorizontal2`. And judge candidates at 16px, not at sketch
+size: `radius` is a legible corner gauge at 48px and mush at 16.
+
+X, Y, W and H stay letterforms. They are names, not pictures — no icon
+distinguishes the horizontal coordinate from the vertical one, and every
+design tool prints the letters for the same reason.
+
+**A shortcut is a hint, not a control.** `Kbd` paints one key cap per key, so
+`⌘N` arrived as two small objects beside the menu item and read as something
+you could press. Desktop menus print shortcuts as quiet secondary text, which
+is what these are now — a `Text type="supporting" color="secondary"`, one
+string, set against the menu's right edge. The cost is platform awareness:
+`Kbd` resolves `mod` to ⌘ or Ctrl, and it does that through
+`isApplePlatform`, which core keeps unexported on purpose, so a template that
+leaves `Kbd` prints macOS glyphs and stops adapting. The `shell-nav` menubar
+already makes that trade. If you need both the quiet treatment and the
+platform switch, that is a gap in `Kbd` rather than something to solve at the
+callsite.
+
+**Rows are `Item`, not `ListItem`.** Both land on the same compact metrics —
+4px/8px padding — but `Item` carries its own `density` instead of taking it
+from `List` context, so a row keeps its spacing wherever it is put and the
+rail does not depend on the list above it to stay dense. The rows still
+render as `<li>` through `as="li"`, so the rail is still a list to a screen
+reader, and `Item` merges `className`, which is what lets the hover-reveal
+marker keep sitting on the row itself.
+
+**One height, two rules: beside a field, or inside a row.** Everything here
+aligns to 28px — the menubar, the tool bar, every inspector field, every row
+of the layer rail. Two different things follow from that, and conflating
+them is what makes a panel look untidy.
+
+An action standing _beside_ a field is `IconButton size="sm"`, and its 28px
+box is the whole point: the clear, the rotate pair, the per-side and
+per-corner toggles all end level with the input's top and bottom, so the row
+reads as one band rather than a field with something small floating next to
+it. The colour swatch and the image thumbnail take the same 28px square for
+the same reason — a chip beside a field is still a thing with edges, and its
+edges should be the field's.
+
+An action _inside_ a row is the exception, and the only place anything
+shrinks. A compact row spends 4px above and below, leaving 20px, and the
+smallest `IconButton` is 28px on its own — so a rail built from them
+measures 36px no matter what density says. There is no smaller size to reach
+for; the floor is the component's. The layer rail's lock is therefore a bare
+`<button>` with a 20px hit area (`styles.itemAction`), and the rail measures
+28px. Note what did _not_ change: it is still a `<button>`, so it stays
+keyboard-reachable and announced. It was `Button`'s minimum that had to go,
+not the element.
+
+**Gutters differ by panel, and the swatch borrows the field's corner.** The
+left rail sits at 8px because its rows are the content — a denser gutter
+lets the list read as a list. The inspector sits at 12px, carried by each
+`InspectorSection` rather than by the panel, which is what keeps the rules
+between sections running edge to edge: pad the panel instead and every
+divider insets by the gutter, turning a full-bleed rule into a floating
+line.
+
+The colour chips round to `--radius-element`, the same token an input
+rounds to, not `--radius-inner`. One step tighter sounds like the safer
+choice for a small square, but at 28px beside a 28px field the two curves
+read as different families; matching them is what makes the chip look like
+another control on the row rather than a tile dropped next to one.
+
+Sliders are the one control that should _not_ match. A filter row pairs a
+28px number field with a 20px rail, centred — a slider is a line to aim at,
+not a box to stack, and stretching it to the field's height would read as a
+second input.
+
+**Border, Shadow and Fill are pickers, not text fields.** Each row is now a
+value, a chip that opens a picker, and a clear that only lights up once the
+slot holds something. Astryx has no colour picker to reach for, so the
+popover is assembled from what it does have: a `Popover`, a `TextInput` for
+hex, and a `Slider` for hue.
+
+The hue rail is worth pausing on, because the obvious move is to paint it and
+that would be wrong. A spectrum rail looks like custom work, but the only
+custom thing about it is the gradient — the dragging, the arrow keys, the
+ARIA and the thumb are all just a slider. So it _is_ a `Slider`, with
+`components['slider-track']` in the template's single `defineTheme` carries
+the spectrum. That same theme is mounted narrowly around the hue Slider so
+the nine filter sliders in the panel keep the plain track they should have.
+Reach for the theming target before reaching for a `<div>`; check a component's
+`theming.targets` in its docs first.
+
+Only the saturation/value plane is painted, and only because it is two axes
+at once and no slider is. It carries `role="slider"`, arrow keys, and pointer
+capture — capture being the part worth copying, since without it a fast drag
+out of the plane stops at the edge instead of following the cursor.
+
+The picker holds HSV while it is open even though the layer stores hex. That
+is not redundancy — hex has no hue left once a colour reaches black or
+white, so a picker that round-trips through it loses your place on the rail
+the moment you drag to the bottom of the plane.
+
+Shadow reuses the same popover and adds X, Y, Blur and Spread inside it,
+because a shadow is one thing to set rather than five rows to find. And
+Shadow appears twice on a text layer on purpose: the one in Styles is the
+box's, the one in Text is the type's, and a layer can carry both.
+
+**Enumerable styling is static; only the open-ended values are dynamic.**
+Text transform, decoration, slant and alignment are closed sets, so they
+compile to real classes picked by key (`typeCase`, `typeLine`, `typeSlant`,
+`typeAlign`) rather than to a custom property written on every keystroke.
+Size, line height, colour, stroke and shadow have no such set, so those stay
+a dynamic `styles.type(…)`. Worth splitting rather than making everything
+dynamic: the static half costs nothing at runtime and shows up in devtools
+as a name instead of a variable.
+
+**Filters emit only what is off its neutral point.** Nine filter functions
+that all happen to be no-ops still force the image onto its own composited
+layer, so `filterCss` drops the ones sitting at 0 or 100 and returns `none`
+when they all are.
+
+**The image row's thumbnail opens a picker.** `FileInput` would be the
+obvious component, but it is fixed at the medium element height and this
+inspector is built on a 28px rhythm, so the picker is driven from the
+thumbnail instead and the file input itself stays hidden in the DOM. Choosing
+a file names it in the adjacent field and stops there: a template has no
+upload endpoint, and repainting the artboard from a local object URL would
+show something the template does not ship.
+
+**The canvas tool bar's end gutters match.** The trailing zoom control is a
+ghost, so edge compensation pulls it out to the card's edge to optically align
+its label — correct when the control is alone in a container, but here it left
+8px on the leading end and nothing on the trailing one. The step goes back via
+a wrapper rather than the control's own `xstyle`, because `Selector` passes
+`xstyle` to an inner node and a margin there does not move the field.
+
+**The layer rail is a `TreeList`, grouped by layer kind.** A poster's layers
+are not a flat list — the two text layers belong together and the images
+belong together — and a tree says so structurally instead of relying on sort
+order and the reader's inference. It also buys collapse for documents whose
+layer count outgrows the rail. The rows are supplied as data rather than
+composed, so `TreeList` keeps the disclosure state, the guide lines and the
+roving focus that a hand-rolled tree would have to reimplement; the lock still
+arrives through `endContent`.
+
+The per-row lock reveal survives the move because `TreeListItemData` forwards
+the `className` and `style` from `useContainerReveal` to each row. Groups take
+the frame mark rather than repeating a child's glyph, since a parent is a
+container and not another layer of that kind.
+
+**A tab's close eats into its label rather than widening the tab.** Fading a
+control that still occupies its box costs the name 20px permanently to hold
+room for something usually invisible. The close now collapses to zero width
+at rest and takes its 20px back on hover, so the space belongs to the name
+until it is needed. That requires a set tab width: with content sizing the
+label has nothing to shrink against, and revealing the close would push every
+tab to its right — the strip would reflow under the pointer and the target
+being reached for would move. The reveal is instant. Easing the width means
+the label reflows for the length of the animation, so the name wobbles every
+time the pointer crosses a tab — motion on an affordance that is only ever
+glanced at. The set width holds the longest seeded name _with_ its close
+showing, since the open document never hides one.
+
+**Tabs separate with a 16px rule, dropped either side of the open one.** A
+vertical `Divider` takes its height from the row unless given one, and the
+strip has no columns to divide — it needs the smallest mark that reads as
+"these are separate tabs". Tabs are all one width, so the rule marks a
+boundary rather than sitting midway between two labels, which is also why it
+is dropped next to the open document: that tab already reads as separate by
+its fill, and a rule running into the fill's rounded edge only crowds it. The
+rule is hidden rather than unmounted, so moving the selection does not add or
+remove a flex item and slide the whole strip sideways under the pointer that
+just clicked it. The strip carries no flex gap, since a gap applies on _both_
+sides of a rule and would leave it floating in a channel of its own instead
+of landing on the seam; the tabs have their own inner padding, so butting
+them up costs the labels nothing.
+
+**Tabs have a ceiling, not a fixed width, and the panels fold by width.** A
+tab now sits at its widest and gives ground as documents are added or the
+window narrows, spending the label's slack before truncating and stopping at
+a floor so a crowded strip scrolls rather than grinding every tab down to a
+sliver. The ceiling has to be `width` and not `flex-basis`: a basis does not
+raise an item's max-content contribution, so the strip sizes itself to the
+tabs' _content_ and then squeezes them back under their own basis, leaving
+every tab short even with the bar half empty.
+
+The strip also caps itself, because it sits in `Toolbar`'s start slot and
+that is not the slot built to give way — only the centre slot carries
+`min-width: 0`, so a start slot grows to its content and pushes the bar wider
+instead of squeezing. Widening the start slot in core would change every
+toolbar to suit one page's tab strip, so the cap is local: bar width less the
+room the menu button and the trailing save/export group need, measured in
+`cqw` against the header so it tracks the bar rather than the window. The
+new-document button moved out of the strip on the way — it is not one of the
+open documents the group is named for, and inside a scrolling strip it would
+be the first thing to scroll out of reach.
+
+The two side panels fold away below a width rather than being switched off:
+the View menu's toggles record what the user asked for, so a panel that
+vanished for room comes back on its own when the window grows. The inspector
+goes first, being the wider of the two and the one you can work without; the
+rail follows later, since knowing what is on the canvas outlasts being able
+to adjust it. Each resize handle folds with its panel, or a grip is left
+behind on a seam with nothing on the other side.
+
+**The header bar sits at 4px, not 8.** Two paddings were stacking: the
+toolbar's own gutter plus the tab strip's, putting 12px above a 28px tab and
+a 53px bar over the canvas. The bar is app chrome, so it takes the tighter
+gutter and the strip keeps its 4px, which lands the header at 45px. Note the
+floor while you are in here — `Toolbar` sets `min-height: --size-element-sm`
+and a tab is that same 28px, so no padding gets the bar below 37px.
+
+**Export is a ghost trigger.** A filled primary put the page's heaviest mark
+on the one control that is not the work — the canvas is, and the bar around
+it should stay chrome. Ghost also lets the toolbar's edge compensation do its
+job: it pulls a ghost trigger out by its own padding, so the icon lands on
+the header's gutter while the hover box still bleeds past it.
+
+**The image row's trigger is a `Thumbnail`, not a button wrapping an `img`.**
+The component already carries what the hand-rolled version was re-deriving:
+button semantics and a hover overlay from `onClick`, an accessible name and
+tooltip from `label`, and the same `--radius-element` the colour swatches
+use. It ships at 64px for media grids, so it takes a width override to join a
+row of 28px controls; the picture stays square on its own aspect ratio, so
+the height needs no help.
+
+**Icons in the rail share one colour, and unselected tabs dim whole.** Every
+rail glyph, and the strip's new-document `+`, now resolves to the secondary
+_icon_ token. That token and its
+text counterpart agree at the theme root but diverge under this editor's
+theme, so a lock keyed to the text ramp came out darker than the layer glyphs
+on its own row. Tabs dim their icon alongside their label; dimming the label
+alone left the icon at full strength and read as half-active.
+
+**An open document tab is an `Item`, and the strip is an `HStack`.** A tab
+was a `div` painting chrome around a `button` and a `span`, with its own
+radius, fill, height, gap, padding and ellipsis. It is the same object as a
+layer row — a name with a mark in front and an action behind — so it is now
+the same component, and all of that comes from `Item`: `density="compact"`
+gives the 28px box, `isSelected` the fill, `startContent` and `endContent`
+the file mark and the close, and a string `label` ellipsizes on its own.
+`Item` also ignores a click that lands on a nested button, which is what
+keeps the close from switching to the document it closes. The strip's flex,
+gap, padding, scroll and cap are all `HStack` props now.
+
+Not `TabList`, which is the component the name suggests: a `Tab` marks the
+open one with an underline rather than a fill, sizes itself to its label with
+no way to cap it from outside, and keeps both of those in spans an `xstyle`
+cannot reach.
+
+Two things stayed local. The width ceiling, because the strip sits in
+`Toolbar`'s start slot and that slot grows to its content. And the selected
+fill, because `Item` marks selection with `--color-accent-muted`, which this
+editor's theme resolves to the exact colour of the header bar in dark — the
+open document would have read as no document at all. `Item` also spaces a
+list row for reading down a column; across a tab those channels cost the name
+six characters, so the measure is tightened back to what the strip had.
+
+**Two wrapper divs went back to the layout components.** The canvas stage is
+an `HStack` — its flex box, its max-content sizing and its 100% floor on the
+block axis are props, leaving only the `min-width` HStack has no prop for.
+The zoom control's wrapper is gone entirely: a div whose only job was one
+margin is a margin the control carries itself.
+
+**A nested row action is a real `IconButton` now.** It was a hand-rolled
+20px `button` because the element scale stops at 28px and a control the
+row's own height would push a 28px row to 36. A `size="sm"` `IconButton`
+pulled in by the row's padding step on every edge lays out as 20px while
+staying 28px to the pointer: the glyph does not move, the row keeps its
+height, and the target grows to what a pointer expects. No tooltip on these
+— a bubble opening off a 28px row covers the row above it, and a padlock and
+an × already say what they do.
+
+A note if you wire the Appearance menu to a Theme of your own: a nested Theme
+recolours text but does not repaint the page behind transparent panels, so an
+explicit mode needs a surface — here a `Section` wrapping the editor — or the
+new mode's text lands on the host's old background.
diff --git a/apps/docsite/scripts/generate-scope.mjs b/apps/docsite/scripts/generate-scope.mjs
index fd3c3c52da..7341d2aa31 100644
--- a/apps/docsite/scripts/generate-scope.mjs
+++ b/apps/docsite/scripts/generate-scope.mjs
@@ -136,7 +136,7 @@ const pgClassForProp = (prop: string, value: PGStyleValue): string => {
if (value != null && typeof value === 'object') {
for (const [cond, condVal] of Object.entries(value)) {
if (condVal == null) continue;
- const decl = '.' + cls + pgPseudoSuffix(cond) + '{' + pgKebab(prop) + ':' + pgCssValue(prop, condVal) + '}';
+ const decl = pgSelector(cls, cond) + '{' + pgKebab(prop) + ':' + pgCssValue(prop, condVal) + '}';
pgInject(pgWrapAtRule(cond, decl));
}
} else {
@@ -148,6 +148,27 @@ const pgClassForProp = (prop: string, value: PGStyleValue): string => {
const pgPseudoSuffix = (cond: string): string =>
cond === 'default' || cond.startsWith('@') ? '' : cond;
+// A marker rides along as a class so an ancestor can be named in a selector.
+// Tagged with a prop key rather than a bare string because \`props\` only keeps
+// string values, and this way one shows up in className like any other class.
+const PG_MARKER_PROP = '--pg-marker';
+const PG_DEFAULT_MARKER = 'pgmarkdefault';
+let pgMarkerSeq = 0;
+const pgMarker = (cls: string): Record<string, unknown> => ({
+ $$css: true,
+ [PG_MARKER_PROP]: cls,
+});
+
+// Every other condition narrows the element's own selector, so it appends.
+// \`when.ancestor\` instead qualifies a *parent*, which has to prepend — hence a
+// tag the rule builder can spot rather than another pseudo suffix.
+const PG_ANCESTOR_TAG = '%pg-ancestor%';
+
+const pgSelector = (cls: string, cond: string): string =>
+ cond.startsWith(PG_ANCESTOR_TAG)
+ ? cond.slice(PG_ANCESTOR_TAG.length) + ' .' + cls
+ : '.' + cls + pgPseudoSuffix(cond);
+
const pgWrapAtRule = (cond: string, decl: string): string =>
cond.startsWith('@') ? cond + '{' + decl + '}' : decl;
@@ -191,6 +212,15 @@ const stylexMock = {
},
defineVars: <T extends Record<string, unknown>>(tokens: T): T => tokens,
keyframes: (kf: Record<string, Record<string, string>>) => kf,
+ defaultMarker: () => pgMarker(PG_DEFAULT_MARKER),
+ defineMarker: () => pgMarker('pgmark' + pgMarkerSeq++),
+ when: {
+ ancestor: (cond: string, marker?: Record<string, unknown>) =>
+ PG_ANCESTOR_TAG +
+ '.' +
+ ((marker?.[PG_MARKER_PROP] as string) ?? PG_DEFAULT_MARKER) +
+ cond,
+ },
types: {
angle: (v: string) => v,
color: (v: string) => v,
@@ -227,9 +257,11 @@ for (const t of SCOPE_THEMES) {
lines.push('');
// ── Theme + tokens ──────────────────────────────────────────────────
-lines.push("import {Theme} from '@astryxdesign/core/theme';");
+lines.push("import {Theme, defineTheme} from '@astryxdesign/core/theme';");
lines.push("import type {DefinedTheme} from '@astryxdesign/core/theme';");
-lines.push("import {createElement, type ComponentProps} from 'react';");
+lines.push(
+ "import {createContext, createElement, useContext, type ComponentProps} from 'react';",
+);
lines.push(
"import * as astryxTokens from '@astryxdesign/core/theme/tokens.stylex';",
);
@@ -266,7 +298,17 @@ lines.push(`const SCOPE_THEMES: Record<string, DefinedTheme> = {
${themeEntries}
};
+const IsNestedTheme = createContext(false);
+
const ControlledTheme = (props: ComponentProps<typeof Theme>) => {
+ const isNested = useContext(IsNestedTheme);
+ // A nested Theme is part of what the code being previewed is showing — a
+ // poster's display face, a slider track painted as a spectrum — so it keeps
+ // the theme and mode it asked for. Only the outermost one answers to the
+ // playground's theme and mode pickers.
+ if (isNested) {
+ return createElement(Theme, props);
+ }
const win =
typeof window !== 'undefined'
? (window as unknown as Record<string, unknown>)
@@ -275,7 +317,11 @@ const ControlledTheme = (props: ComponentProps<typeof Theme>) => {
(win?.__xds_preview_mode__ as 'light' | 'dark' | 'system') || 'system';
const themeName = (win?.__xds_preview_theme__ as string) || 'default';
const theme = SCOPE_THEMES[themeName] ?? ${SCOPE_THEMES[0].name};
- return createElement(Theme, {...props, theme, mode});
+ return createElement(
+ IsNestedTheme.Provider,
+ {value: true},
+ createElement(Theme, {...props, theme, mode}),
+ );
};`);
lines.push('');
@@ -307,7 +353,9 @@ for (const t of SCOPE_THEMES) {
}
// Theme (controlled wrapper)
-lines.push(" '@astryxdesign/core/theme': {Theme: ControlledTheme},");
+lines.push(
+ " '@astryxdesign/core/theme': {Theme: ControlledTheme, defineTheme},",
+);
// tokens.stylex
lines.push(" '@astryxdesign/core/theme/tokens.stylex': astryxTokens,");
diff --git a/apps/docsite/src/__tests__/template-preview-coverage.test.ts b/apps/docsite/src/__tests__/template-preview-coverage.test.ts
new file mode 100644
index 0000000000..4e31f270d5
--- /dev/null
+++ b/apps/docsite/src/__tests__/template-preview-coverage.test.ts
@@ -0,0 +1,29 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Guards that every template the gallery lists can actually render.
+ * @input The generated template registry and the shared preview component map.
+ * @output An invariant pairing each gallery-visible slug with a lazy component.
+ * @position Docsite regression test for `/templates` and the preview dialog.
+ */
+
+import {describe, expect, it} from 'vitest';
+import {templates} from '../generated/templateRegistry';
+import {TEMPLATE_COMPONENTS} from '../components/templateComponents';
+
+describe('template preview coverage', () => {
+ it('gives every gallery-visible template a preview component', () => {
+ // Adding a template takes two edits — the page plus a registry entry — and
+ // only the first is obvious. Miss the second and nothing errors: the card
+ // still lists from doc metadata, but TemplateThumbnail and
+ // TemplatePreviewSurface both bail on the missing slug, so the tile renders
+ // empty and the dialog apologises. Mirror the gallery's own filter so this
+ // fails for exactly the templates a reader would see broken.
+ const missing = templates
+ .filter(template => template.isReady && !template.isHiddenFromOverview)
+ .map(template => template.slug)
+ .filter(slug => !TEMPLATE_COMPONENTS[slug]);
+
+ expect(missing).toEqual([]);
+ });
+});
diff --git a/apps/docsite/src/components/templateComponents.ts b/apps/docsite/src/components/templateComponents.ts
index 15e44e04ac..a97efe2736 100644
--- a/apps/docsite/src/components/templateComponents.ts
+++ b/apps/docsite/src/components/templateComponents.ts
@@ -30,6 +30,10 @@ export const TEMPLATE_COMPONENTS: Record<
blank: lazy(
() => import('../../../../packages/cli/assets/templates/pages/blank/page'),
),
+ 'canvas-editor': lazy(
+ () =>
+ import('../../../../packages/cli/assets/templates/pages/canvas-editor/page'),
+ ),
'centered-hero': lazy(
() =>
import('../../../../packages/cli/assets/templates/pages/centered-hero/page'),
@@ -210,6 +214,10 @@ export const TEMPLATE_COMPONENTS: Record<
() =>
import('../../../../packages/cli/assets/templates/pages/table-page/page'),
),
+ 'work-item-detail': lazy(
+ () =>
+ import('../../../../packages/cli/assets/templates/pages/work-item-detail/page'),
+ ),
};
/** Resolve a template's lazy component by slug, or `undefined` if unknown. */
diff --git a/apps/template-viewer/package.json b/apps/template-viewer/package.json
index f2bf014946..310acfe1cb 100644
--- a/apps/template-viewer/package.json
+++ b/apps/template-viewer/package.json
@@ -13,6 +13,7 @@
"@astryxdesign/theme-neutral": "*",
"@heroicons/react": "^2.2.0",
"@stylexjs/stylex": "catalog:",
+ "lucide-react": "^1.18.0",
"react": "^19.2.7",
"react-dom": "^19.2.7"
},
diff --git a/apps/template-viewer/vite.config.ts b/apps/template-viewer/vite.config.ts
index c96d2e65fc..3c44af5084 100644
--- a/apps/template-viewer/vite.config.ts
+++ b/apps/template-viewer/vite.config.ts
@@ -6,6 +6,9 @@ import {astryxStylex} from '@astryxdesign/build/vite';
export default defineConfig({
plugins: [...astryxStylex(), react()],
+ // Templates that show imagery point at /template-assets/*, which the docsite
+ // serves from its own public dir. Reuse it so previews here match.
+ publicDir: '../docsite/public',
// Templates live outside this app's root (packages/cli/assets/templates).
server: {fs: {allow: ['../..']}},
});
diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.json
index d78ef6a965..4e4ae7f03c 100644
--- a/internal/shadcn-registry/routes.lock.json
+++ b/internal/shadcn-registry/routes.lock.json
@@ -4640,6 +4640,11 @@
"path": "templates/ai-chat-landing",
"aliases": []
},
+ {
+ "name": "template-canvas-editor",
+ "path": "templates/canvas-editor",
+ "aliases": []
+ },
{
"name": "template-centered-hero",
"path": "templates/centered-hero",
diff --git a/packages/cli/assets/templates/pages/canvas-editor/page.tsx b/packages/cli/assets/templates/pages/canvas-editor/page.tsx
new file mode 100644
index 0000000000..1d093f9ac8
--- /dev/null
+++ b/packages/cli/assets/templates/pages/canvas-editor/page.tsx
@@ -0,0 +1,2875 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+import {Fragment, useCallback, useRef, useState, type SVGProps} from 'react';
+import * as stylex from '@stylexjs/stylex';
+
+import {AspectRatio} from '@astryxdesign/core/AspectRatio';
+import {Card} from '@astryxdesign/core/Card';
+import {Center} from '@astryxdesign/core/Center';
+import {Divider} from '@astryxdesign/core/Divider';
+import {
+ DropdownMenu,
+ DropdownMenuCheckboxItem,
+ DropdownMenuDivider,
+ DropdownMenuItem,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSubMenu,
+} from '@astryxdesign/core/DropdownMenu';
+import {Icon, type IconType} from '@astryxdesign/core/Icon';
+import {IconButton} from '@astryxdesign/core/IconButton';
+import {Item} from '@astryxdesign/core/Item';
+import {
+ HStack,
+ Layout,
+ LayoutContent,
+ LayoutFooter,
+ LayoutHeader,
+ LayoutPanel,
+ StackItem,
+ VStack,
+} from '@astryxdesign/core/Layout';
+import {List} from '@astryxdesign/core/List';
+import {NumberInput} from '@astryxdesign/core/NumberInput';
+import {Popover} from '@astryxdesign/core/Popover';
+import {ResizeHandle, useResizable} from '@astryxdesign/core/Resizable';
+import {Section} from '@astryxdesign/core/Section';
+import {Slider} from '@astryxdesign/core/Slider';
+import {
+ SegmentedControl,
+ SegmentedControlItem,
+} from '@astryxdesign/core/SegmentedControl';
+import {Selector} from '@astryxdesign/core/Selector';
+import {Heading, Text} from '@astryxdesign/core/Text';
+import {TextArea} from '@astryxdesign/core/TextArea';
+import {TextInput} from '@astryxdesign/core/TextInput';
+import {Thumbnail} from '@astryxdesign/core/Thumbnail';
+import {TreeList, type TreeListItemData} from '@astryxdesign/core/TreeList';
+import {useContainerReveal} from '@astryxdesign/core/hooks';
+import {Theme, defineTheme} from '@astryxdesign/core/theme';
+import {Toolbar} from '@astryxdesign/core/Toolbar';
+import {neutralTheme} from '@astryxdesign/theme-neutral/built';
+import {
+ Aperture,
+ ArrowDownToLine,
+ ArrowUpToLine,
+ Baseline,
+ CaseLower,
+ CaseSensitive,
+ CaseUpper,
+ Contrast,
+ Download,
+ // Aliased: a bare `File` would shadow the DOM type the image picker reads.
+ File as FileIcon,
+ FlipHorizontal2,
+ FlipVertical2,
+ FoldVertical,
+ Frame,
+ Grip,
+ Group,
+ Image as ImageIcon,
+ Italic,
+ Lock,
+ LockOpen,
+ Menu,
+ Minus,
+ PanelBottom,
+ PanelLeft,
+ PanelLeftRightDashed,
+ PanelRight,
+ PanelTopBottomDashed,
+ Plus,
+ Redo2,
+ RotateCcw,
+ RotateCw,
+ Scan,
+ SquareSquare,
+ SquareRoundCorner,
+ Strikethrough,
+ TextAlignCenter,
+ TextAlignEnd,
+ TextAlignJustify,
+ TextAlignStart,
+ // The angle mark for the Rotation field. Not `Angle`: that landed in
+ // lucide after the version this repo pins, and a template has to build
+ // against the pack the consumer actually gets.
+ TriangleRight,
+ Type,
+ Underline,
+ Undo2,
+ X,
+} from 'lucide-react';
+
+// =============================================================================
+// Canvas editor theme
+// =============================================================================
+
+/**
+ * The template keeps its visual overrides in one theme. The artboard is artwork,
+ * not app chrome, so that theme is mounted around it with a heavy condensed
+ * display face, poster-scale type, and a light palette pinned with `mode="light"`
+ * so the poster holds when the editor goes dark.
+ *
+ * The theme owns what belongs to the poster as a whole — the face, the
+ * leading, the uppercase treatment, the frame margins. Per-layer size and
+ * tracking are not here: those belong to a layer, and the inspector edits
+ * them.
+ *
+ * Sizes here are artboard pixels, not screen pixels. The artboard always lays
+ * out at its native 1080 x 1920 and the zoom control scales the whole frame,
+ * so these stay the numbers a designer would type into the inspector.
+ */
+const canvasEditorTheme = defineTheme({
+ name: 'canvas-editor',
+ typography: {
+ // Anton is the reference face. It and the fallbacks are all single-weight
+ // blacks, so display-1 stays at weight 400 and the poster needs no
+ // webfont. Order matters: Impact outranks Arial Narrow because Arial
+ // Narrow at 400 renders thin, which reads nothing like a poster.
+ heading: {
+ family: 'Anton',
+ fallbacks: 'Haettenschweiler, Impact, "Arial Narrow", sans-serif',
+ },
+ },
+ tokens: {
+ '--text-display-1-leading': '1.02',
+ // The two spacing steps the poster lockup uses: the frame margin and the
+ // gap under the eyebrow.
+ '--spacing-6': '56px',
+ '--spacing-3': '24px',
+ },
+ components: {
+ heading: {'type:display-1': {textTransform: 'uppercase'}},
+ text: {'type:supporting': {textTransform: 'uppercase'}},
+ // The hue rail is a Slider whose track is the only custom paint. Keeping
+ // the override in this template's one theme avoids a component-only theme;
+ // the theme is mounted narrowly where the hue control and poster need it.
+ 'slider-track': {
+ base: {
+ backgroundImage:
+ 'linear-gradient(to right, #f00, #ff0, #0f0, #0ff, #00f, #f0f, #f00)',
+ },
+ },
+ },
+});
+
+// =============================================================================
+// Document
+// =============================================================================
+
+/** Artboard size in design pixels — a 9:16 social poster. */
+const FRAME = {width: 1080, height: 1920};
+
+/**
+ * Every icon on this page is 16px.
+ *
+ * Icon's own scale runs 12/16/20/24, and a page that mixes them reads as
+ * drift rather than hierarchy: the rail's layer marks, the inspector's
+ * buttons, and the canvas tools are all the same rank of thing. Button sizes
+ * its icon slot to 16px at `sm` and `md`, so this is also the size that fits
+ * the slot exactly instead of being scaled into it.
+ */
+const ICON = 'sm' as const;
+
+/**
+ * Width of the inspector's label column, in pixels.
+ *
+ * Wide enough for the longest label the panel uses at the label type size,
+ * which is what puts every control on a single left edge.
+ */
+const LABEL_COLUMN = 80;
+
+/**
+ * Widest a document tab is allowed to get, in pixels.
+ *
+ * A ceiling rather than a fixed width: it holds the longest seeded name with
+ * its close showing, and tabs fall below it as the strip fills or the window
+ * narrows.
+ */
+const TAB_MAX_WIDTH = 164;
+
+/**
+ * Room the tab strip leaves for the rest of the header, in pixels.
+ *
+ * Covers the menu button ahead of the strip, the save note and Export button
+ * after it, and the bar's own gutters. Generous rather than exact: too small
+ * and the strip crowds Export, too large and it gives up room it could have
+ * spent on tabs.
+ */
+const TAB_STRIP_RESERVE = 320;
+
+/**
+ * Width below which the inspector is folded away.
+ *
+ * It is the wider of the two panels and the one whose absence costs least:
+ * you can still see the artwork and pick layers without it. Set where the
+ * canvas would otherwise be squeezed under the artboard's own width.
+ */
+const HIDE_INSPECTOR = '@media (max-width: 1099.98px)';
+
+/**
+ * Width below which the layer rail folds away too.
+ *
+ * Later than the inspector, since knowing what is on the canvas survives
+ * longer than being able to adjust it.
+ */
+const HIDE_RAIL = '@media (max-width: 839.98px)';
+
+const PHOTO_LAYER_SRC = '/template-assets/moody-scene-vertical-1.png';
+
+type LayerKind = 'text' | 'image';
+
+/** What the Appearance submenu sets on the editor chrome. */
+type ThemeMode = 'light' | 'dark' | 'system';
+
+/** The menubar's menus, left to right. */
+/** Horizontal and vertical placement of a text layer inside its box. */
+type AlignX = 'start' | 'center' | 'end' | 'justify';
+type AlignY = 'start' | 'center' | 'end';
+type Decoration = 'none' | 'underline' | 'line-through';
+type Transform = 'none' | 'capitalize' | 'uppercase' | 'lowercase';
+
+/**
+ * The nine CSS filters the image inspector exposes, in the order they are
+ * listed there. Kept as one record so a layer carries a single `filters`
+ * object and the artboard can build a `filter` string by walking it, rather
+ * than nine optional fields that every read has to spell out.
+ */
+interface Filters {
+ blur: number;
+ brightness: number;
+ contrast: number;
+ grayscale: number;
+ hue: number;
+ invert: number;
+ opacity: number;
+ saturate: number;
+ sepia: number;
+}
+
+/** A drop shadow, in the four numbers the shadow popover edits. */
+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;
+ /**
+ * Padding is two numbers, not one: a poster's inset is almost never square,
+ * and a single field makes the common case — wide margins, tight leading
+ * above and below — impossible to express without opening a per-side
+ * editor. Inline is the left/right pair, block the top/bottom, matching the
+ * axis names CSS uses for the same thing.
+ */
+ paddingInline: number;
+ paddingBlock: number;
+ radius: number;
+ isLocked: boolean;
+ /** Copy for a text layer; the alt text for an image layer. */
+ content: string;
+ /** Undefined means the slot is empty and the field shows its placeholder. */
+ border?: string;
+ fill?: string;
+ /** The shadow cast by the layer's box. */
+ shadow?: Shadow;
+ /** Type settings. Only text layers carry them, and only they show them. */
+ family?: string;
+ weight?: string;
+ color?: string;
+ size?: number;
+ line?: number;
+ tracking?: number;
+ alignX?: AlignX;
+ alignY?: AlignY;
+ isItalic?: boolean;
+ decoration?: Decoration;
+ transform?: Transform;
+ /**
+ * The shadow cast by the glyphs, which is a different property from the
+ * one in Styles: that one is the box's, this one is the type's, and a
+ * layer can carry both.
+ */
+ textShadow?: Shadow;
+ stroke?: number;
+ /** Image settings. Only image layers carry them. */
+ fit?: string;
+ filters?: Filters;
+}
+
+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,
+};
+
+/** An open document in the strip above the menubar. */
+interface DocumentTabData {
+ id: string;
+ name: string;
+ icon: IconType;
+}
+
+// Every tab carries the same mark: varying it per document would imply a
+// distinction the editor does not make, and a strip of mixed glyphs is harder
+// to scan than a strip of one. A tab stands for an open file, so the file mark
+// is the literal one; the frame mark belongs to the layer groups, where it
+// names an actual container.
+const INITIAL_TABS: DocumentTabData[] = [
+ {id: 'poster', name: 'Salzburg poster', icon: FileIcon},
+ {id: 'brand', name: 'Brand sheet', icon: FileIcon},
+ {id: 'draft', name: 'Untitled draft', icon: FileIcon},
+];
+
+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: 'A weekend in Salzburg',
+ fill: '#111111',
+ family: 'Anton',
+ weight: 'Regular',
+ color: '#111111',
+ 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: 'March 14–16 · Austria',
+ family: 'Inter Tight',
+ weight: 'Medium',
+ color: '#111111',
+ 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: 'The Salzach river and old town rooftops at dusk',
+ fit: 'Cover',
+ filters: NO_FILTERS,
+ },
+];
+
+const LAYER_ICON = {text: Type, image: ImageIcon} as const;
+
+/** The inspector's vertical alignment, in the words a Stack uses for it. */
+const V_ALIGN = {start: 'start', center: 'center', end: 'end'} as const;
+
+// =============================================================================
+// Field glyphs
+// =============================================================================
+
+/**
+ * Draws a letterform sized to the icon grid.
+ *
+ * A design tool names a numeric field from inside it — the X sits in the box
+ * with the number, not in a segment bolted to its edge — so the row reads as
+ * one control. That is the input's start-icon slot, which takes an SVG
+ * component; Lucide ships no letterforms, so these are drawn on the same 24px
+ * grid Lucide uses. They inherit `currentColor` and the slot's sizing, so a
+ * letter and an icon are interchangeable in the same position.
+ */
+function glyph(char: string): IconType {
+ const Glyph = (props: SVGProps<SVGSVGElement>) => (
+ <svg viewBox="0 0 24 24" {...props}>
+ <text
+ x={12}
+ y={12}
+ fill="currentColor"
+ // Two-letter glyphs get the smaller size so both fit the same box.
+ fontSize={char.length > 1 ? 13 : 17}
+ fontWeight={500}
+ textAnchor="middle"
+ dominantBaseline="central">
+ {char}
+ </text>
+ </svg>
+ );
+ Glyph.displayName = `Glyph(${char})`;
+ return Glyph;
+}
+
+/**
+ * Built once at module scope so each glyph keeps a stable component identity.
+ *
+ * Only the axis fields are lettered. A letter is the right mark when the
+ * field names a *dimension* a reader already has a letter for — X, Y, W, H
+ * are how the value is written down anyway. Where the pack has a drawing of
+ * the thing being set (an angle, a pair of insets, a rounded corner), the
+ * drawing says it in one glance and the letter makes you translate.
+ */
+const GLYPH = {
+ x: glyph('X'),
+ y: glyph('Y'),
+ width: glyph('W'),
+ height: glyph('H'),
+} as const;
+
+/**
+ * Each preset carries its own icon. A library where every row shows the same
+ * glyph is a list you have to read word by word; distinct marks let the eye
+ * find the row it wants.
+ */
+const EFFECT_PRESETS: {label: string; icon: IconType}[] = [
+ {label: 'Grain overlay', icon: Aperture},
+ {label: 'Halftone', icon: Grip},
+ {label: 'Duotone teal', icon: Contrast},
+];
+
+/**
+ * The icon-only segmented rows in the text inspector. Each entry keeps its
+ * spoken label next to its glyph, because `isLabelHidden` hides the text but
+ * still needs it for the accessible name.
+ */
+const ALIGN_X: {value: AlignX; label: string; icon: IconType}[] = [
+ {value: 'start', label: 'Align left', icon: TextAlignStart},
+ {value: 'center', label: 'Align centre', icon: TextAlignCenter},
+ {value: 'end', label: 'Align right', icon: TextAlignEnd},
+ {value: 'justify', label: 'Justify', icon: TextAlignJustify},
+];
+
+const ALIGN_Y: {value: AlignY; label: string; icon: IconType}[] = [
+ {value: 'start', label: 'Align top', icon: ArrowUpToLine},
+ {value: 'center', label: 'Align middle', icon: FoldVertical},
+ {value: 'end', label: 'Align bottom', icon: ArrowDownToLine},
+];
+
+const DECORATIONS: {value: Decoration; label: string; icon: IconType}[] = [
+ {value: 'none', label: 'No decoration', icon: CaseSensitive},
+ {value: 'underline', label: 'Underline', icon: Underline},
+ {value: 'line-through', label: 'Strikethrough', icon: Strikethrough},
+];
+
+const TRANSFORMS: {value: Transform; label: string; icon: IconType}[] = [
+ {value: 'none', label: 'As typed', icon: Minus},
+ {value: 'capitalize', label: 'Capitalise', icon: CaseSensitive},
+ {value: 'uppercase', label: 'Uppercase', icon: CaseUpper},
+ {value: 'lowercase', label: 'Lowercase', icon: CaseLower},
+];
+
+/**
+ * The nine image filters, with the range and unit each one is stated in.
+ * `max` is what the slider runs to rather than what CSS allows — brightness
+ * and saturate go past 200%, but a rail that reaches 500 spends most of its
+ * travel somewhere nobody drags to.
+ */
+const FILTERS: {
+ 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'];
+
+/** What the Insert submenu can add to the artboard. */
+const INSERT_ITEMS: {label: string; icon: IconType}[] = [
+ {label: 'Frame', icon: Frame},
+ {label: 'Group', icon: Group},
+ {label: 'Text', icon: Type},
+ {label: 'Image', icon: ImageIcon},
+];
+
+/** Written once: the Export button and the File menu offer the same three. */
+const EXPORT_FORMATS = [
+ 'PNG · 1080 × 1920',
+ 'JPG · 1080 × 1920',
+ 'PDF · print ready',
+];
+
+const EXPORT_MENU = EXPORT_FORMATS.map(label => ({label}));
+
+// =============================================================================
+// Colour
+// =============================================================================
+
+/** A colour as the picker holds it: hue 0–360, saturation and value 0–100. */
+interface Hsv {
+ h: number;
+ s: number;
+ v: number;
+}
+
+/**
+ * The picker thinks in HSV because that is the shape of its two controls — a
+ * hue rail and a saturation/value plane — while every value it reads and
+ * writes is a hex string. These convert between the two.
+ */
+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),
+ };
+}
+
+/**
+ * Drag tracking for the saturation/value plane, which is the one control
+ * here that has to be painted: it is two axes at once, and no slider is.
+ * Reports the pointer as a fraction of the element on press and for as long
+ * as the drag lasts.
+ *
+ * Pointer capture is what makes the drag survive leaving the element: a fast
+ * diagonal out of the plane keeps tracking instead of stopping dead at the
+ * edge, which is the difference between a picker that feels attached to the
+ * cursor and one that keeps dropping it.
+ */
+function usePointerTrack(onTrack: (x: number, y: number) => void) {
+ const read = useCallback(
+ (event: React.PointerEvent<HTMLElement>) => {
+ const box = event.currentTarget.getBoundingClientRect();
+ onTrack(
+ Math.min(1, Math.max(0, (event.clientX - box.left) / box.width)),
+ Math.min(1, Math.max(0, (event.clientY - box.top) / box.height)),
+ );
+ },
+ [onTrack],
+ );
+ return {
+ onPointerDown: (event: React.PointerEvent<HTMLElement>) => {
+ event.currentTarget.setPointerCapture(event.pointerId);
+ read(event);
+ },
+ onPointerMove: (event: React.PointerEvent<HTMLElement>) => {
+ if (event.currentTarget.hasPointerCapture(event.pointerId)) {
+ read(event);
+ }
+ },
+ };
+}
+
+/**
+ * Builds the `filter` shorthand from the nine values the inspector edits.
+ *
+ * Only the ones that are off their neutral point are emitted: a filter list
+ * of nine no-op functions still forces the image onto its own composited
+ * layer, and a poster that is only ever blurred should not pay for the other
+ * eight.
+ */
+function filterCss(filters: Filters): string {
+ const parts = [
+ ['blur', filters.blur, 0, 'px'],
+ ['brightness', filters.brightness, 100, '%'],
+ ['contrast', filters.contrast, 100, '%'],
+ ['grayscale', filters.grayscale, 0, '%'],
+ ['hue-rotate', filters.hue, 0, 'deg'],
+ ['invert', filters.invert, 0, '%'],
+ ['opacity', filters.opacity, 100, '%'],
+ ['saturate', filters.saturate, 100, '%'],
+ ['sepia', filters.sepia, 0, '%'],
+ ] as const;
+ const active = parts
+ .filter(([, value, neutral]) => value !== neutral)
+ .map(([name, value, , unit]) => `${name}(${value}${unit})`);
+ return active.length > 0 ? active.join(' ') : 'none';
+}
+
+/** `text-shadow` takes no spread, so a text layer's shadow drops it. */
+function shadowCss(shadow: Shadow | undefined): string {
+ return shadow
+ ? `${shadow.x}px ${shadow.y}px ${shadow.blur}px ${shadow.color}`
+ : 'none';
+}
+
+// =============================================================================
+// Styles
+// =============================================================================
+
+const styles = stylex.create({
+ // Zoom the way a design tool does: lay the artboard out once at its native
+ // size and scale the painted result. Type and spacing stay in artboard
+ // pixels, and the poster gets no reflow between zoom steps.
+ artboard: (scale: number) => ({
+ width: FRAME.width,
+ transform: `scale(${scale})`,
+ transformOrigin: 'top left',
+ }),
+ // Type the inspector owns. Size and tracking can't be theme tokens: they
+ // belong to a layer, not to the poster, and they change per keystroke.
+ // Tracking is a percentage of the type size, the way a design tool states
+ // it, so it holds when the size changes.
+ type: (
+ size: number,
+ tracking: number,
+ line: number,
+ color: string,
+ stroke: number,
+ shadow: string,
+ ) => ({
+ fontSize: `${size}px`,
+ letterSpacing: `${tracking / 100}em`,
+ lineHeight: `${line}%`,
+ color,
+ WebkitTextStrokeWidth: stroke > 0 ? `${stroke}px` : null,
+ WebkitTextStrokeColor: stroke > 0 ? color : null,
+ textShadow: shadow,
+ }),
+ // AspectRatio's `fit` stretches every direct child to fill the box, so a
+ // second one would flow below the photo and clip. Taking the text layers
+ // out of flow is what stacks them over it, the way they sit on an artboard.
+ textLayers: {position: 'absolute', inset: 0},
+ // A Card given a height prop turns into a scroll container, which is the
+ // right default for a card holding more copy than fits. This one is a
+ // viewport onto an artboard that is deliberately larger than its frame —
+ // the artboard lays out at 1080 wide at every zoom step and the frame
+ // scales it — so it clips instead. `clip` over `hidden`: nothing here
+ // should scroll, including the quiet scroll that focusing a clipped child
+ // would otherwise cause.
+ artboardFrame: {overflow: 'clip'},
+ // The canvas pans in both axes, which centring normally breaks.
+ //
+ // A scroll port that centres with `justify-content`/`align-items` has no
+ // scrollable overflow on the *start* side: once the artboard is bigger than
+ // the port, its top-left is pushed out and nothing can scroll back to it.
+ // Auto margins centre the same way while leaving that overflow reachable —
+ // when there is spare room they split it, and when there is none they
+ // resolve to zero instead of pushing.
+ //
+ // The stage sizes to whichever is larger, the port or the artboard, so the
+ // scrollbars describe the artboard rather than the port.
+ // The one part HStack has no prop for; the rest of the stage — the flex
+ // box, the max-content sizing and the 100% floor on the block axis — says
+ // itself in props.
+ canvasStage: {minWidth: '100%'},
+ artboardCentered: {margin: 'auto'},
+ // Concentric corners. The card rounds to --radius-container and holds one
+ // spacing step of padding, so the controls inside it round to the
+ // difference: an inner corner struck from the same centre as the outer one
+ // rather than a rounder curve cutting across it. Stated as the subtraction
+ // so it still holds if either token moves.
+ toolBarControl: {
+ borderRadius: 'calc(var(--radius-container) - var(--spacing-1))',
+ },
+ // The trailing control is a ghost, so edge compensation pulls it out to the
+ // card's edge to optically align its label. That is the right call when the
+ // control is the only thing in a container, but here it leaves the bar with
+ // a gutter on the left and none on the right. Putting the step back matches
+ // the two ends. It rides on the control itself rather than a wrapper — a
+ // div whose only job is one margin is a div the control can absorb.
+ toolBarTrailing: {
+ marginInlineEnd: 'var(--spacing-2)',
+ },
+ // A vertical Divider is `height: 100%`, and a flex row that centres its
+ // items gives a percentage height nothing to resolve against — the rule
+ // collapses to nothing and the tool bar loses its groups. Stretching the
+ // item is what gives it a height; the inset then pulls it back off the
+ // buttons so it separates them rather than boxing them in.
+ toolBarRule: {
+ alignSelf: 'stretch',
+ height: 'auto',
+ marginBlock: 'var(--spacing-1)',
+ },
+ // Give the header bar its own inline padding, so the Export button stops
+ // at a margin instead of the window edge.
+ //
+ // The layout under it is set to zero padding — the panels have to reach
+ // the edges — and a Toolbar takes its inline padding from whatever
+ // container it sits in, so it inherits that zero. The fix has to arrive as
+ // Section's padding token rather than as `paddingInline`: Section renders
+ // an outer wrapper that escapes its parent's gutter and an inner one that
+ // holds the padding, xstyle lands on the outer, and padding set there
+ // makes the bar bleed 12px past the window rather than inset its contents.
+ // The token is read on the inner element, where it also republishes
+ // --container-padding-inline-*. That second effect is the one that
+ // matters: it feeds the toolbar's edge compensation, which pulls ghost
+ // triggers back out by their own padding so the menu button's *icon* lines
+ // up on the gutter while its hover box still bleeds into it.
+ headerBar: {
+ // Named so the tab strip can size against the bar rather than the window:
+ // cqw tracks this element, so it stays right if the bar ever stops being
+ // full-bleed, and it excludes a scrollbar the way vw does not.
+ containerType: 'inline-size',
+ containerName: 'editor-header',
+ },
+ // The menu, the tabs and the add button. It has to be allowed to shrink or
+ // the strip's own ceiling never binds — a flex item defaults to min-width
+ // auto, which floors it at the tabs' combined width.
+ headerLead: {
+ minWidth: 0,
+ },
+ // The open-document strip above the menubar. It scrolls rather than wraps:
+ // a second row of tabs would move the menubar down, and the whole point of
+ // the strip is that the chrome above the canvas has a fixed height.
+ tabStrip: {
+ minWidth: 0,
+ flexShrink: 1,
+ // The strip has to cap itself, which is the one thing HStack's maxWidth
+ // cannot say for it. It sits in Toolbar's start slot, and that slot is
+ // not the one built to give way — only the centre slot carries
+ // `min-width: 0`, so a start slot grows to its content and pushes the bar
+ // wider instead of squeezing. Widening the start slot in core would
+ // change every toolbar's behaviour to suit one page's tab strip, so the
+ // cap arrives as a maxWidth prop and this only has to let it shrink.
+ //
+ // The strip is short enough that a scrollbar would eat most of it, and
+ // the tabs are draggable-looking targets already.
+ scrollbarWidth: 'none',
+ },
+ // Folded by width, not by the View menu's toggles. Those record what the
+ // user asked for; this records whether there is room to honour it, so the
+ // panel comes back on its own when the window grows rather than leaving
+ // the toggle switched off. Applied to the handle as well as the panel, or
+ // a grip is left behind on a seam with nothing on the other side.
+ foldsAtRail: {display: {default: null, [HIDE_RAIL]: 'none'}},
+ foldsAtInspector: {display: {default: null, [HIDE_INSPECTOR]: 'none'}},
+ // A short rule, not a full-height one: the strip has no columns to divide,
+ // it only needs the smallest mark that reads as "these are separate tabs".
+ // A vertical Divider takes its height from the row unless given one, and a
+ // centred 16px keeps it clear of both the tab fill and the bar's own edges.
+ tabRule: {height: 16, alignSelf: 'center', flexShrink: 0},
+ tabRuleHidden: {visibility: 'hidden'},
+ // Everything a tab needs beyond an Item: a width ceiling and a tighter
+ // measure. Item brings the 28px box, the radius, the fill when selected,
+ // the inline padding, and the ellipsis on a string label.
+ tab: {
+ // Item spaces a list row, where 8px either side of the label is right
+ // because the rows are stacked and the eye reads down a column. A tab is
+ // read across, and at this ceiling those three 8px channels cost the
+ // name six characters: "Salzburg poster" needs 102px and would get 96.
+ // Back to the measure the strip had before, which clears it with 2px
+ // spare — the close end tighter still, because a bare 20px icon carries
+ // its own inset and an equal gap there reads as a wider one.
+ gap: 'var(--spacing-1-5)',
+ paddingInlineEnd: 'var(--spacing-1)',
+ // A width the tab is allowed to shrink under, which makes it a ceiling:
+ // it never grows, so it sits at this size until something squeezes it.
+ // It has to be `width` and not `flexBasis` — a basis does not raise an
+ // item's max-content contribution, so the strip above would size itself
+ // to the tabs' *content* and then squeeze them back under their basis,
+ // leaving every tab short even with the bar half empty.
+ flexGrow: 0,
+ flexShrink: 1,
+ width: TAB_MAX_WIDTH,
+ // A floor, so a crowded strip scrolls instead of grinding every tab down
+ // to an unreadable sliver. Enough for the mark, a few characters and the
+ // close; past it the strip's own overflow takes over.
+ minWidth: 96,
+ },
+ // Item marks a selected row with --color-accent-muted, which this editor's
+ // theme resolves to #262626 in dark — the exact colour of the header bar
+ // the strip sits on, so the open document would read as no document at
+ // all. The muted background is a step off the bar in both schemes, and it
+ // is the fill hover already uses, so selection and hover agree.
+ tabSelected: {backgroundColor: 'var(--color-background-muted)'},
+ // Item paints a fill when selected but leaves hover to the list that owns
+ // it, and the strip is not a list. The tab is a target on its own, so it
+ // answers the pointer itself.
+ tabHover: {
+ backgroundColor: {
+ default: 'transparent',
+ ':hover': 'var(--color-background-muted)',
+ },
+ },
+ // Hold the label column at its set width. The fields beside it carry the
+ // flex min-width reset, so without this the row spends its shrinkage on
+ // whichever item gives way first and each label ends up a different width —
+ // which is exactly the shared left edge the panel is built around.
+ labelColumn: {flexShrink: 0},
+ // An action nested *inside* a row, as opposed to one standing beside a
+ // field. This is the only place a control drops below the 28px the rest
+ // of the panel aligns to.
+ //
+ // It has to: the smallest IconButton is 28px, which is the whole row's
+ // height budget once compact density adds its 4px above and below, so a
+ // rail of 28px rows cannot hold a 28px button. Hence a bare button — no
+ // painted box, no size floor, just a hit area around the icon. It stays a
+ // <button> because the lock is a real action that has to remain
+ // keyboard-reachable; it was the Button *component's* minimum that had to
+ // go, not the element.
+ itemAction: {
+ // A full 28px button laid out as 20px. The row is 28px with a step of
+ // padding, so a control its own height would push it to 36; pulling that
+ // same step off every edge hands the padding back to the layout. The
+ // glyph does not move — centred in a 28px box that now starts a step
+ // early, it lands exactly where a 20px button would have put it — but
+ // the target it sits in is the full 28px the pointer expects.
+ //
+ // Stated against the row's own padding token rather than as -4px, so the
+ // two cannot drift apart.
+ margin: 'calc(-1 * var(--spacing-1))',
+ // Icon tokens, not the text ones a ghost Button reaches for. The two
+ // agree at the theme root but this editor's theme separates them, and a
+ // lock keyed to the text ramp came out darker than the layer glyphs
+ // sitting beside it on the same row.
+ color: {
+ default: 'var(--color-icon-secondary)',
+ ':hover': 'var(--color-icon-primary)',
+ ':disabled': 'var(--color-icon-disabled)',
+ },
+ },
+ // The colour chip that opens a picker. Square at the field's own height
+ // and rounded to the field's own corner, so it reads as another control
+ // on the row rather than a tile dropped beside one. --radius-element is
+ // the token an input rounds to; --radius-inner is a step tighter and
+ // reads as a different family at this size.
+ swatch: {
+ width: 'var(--spacing-7)',
+ height: 'var(--spacing-7)',
+ flexShrink: 0,
+ padding: 0,
+ borderWidth: '1px',
+ borderStyle: 'solid',
+ borderColor: 'var(--color-border-emphasized)',
+ borderRadius: 'var(--radius-element)',
+ cursor: 'pointer',
+ // A chip for an unset slot reads as empty rather than as black.
+ backgroundImage:
+ 'linear-gradient(45deg, transparent 45%, var(--color-border-emphasized) 45% 55%, transparent 55%)',
+ },
+ swatchFilled: {backgroundImage: 'none'},
+ // The saturation/value plane. White runs left to right and black bottom to
+ // top over the pure hue, so every point in the square is one colour at
+ // that hue.
+ plane: {
+ position: 'relative',
+ height: 160,
+ borderRadius: 'var(--radius-inner)',
+ backgroundImage:
+ 'linear-gradient(to top, #000, transparent), linear-gradient(to right, #fff, transparent)',
+ cursor: 'crosshair',
+ touchAction: 'none',
+ },
+ // Both thumbs are positioned by their centre, so the translate is what
+ // keeps them on the value rather than beside it.
+ thumb: {
+ position: 'absolute',
+ width: 'var(--spacing-3)',
+ height: 'var(--spacing-3)',
+ borderWidth: '2px',
+ borderStyle: 'solid',
+ borderColor: '#fff',
+ borderRadius: 'var(--radius-full)',
+ boxShadow: '0 0 0 1px rgba(0, 0, 0, 0.35)',
+ transform: 'translate(-50%, -50%)',
+ pointerEvents: 'none',
+ },
+ planeStack: {display: 'grid', gap: 'var(--spacing-3)'},
+ // Filter rows put the slider beside the number rather than under it, so
+ // nine of them still read as one column.
+ //
+ // The slider takes the fill and the number trails it at a fixed width: the
+ // slider is the control being used and the number is the read-out, so the
+ // draggable track gets the room. Fixed rather than hugging, so nine
+ // read-outs share one right edge instead of stepping in and out as their
+ // values change width.
+ filterValue: {flexShrink: 0, width: 64},
+ // Thumbnail ships at 64px for media grids; here it is a control sitting in
+ // a row of 28px controls, so it takes the same box as the colour swatches.
+ // Width alone is enough — the picture is kept square by an aspect ratio.
+ sourceThumbnail: {width: 'var(--spacing-7)'},
+});
+
+/**
+ * The enumerable half of a text layer's styling. These are closed sets, so
+ * they compile to static classes picked by key rather than to a custom
+ * property set at runtime.
+ */
+const typeCase = stylex.create({
+ none: {textTransform: 'none'},
+ capitalize: {textTransform: 'capitalize'},
+ uppercase: {textTransform: 'uppercase'},
+ lowercase: {textTransform: 'lowercase'},
+});
+
+const typeLine = stylex.create({
+ none: {textDecorationLine: 'none'},
+ underline: {textDecorationLine: 'underline'},
+ 'line-through': {textDecorationLine: 'line-through'},
+});
+
+const typeSlant = stylex.create({
+ normal: {fontStyle: 'normal'},
+ italic: {fontStyle: 'italic'},
+});
+
+const typeAlign = stylex.create({
+ start: {textAlign: 'start'},
+ center: {textAlign: 'center'},
+ end: {textAlign: 'end'},
+ justify: {textAlign: 'justify'},
+});
+
+/** Runtime values the painted controls need, kept out of the static sheet. */
+const paint = stylex.create({
+ photo: (filter: string) => ({filter}),
+ hue: (h: number) => ({backgroundColor: `hsl(${h} 100% 50%)`}),
+ planeThumb: (s: number, v: number) => ({
+ insetInlineStart: `${s}%`,
+ insetBlockStart: `${100 - v}%`,
+ }),
+ fill: (color: string) => ({backgroundColor: color}),
+});
+
+// =============================================================================
+// Panel building blocks
+// =============================================================================
+
+/**
+ * One inspector row: a fixed label column, then the controls for it.
+ *
+ * The label column is a set width rather than intrinsic so that every control
+ * in the panel starts on the same vertical line, whatever its label is
+ * called. That shared edge is what lets the eye run down the column and
+ * compare values instead of hunting for each field.
+ */
+function InspectorRow({
+ label,
+ hAlign,
+ labelWidth = LABEL_COLUMN,
+ children,
+}: {
+ label: string;
+ /** Set to "end" for a row of bare buttons, which have no field to fill. */
+ hAlign?: 'start' | 'end';
+ /** Narrower inside a popover, where the panel's column would not fit. */
+ labelWidth?: number;
+ children: React.ReactNode;
+}) {
+ return (
+ <HStack gap={2} vAlign="center">
+ <HStack width={labelWidth} xstyle={styles.labelColumn}>
+ <Text type="label" color="secondary" maxLines={1}>
+ {label}
+ </Text>
+ </HStack>
+ <StackItem size="fill">
+ <HStack gap={1} vAlign="center" hAlign={hAlign}>
+ {children}
+ </HStack>
+ </StackItem>
+ </HStack>
+ );
+}
+
+/** A numeric field that names itself from inside, like X 40. */
+function AxisInput({
+ icon,
+ label,
+ value,
+ onChange,
+}: {
+ icon: IconType;
+ label: string;
+ value: number;
+ onChange: (next: number) => void;
+}) {
+ return (
+ <StackItem size="fill">
+ <NumberInput
+ label={label}
+ isLabelHidden
+ startIcon={icon}
+ size="sm"
+ value={value}
+ onChange={onChange}
+ isWheelEnabled={false}
+ />
+ </StackItem>
+ );
+}
+
+/**
+ * A numeric row with the steppers showing. Size, line height and letter
+ * spacing get them because they are values you arrive at by nudging rather
+ * than by typing a number you already know.
+ */
+function StepperRow({
+ label,
+ value,
+ onChange,
+}: {
+ label: string;
+ value: number;
+ onChange: (next: number) => void;
+}) {
+ return (
+ <InspectorRow label={label}>
+ <StackItem size="fill">
+ <NumberInput
+ label={label}
+ isLabelHidden
+ size="sm"
+ hasNumberSteppers
+ value={value}
+ onChange={onChange}
+ isWheelEnabled={false}
+ />
+ </StackItem>
+ </InspectorRow>
+ );
+}
+
+/**
+ * One image filter: the number and the rail that drags it.
+ *
+ * Both are wired to the same value, which is the point — you drag to find
+ * the look and read the number to reproduce it, and nine of these read as
+ * one column because the rail is fixed-width instead of filling.
+ */
+function FilterRow({
+ filter,
+ value,
+ onChange,
+}: {
+ filter: (typeof FILTERS)[number];
+ value: number;
+ onChange: (next: number) => void;
+}) {
+ return (
+ <InspectorRow label={filter.label}>
+ <StackItem size="fill">
+ <Slider
+ label={`${filter.label} slider`}
+ isLabelHidden
+ min={0}
+ max={filter.max}
+ value={value}
+ onChange={onChange}
+ valueDisplay="none"
+ />
+ </StackItem>
+ <NumberInput
+ label={filter.label}
+ isLabelHidden
+ size="sm"
+ min={0}
+ max={filter.max}
+ value={value}
+ onChange={onChange}
+ isWheelEnabled={false}
+ xstyle={styles.filterValue}
+ />
+ </InspectorRow>
+ );
+}
+
+/** An inspector group: a caption, its rows, and a closing divider. */
+function InspectorSection({
+ title,
+ children,
+}: {
+ title: string;
+ children: React.ReactNode;
+}) {
+ return (
+ // The panel itself stays at zero padding and each section carries the
+ // gutter instead. That is what keeps the rules between sections running
+ // edge to edge: pad the panel and every divider insets by the gutter,
+ // turning a full-bleed rule into a floating line.
+ <Section padding={3} dividers={['bottom']}>
+ <VStack gap={3}>
+ <Text type="label" weight="semibold">
+ {title}
+ </Text>
+ {children}
+ </VStack>
+ </Section>
+ );
+}
+
+/**
+ * An action nested inside a list row: an icon you can click, not a button
+ * with an icon in it.
+ *
+ * This is the exception, not the pattern. An action standing beside a field
+ * uses `IconButton size="sm"`, so its 28px box lines up with the input's
+ * and the row reads as one band. Only an action *inside* a 28px row shrinks,
+ * because the row has no space for a control its own height. See
+ * `styles.itemAction`.
+ */
+function ItemAction({
+ label,
+ icon,
+ isDisabled,
+ onClick,
+ xstyle,
+ className,
+ style,
+}: {
+ label: string;
+ icon: IconType;
+ isDisabled?: boolean;
+ onClick?: () => void;
+ xstyle?: stylex.StyleXStyles;
+ className?: string;
+ style?: React.CSSProperties;
+}) {
+ return (
+ <IconButton
+ label={label}
+ // No tooltip. These sit in 28px rows, and a bubble opening off one
+ // covers the row above it — a lot of chrome for a padlock and an ×
+ // that already say what they do. `label` still names them for anyone
+ // reading the rail through assistive tech.
+ icon={<Icon icon={icon} size={ICON} />}
+ variant="ghost"
+ size="sm"
+ isDisabled={isDisabled}
+ onClick={onClick}
+ xstyle={[styles.itemAction, xstyle]}
+ className={className}
+ style={style}
+ />
+ );
+}
+
+/**
+ * One open document in the strip above the menubar.
+ *
+ * An open document is the same kind of thing as a layer: a name with a mark
+ * in front of it and an action behind, which is why this is the same Item
+ * the rail is built from rather than a tab. Item ellipsizes a string label
+ * on its own, so the width ceiling below is the only thing left to say, and
+ * it ignores a click that lands on a nested button — that is what stops the
+ * close from also switching to the document it is closing.
+ *
+ * Not TabList: a Tab marks the open one with an underline rather than a
+ * fill, sizes itself to its label with no way to cap it from out here, and
+ * keeps both of those in spans an xstyle cannot reach.
+ *
+ * The close follows the same rule as the layer rail's lock: hidden until the
+ * tab is hovered or holds focus, and pinned open on the active tab, which is
+ * the one whose close a user reaches for. Because it only fades, the tab does
+ * not change width when the control arrives.
+ */
+function DocumentTab({
+ tab,
+ isActive,
+ onSelect,
+ onClose,
+}: {
+ tab: DocumentTabData;
+ isActive: boolean;
+ onSelect: () => void;
+ onClose: () => void;
+}) {
+ const {getContainerProps, getContentRevealProps} = useContainerReveal();
+
+ return (
+ <Item
+ label={tab.name}
+ density="compact"
+ isSelected={isActive}
+ onClick={onSelect}
+ aria-current={isActive ? 'true' : undefined}
+ {...getContainerProps()}
+ startContent={
+ <Icon
+ icon={tab.icon}
+ size={ICON}
+ color={isActive ? 'primary' : 'secondary'}
+ />
+ }
+ endContent={
+ <ItemAction
+ label={`Close ${tab.name}`}
+ icon={X}
+ onClick={onClose}
+ {...getContentRevealProps({
+ forceVisibility: isActive ? 'shown' : undefined,
+ })}
+ />
+ }
+ // Both fills land after Item's own, which is what lets the selected one
+ // be replaced; they stay mutually exclusive so hover cannot erase it.
+ xstyle={[styles.tab, isActive ? styles.tabSelected : styles.tabHover]}
+ />
+ );
+}
+
+/**
+ * The saturation/value plane, the hue rail, and the hex field, which are the
+ * three ways the same colour gets said.
+ *
+ * The plane and the rail are painted rather than composed: a two-dimensional
+ * gradient and a rainbow track are not controls the system ships, and a
+ * Slider styled into a hue rail would still only give one of the two axes.
+ * They carry `role="slider"` with arrow keys so the picker is not
+ * pointer-only, and the hex field is the exact route for anyone who already
+ * knows the value.
+ *
+ * HSV lives here rather than on the layer. A layer stores a hex string —
+ * that is what the artboard paints — but hex has no hue to slide once the
+ * colour reaches black or white, so the picker keeps the HSV it is working
+ * in for as long as it is open.
+ */
+function ColorPicker({
+ value,
+ onChange,
+}: {
+ value: string;
+ onChange: (next: string) => void;
+}) {
+ const [hsv, setHsv] = useState(() => hexToHsv(value));
+ const [draft, setDraft] = useState(value);
+
+ const commit = useCallback(
+ (next: Hsv) => {
+ setHsv(next);
+ const hex = hsvToHex(next);
+ setDraft(hex);
+ onChange(hex);
+ },
+ [onChange],
+ );
+
+ const planeTrack = usePointerTrack(
+ useCallback(
+ (x, y) =>
+ commit({...hsv, s: Math.round(x * 100), v: Math.round(100 - y * 100)}),
+ [commit, hsv],
+ ),
+ );
+ /** Arrow keys on the plane: left/right saturate, up/down brighten. */
+ const nudge = (event: React.KeyboardEvent) => {
+ const sign =
+ event.key === 'ArrowRight' || event.key === 'ArrowUp'
+ ? 1
+ : event.key === 'ArrowLeft' || event.key === 'ArrowDown'
+ ? -1
+ : 0;
+ if (sign === 0) {
+ return;
+ }
+ event.preventDefault();
+ const horizontal = event.key === 'ArrowRight' || event.key === 'ArrowLeft';
+ const clamp = (n: number) => Math.min(100, Math.max(0, n));
+ commit({
+ h: hsv.h,
+ s: clamp(hsv.s + (horizontal ? sign * 2 : 0)),
+ v: clamp(hsv.v + (horizontal ? 0 : sign * 2)),
+ });
+ };
+
+ return (
+ <div {...stylex.props(styles.planeStack)}>
+ <div
+ role="slider"
+ tabIndex={0}
+ aria-label="Saturation and brightness"
+ aria-valuetext={`${hsv.s}% saturation, ${hsv.v}% brightness`}
+ aria-valuenow={hsv.s}
+ aria-valuemin={0}
+ aria-valuemax={100}
+ onKeyDown={nudge}
+ {...planeTrack}
+ {...stylex.props(styles.plane, paint.hue(hsv.h))}>
+ <span
+ {...stylex.props(
+ styles.thumb,
+ paint.planeThumb(hsv.s, hsv.v),
+ paint.fill(hsvToHex(hsv)),
+ )}
+ />
+ </div>
+ {/* The hue rail is a real Slider with its track repainted, not a
+ hand-rolled one: the rainbow is the only thing about it that is not
+ already a Slider, and `slider-track` is a theming target. The template's
+ one custom theme is mounted narrowly here so the nine filter sliders in
+ the same panel keep the plain track they should have. */}
+ <Theme theme={canvasEditorTheme}>
+ <Slider
+ label="Hue"
+ isLabelHidden
+ min={0}
+ max={360}
+ value={hsv.h}
+ // Annotated because Slider's props are a union of the single and
+ // range forms, and with no `value` tuple to discriminate on there is
+ // nothing for the parameter to infer from.
+ onChange={(h: number) => commit({...hsv, h})}
+ valueDisplay="none"
+ />
+ </Theme>
+ <TextInput
+ label="Hex"
+ isLabelHidden
+ size="sm"
+ value={draft}
+ onChange={next => {
+ setDraft(next);
+ if (/^#?[\da-f]{6}$/i.test(next.trim())) {
+ setHsv(hexToHsv(next));
+ onChange(next.startsWith('#') ? next : `#${next}`);
+ }
+ }}
+ />
+ </div>
+ );
+}
+
+/**
+ * The chip that opens a picker. Twenty pixels square, so a row carrying one
+ * still measures 28.
+ */
+function Swatch({
+ label,
+ value,
+ onChange,
+ children,
+}: {
+ label: string;
+ value?: string;
+ onChange: (next: string) => void;
+ children?: React.ReactNode;
+}) {
+ return (
+ <Popover
+ label={label}
+ placement="start"
+ alignment="start"
+ width={248}
+ content={
+ <VStack gap={3}>
+ <Text type="label" weight="semibold">
+ {label}
+ </Text>
+ <ColorPicker value={value ?? '#ffffff'} onChange={onChange} />
+ {children}
+ </VStack>
+ }>
+ <button
+ type="button"
+ aria-label={`${label}${value ? `, ${value}` : ', not set'}`}
+ {...stylex.props(
+ styles.swatch,
+ value != null && styles.swatchFilled,
+ value != null && paint.fill(value),
+ )}
+ />
+ </Popover>
+ );
+}
+
+/**
+ * A menu shortcut, printed the way a desktop menu prints one: quiet
+ * secondary text set hard against the menu's right edge.
+ *
+ * `Kbd` paints one key cap per key, so `⌘` and `N` arrive as two small
+ * objects sitting beside the item. A shortcut is a hint about the item, not
+ * a control on it, so it reads better as one dim string that the eye can
+ * skip.
+ *
+ * The glyphs are literal because platform detection is core's, not a
+ * template's — `Kbd` resolves `mod` to ⌘ or Ctrl through an internal util
+ * that is deliberately unexported. These read as macOS, as they do in the
+ * shell-nav template.
+ */
+function Shortcut({children}: {children: string}) {
+ return (
+ <Text type="supporting" color="secondary">
+ {children}
+ </Text>
+ );
+}
+
+/**
+ * One row of the layer rail: an icon, the layer's name, and a lock.
+ *
+ * The lock is an action on the row, so it stays out of the way until the row
+ * is the one being pointed at — the rail reads as a list of names, and the
+ * control arrives where the cursor already is. A locked row is the exception:
+ * it shows the closed lock at rest, because that is a fact about the layer
+ * rather than an action being offered.
+ */
+/**
+ * The layer rail as a tree, grouped by what each layer is.
+ *
+ * A poster's layers are not a flat list — the two text layers belong together
+ * and the images belong together — and a tree says so structurally rather
+ * than by sorting and hoping the reader infers it. It also buys collapse: a
+ * document with thirty layers is navigable when the groups fold.
+ *
+ * Built as data rather than rows because TreeList owns the disclosure state,
+ * the guide lines and the roving focus that a hand-rolled tree would have to
+ * reimplement. The per-row pieces still come through the content slots, so
+ * the lock keeps its hover reveal.
+ */
+function layerTree(
+ layers: Layer[],
+ selectedID: string,
+ onSelect: (id: string) => void,
+ onToggleLock: (id: string) => void,
+ reveal: ReturnType<typeof useContainerReveal>,
+): TreeListItemData[] {
+ const row = (layer: Layer): TreeListItemData => ({
+ id: layer.id,
+ label: layer.name,
+ isSelected: layer.id === selectedID,
+ onClick: () => onSelect(layer.id),
+ // The hook owns both sides of the reveal. TreeList forwards the complete
+ // container props to this row, including the inline custom properties that
+ // isolate nested reveal containers.
+ ...reveal.getContainerProps(),
+ startContent: (
+ <Icon icon={LAYER_ICON[layer.kind]} size={ICON} color="secondary" />
+ ),
+ endContent: (
+ <ItemAction
+ label={layer.isLocked ? `Unlock ${layer.name}` : `Lock ${layer.name}`}
+ icon={layer.isLocked ? Lock : LockOpen}
+ onClick={() => onToggleLock(layer.id)}
+ {...reveal.getContentRevealProps({
+ forceVisibility: layer.isLocked ? 'shown' : undefined,
+ })}
+ />
+ ),
+ });
+
+ const groups: {id: string; label: string; kind: LayerKind}[] = [
+ {id: 'group-text', label: 'Text', kind: 'text'},
+ {id: 'group-images', label: 'Images', kind: 'image'},
+ ];
+
+ // A group with nothing in it is a disclosure that opens onto nothing, so it
+ // does not get drawn.
+ return groups
+ .map(group => ({
+ id: group.id,
+ label: group.label,
+ isExpanded: true,
+ // A group is a frame, not a bigger version of what it holds. Repeating
+ // the child's glyph on the parent says the row is another layer of that
+ // kind; the frame mark says it is the container.
+ startContent: <Icon icon={Frame} size={ICON} color="secondary" />,
+ children: layers.filter(l => l.kind === group.kind).map(row),
+ }))
+ .filter(group => group.children.length > 0);
+}
+
+/**
+ * A style slot that is either unset or carries a value: a field led by the
+ * slot's own icon, and a clear that only lights up once the slot holds
+ * something.
+ *
+ * The icon is a prop rather than one shared swatch. Border, shadow and fill
+ * are three different properties, and giving them one icon makes the column
+ * read as three copies of the same control.
+ */
+function StyleRow({
+ label,
+ name = label,
+ value,
+ placeholder,
+ onChange,
+ onClear,
+ children,
+}: {
+ label: string;
+ /**
+ * What the row's controls are called, when that has to differ from what
+ * the row is captioned. A text layer carries two shadows — its box's and
+ * its type's — and both are captioned "Shadow" because the section
+ * heading above each already says which. Screen reader users get no such
+ * heading with the control, so they get the longer name instead.
+ */
+ name?: string;
+ value?: string;
+ placeholder: string;
+ onChange: (next: string) => void;
+ onClear: () => void;
+ /** Extra controls for the popover, e.g. a shadow's offset and blur. */
+ children?: React.ReactNode;
+}) {
+ return (
+ <InspectorRow label={label}>
+ <StackItem size="fill">
+ <TextInput
+ label={name}
+ isLabelHidden
+ size="sm"
+ value={value ?? ''}
+ placeholder={placeholder}
+ onChange={onChange}
+ />
+ </StackItem>
+ <Swatch label={name} value={value} onChange={onChange}>
+ {children}
+ </Swatch>
+ <IconButton
+ label={`Clear ${name.toLowerCase()}`}
+ tooltip="Clear"
+ size="sm"
+ variant="ghost"
+ isDisabled={value === undefined}
+ onClick={onClear}
+ icon={<Icon icon={X} size={ICON} />}
+ />
+ </InspectorRow>
+ );
+}
+
+/**
+ * The four numbers a shadow has beyond its colour. They live in the same
+ * popover as the colour because a shadow is one thing to set, not five.
+ */
+function ShadowFields({
+ name,
+ shadow,
+ onChange,
+}: {
+ /** Prefixes each field, so two shadows on one layer stay tellable apart. */
+ name: string;
+ shadow: Shadow;
+ onChange: (next: Shadow) => void;
+}) {
+ const field = (key: 'x' | 'y' | 'blur' | 'spread', label: string) => (
+ <InspectorRow label={label} labelWidth={56}>
+ <StackItem size="fill">
+ <NumberInput
+ label={`${name} ${label.toLowerCase()}`}
+ isLabelHidden
+ size="sm"
+ hasNumberSteppers
+ value={shadow[key]}
+ onChange={next => onChange({...shadow, [key]: next})}
+ isWheelEnabled={false}
+ />
+ </StackItem>
+ </InspectorRow>
+ );
+ return (
+ <VStack gap={2}>
+ {field('x', 'X')}
+ {field('y', 'Y')}
+ {field('blur', 'Blur')}
+ {field('spread', 'Spread')}
+ </VStack>
+ );
+}
+
+// =============================================================================
+// Page
+// =============================================================================
+
+export default function CanvasEditor() {
+ const [layers, setLayers] = useState(INITIAL_LAYERS);
+ const [selectedID, setSelectedID] = useState('headline');
+ const [panel, setPanel] = useState('layers');
+ const [zoom, setZoom] = useState('0.4');
+
+ // The picker is presentational here: a template has no upload endpoint to
+ // post to, and swapping the artboard for a local object URL would leave the
+ // page showing something the template does not ship. Naming the chosen file
+ // is the honest middle — the control demonstrably works, and nothing
+ // pretends to have been uploaded.
+ const fileRef = useRef<HTMLInputElement>(null);
+ const [imageName, setImageName] = useState('Image');
+ // What the View submenu toggles. A design tool trades chrome for canvas, so
+ // these drive the real Layout slots rather than standing in for them.
+ const [chrome, setChrome] = useState({
+ left: true,
+ right: true,
+ toolbar: true,
+ });
+ const [appearance, setAppearance] = useState<ThemeMode>('system');
+ const [tabs, setTabs] = useState(INITIAL_TABS);
+ const [activeTab, setActiveTab] = useState(INITIAL_TABS[0].id);
+ const layerReveal = useContainerReveal();
+ // Only used to name new tabs, so it counts documents opened rather than
+ // documents open — reusing "Untitled 2" after closing one would be worse.
+ const untitledCount = useRef(1);
+
+ // Closing the open document has to hand the strip a new one, and the
+ // neighbour is the least surprising choice: the tab that slides under the
+ // pointer is the one that takes over. Closing the last tab leaves the strip
+ // empty rather than inventing a document nobody asked for.
+ const closeTab = (id: string) => {
+ setTabs(current => {
+ const index = current.findIndex(tab => tab.id === id);
+ const next = current.filter(tab => tab.id !== id);
+ if (id === activeTab) {
+ const neighbour = next[index] ?? next[index - 1];
+ setActiveTab(neighbour ? neighbour.id : '');
+ }
+ return next;
+ });
+ };
+
+ const addTab = () => {
+ untitledCount.current += 1;
+ const tab: DocumentTabData = {
+ id: `untitled-${untitledCount.current}`,
+ name: `Untitled ${untitledCount.current}`,
+ icon: FileIcon,
+ };
+ setTabs(current => [...current, tab]);
+ setActiveTab(tab.id);
+ };
+
+ // Both rails are drag-sized. The floors are the width each panel stops
+ // being useful below — the rail at the point layer names start truncating,
+ // the inspector at the point its two-field rows stop fitting side by side —
+ // and the ceilings keep either from eating the canvas they exist to serve.
+ const rail = useResizable({defaultSize: 216, minSize: 176, maxSize: 320});
+ const inspector = useResizable({
+ defaultSize: 288,
+ minSize: 264,
+ maxSize: 400,
+ });
+
+ const selected = layers.find(layer => layer.id === selectedID) ?? layers[0];
+ const scale = Number(zoom);
+
+ const updateSelected = useCallback(
+ (patch: Partial<Layer>) => {
+ setLayers(current =>
+ current.map(layer =>
+ layer.id === selectedID ? {...layer, ...patch} : layer,
+ ),
+ );
+ },
+ [selectedID],
+ );
+
+ const [headline, dateline] = layers.filter(layer => layer.kind === 'text');
+ const photo = layers.filter(layer => layer.kind === 'image')[0];
+
+ return (
+ // Appearance drives a Theme around the whole editor, and that Theme needs
+ // a surface of its own. Panels and toolbars are transparent, so without
+ // one they keep showing the host page's background while their text takes
+ // the new mode's colour — light text on a light page. The Section paints
+ // the mode's own background, which is what makes the editor consistent.
+ <Theme theme={neutralTheme} mode={appearance}>
+ <Section variant="section" padding={0} height="100%">
+ <Layout
+ height="fill"
+ padding={0}
+ header={
+ // Not a Toolbar. A toolbar is a set of peer commands that arrow
+ // keys walk across, and the document tabs make that wrong twice
+ // over: arrowing off a tab lands on its own close button, and a
+ // strip of documents is not a band of tools. This is the header
+ // slot of the layout it heads, which is what LayoutHeader is.
+ <LayoutHeader
+ hasDivider
+ // 4px on every edge. A toolbar's padding is sized for a band
+ // heading content, and app chrome wants to sit tighter: the
+ // strip inside carries its own 4px around a 28px tab. It also
+ // lands the menu button on the inset a ghost trigger wants, so
+ // nothing has to be pulled back out again.
+ padding={1}
+ xstyle={styles.headerBar}>
+ <HStack gap={0.5} vAlign="center" hAlign="between">
+ <HStack gap={0.5} vAlign="center" xstyle={styles.headerLead}>
+ {/*
+ One button for every command in the editor, the way a
+ single-window design tool does it. A menubar spends the
+ top-left on five words that are only read when someone is
+ already looking for a command; folding them into submenus
+ hands that space to the tabs, which are read constantly.
+ The commands keep their grouping — the bar became the
+ first level of the menu rather than disappearing.
+ */}
+ <DropdownMenu
+ button={{
+ label: 'Menu',
+ tooltip: 'Menu',
+ variant: 'ghost',
+ size: 'sm',
+ isIconOnly: true,
+ icon: <Icon icon={Menu} size={ICON} />,
+ }}
+ hasChevron={false}
+ // Left to itself the menu matches its trigger, and the
+ // trigger is a 28px icon button — five one-word rows in a
+ // column barely wider than the words. A set width gives
+ // the submenu chevrons somewhere to sit at the far edge,
+ // which is what makes the rows read as a menu bar folded
+ // into a list rather than a stack of buttons.
+ menuWidth={280}>
+ <DropdownMenuSubMenu label="File">
+ <DropdownMenuItem
+ label="New poster"
+ endContent={<Shortcut>⌘N</Shortcut>}
+ />
+ <DropdownMenuItem
+ label="Open…"
+ endContent={<Shortcut>⌘O</Shortcut>}
+ />
+ <DropdownMenuDivider />
+ <DropdownMenuItem
+ label="Save"
+ endContent={<Shortcut>⌘S</Shortcut>}
+ />
+ <DropdownMenuItem
+ label="Save as…"
+ endContent={<Shortcut>⇧⌘S</Shortcut>}
+ />
+ <DropdownMenuSubMenu label="Export">
+ {EXPORT_FORMATS.map(format => (
+ <DropdownMenuItem key={format} label={format} />
+ ))}
+ </DropdownMenuSubMenu>
+ <DropdownMenuDivider />
+ <DropdownMenuItem
+ label="Close"
+ endContent={<Shortcut>⌘W</Shortcut>}
+ />
+ </DropdownMenuSubMenu>
+
+ <DropdownMenuSubMenu label="Edit">
+ <DropdownMenuItem
+ label="Undo"
+ endContent={<Shortcut>⌘Z</Shortcut>}
+ />
+ <DropdownMenuItem
+ label="Redo"
+ endContent={<Shortcut>⇧⌘Z</Shortcut>}
+ />
+ <DropdownMenuDivider />
+ <DropdownMenuItem
+ label="Cut"
+ endContent={<Shortcut>⌘X</Shortcut>}
+ />
+ <DropdownMenuItem
+ label="Copy"
+ endContent={<Shortcut>⌘C</Shortcut>}
+ />
+ <DropdownMenuItem
+ label="Paste"
+ endContent={<Shortcut>⌘V</Shortcut>}
+ />
+ <DropdownMenuDivider />
+ <DropdownMenuItem
+ label="Duplicate"
+ endContent={<Shortcut>⌘D</Shortcut>}
+ />
+ {/* Named, because a menu opened from the bar has lost
+ sight of the rail: the row that would go is worth saying
+ out loud before a destructive item is clicked. */}
+ <DropdownMenuItem
+ label={`Delete ${selected.name}`}
+ variant="destructive"
+ endContent={<Shortcut>⌫</Shortcut>}
+ />
+ </DropdownMenuSubMenu>
+
+ {/* Checkbox rows, not actions: each reports a state the
+ user can see on the page, and the menu stays open so all
+ three can be set in one visit. */}
+ <DropdownMenuSubMenu label="View">
+ <DropdownMenuCheckboxItem
+ label="Left panel"
+ icon={PanelLeft}
+ endContent={<Shortcut>⌘B</Shortcut>}
+ value={chrome.left}
+ onChange={next => setChrome(c => ({...c, left: next}))}
+ />
+ <DropdownMenuCheckboxItem
+ label="Right panel"
+ icon={PanelRight}
+ endContent={<Shortcut>⇧⌘B</Shortcut>}
+ value={chrome.right}
+ onChange={next => setChrome(c => ({...c, right: next}))}
+ />
+ <DropdownMenuCheckboxItem
+ label="Canvas tools"
+ icon={PanelBottom}
+ endContent={<Shortcut>⌘.</Shortcut>}
+ value={chrome.toolbar}
+ onChange={next =>
+ setChrome(c => ({...c, toolbar: next}))
+ }
+ />
+ <DropdownMenuDivider />
+ {/* The same value the tool bar's zoom control holds, so
+ setting it in either place moves the other. */}
+ <DropdownMenuSubMenu label="Zoom">
+ <DropdownMenuRadioGroup
+ label="Zoom"
+ value={zoom}
+ onChange={setZoom}>
+ {ZOOM_OPTIONS.map(option => (
+ <DropdownMenuRadioItem
+ key={option.value}
+ value={option.value}
+ label={option.label}
+ />
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuSubMenu>
+ <DropdownMenuSubMenu label="Appearance">
+ <DropdownMenuRadioGroup
+ label="Appearance"
+ value={appearance}
+ onChange={next => setAppearance(next as ThemeMode)}>
+ <DropdownMenuRadioItem value="light" label="Light" />
+ <DropdownMenuRadioItem value="dark" label="Dark" />
+ <DropdownMenuRadioItem
+ value="system"
+ label="System"
+ />
+ </DropdownMenuRadioGroup>
+ </DropdownMenuSubMenu>
+ </DropdownMenuSubMenu>
+
+ <DropdownMenuSubMenu label="Object">
+ <DropdownMenuSubMenu label="Insert">
+ {INSERT_ITEMS.map(item => (
+ <DropdownMenuItem
+ key={item.label}
+ label={item.label}
+ icon={item.icon}
+ />
+ ))}
+ </DropdownMenuSubMenu>
+ <DropdownMenuDivider />
+ <DropdownMenuItem
+ label="Bring forward"
+ endContent={<Shortcut>⌘]</Shortcut>}
+ />
+ <DropdownMenuItem
+ label="Send backward"
+ endContent={<Shortcut>⌘[</Shortcut>}
+ />
+ <DropdownMenuDivider />
+ {/* The lock the rail row reveals on hover, reached from
+ the menubar instead — one piece of state, two ways in. */}
+ <DropdownMenuCheckboxItem
+ label={`Lock ${selected.name}`}
+ icon={selected.isLocked ? Lock : LockOpen}
+ endContent={<Shortcut>⇧⌘L</Shortcut>}
+ value={selected.isLocked}
+ onChange={next => updateSelected({isLocked: next})}
+ />
+ </DropdownMenuSubMenu>
+
+ <DropdownMenuDivider />
+
+ <DropdownMenuSubMenu label="Help">
+ <DropdownMenuItem
+ label="Keyboard shortcuts"
+ endContent={<Shortcut>⌘/</Shortcut>}
+ />
+ <DropdownMenuItem label="Documentation" />
+ <DropdownMenuDivider />
+ <DropdownMenuItem label="About this editor" />
+ </DropdownMenuSubMenu>
+ </DropdownMenu>
+
+ {/*
+ A group, not a nav landmark: a landmark inside a
+ role="toolbar" is not a place a screen reader expects one,
+ and the toolbar already is the region. The group gives the
+ strip a name, and each tab says whether it is the open
+ document with aria-current.
+ */}
+ <HStack
+ role="group"
+ aria-label="Open documents"
+ gap={0}
+ vAlign="center"
+ paddingInline={2}
+ paddingBlock={1}
+ isScrollable
+ maxWidth={`calc(100cqw - ${TAB_STRIP_RESERVE}px)`}
+ xstyle={styles.tabStrip}>
+ {tabs.map((tab, index) => {
+ // Tabs are all one width, so the rule marks a boundary
+ // rather than sitting midway between two labels. It is
+ // dropped either side of the open document: that tab
+ // already reads as separate by its fill, and a rule
+ // running into the fill's rounded edge only crowds it.
+ // Hidden rather than unmounted, so moving the selection
+ // does not add or remove a flex item and slide the whole
+ // strip sideways under the pointer that just clicked it.
+ const previous = tabs[index - 1];
+ const isRuleHidden =
+ previous?.id === activeTab || tab.id === activeTab;
+ return (
+ <Fragment key={tab.id}>
+ {previous != null ? (
+ <Divider
+ orientation="vertical"
+ xstyle={[
+ styles.tabRule,
+ isRuleHidden && styles.tabRuleHidden,
+ ]}
+ />
+ ) : null}
+ <DocumentTab
+ tab={tab}
+ isActive={tab.id === activeTab}
+ onSelect={() => setActiveTab(tab.id)}
+ onClose={() => closeTab(tab.id)}
+ />
+ </Fragment>
+ );
+ })}
+ </HStack>
+ {/*
+ Outside the strip on both counts: it is not one of the
+ open documents the group is named for, and inside a strip
+ that scrolls once the tabs stop fitting it would be the
+ first thing to scroll out of reach — exactly when adding
+ a document is most likely to be what you came for.
+ */}
+ <IconButton
+ label="New document"
+ tooltip="New document"
+ variant="ghost"
+ size="sm"
+ onClick={addTab}
+ icon={<Icon icon={Plus} size={ICON} color="secondary" />}
+ />
+ </HStack>
+ <HStack gap={3} vAlign="center">
+ <Text type="supporting" color="secondary">
+ Saved · 2 min ago
+ </Text>
+ <DropdownMenu
+ button={{
+ label: 'Export',
+ variant: 'ghost',
+ size: 'sm',
+ icon: <Icon icon={Download} size={ICON} />,
+ }}
+ alignment="end"
+ items={EXPORT_MENU}
+ />
+ </HStack>
+ </HStack>
+ </LayoutHeader>
+ }
+ content={
+ <LayoutContent padding={0}>
+ <Layout
+ height="fill"
+ start={
+ chrome.left ? (
+ <>
+ <LayoutPanel
+ resizable={rail.props}
+ hasDivider
+ padding={2}
+ label="Layers and assets"
+ xstyle={styles.foldsAtRail}>
+ <VStack gap={3}>
+ <SegmentedControl
+ label="Left panel"
+ size="sm"
+ layout="fill"
+ value={panel}
+ onChange={setPanel}>
+ <SegmentedControlItem
+ label="Layers"
+ value="layers"
+ />
+ <SegmentedControlItem
+ label="Library"
+ value="library"
+ />
+ </SegmentedControl>
+ {panel === 'layers' ? (
+ <TreeList
+ density="compact"
+ items={layerTree(
+ layers,
+ selectedID,
+ setSelectedID,
+ id =>
+ setLayers(current =>
+ current.map(l =>
+ l.id === id
+ ? {...l, isLocked: !l.isLocked}
+ : l,
+ ),
+ ),
+ layerReveal,
+ )}
+ />
+ ) : (
+ <List>
+ {EFFECT_PRESETS.map(preset => (
+ <Item
+ key={preset.label}
+ as="li"
+ density="compact"
+ label={preset.label}
+ startContent={
+ <Icon
+ icon={preset.icon}
+ size={ICON}
+ color="secondary"
+ />
+ }
+ />
+ ))}
+ </List>
+ )}
+ </VStack>
+ </LayoutPanel>
+ {/* The panel draws the separator, so the handle stays
+ divider-less and keeps its grip hidden until the pointer
+ is on the seam. */}
+ <ResizeHandle
+ resizable={rail.props}
+ isAlwaysVisible={false}
+ // Centred on the seam rather than pushed onto the
+ // content side: the grip marks the edge it moves, and
+ // an offset pill points at a boundary that is not
+ // where the drag actually happens.
+ pillPlacement="center"
+ label="Resize layers panel"
+ xstyle={styles.foldsAtRail}
+ />
+ </>
+ ) : undefined
+ }
+ content={
+ <LayoutContent padding={0}>
+ <Section variant="muted" padding={0} height="100%">
+ <Layout
+ height="fill"
+ // Lifts the tool bar off the bottom edge: the footer
+ // reads this as its outer padding, so the bar floats
+ // over the backdrop rather than sitting on the sill.
+ padding={4}
+ content={
+ <LayoutContent padding={6}>
+ <HStack
+ width="max-content"
+ height="max-content"
+ minHeight="100%"
+ xstyle={styles.canvasStage}>
+ <Card
+ padding={0}
+ elevation="med"
+ width={FRAME.width * scale}
+ height={FRAME.height * scale}
+ xstyle={[
+ styles.artboardFrame,
+ styles.artboardCentered,
+ ]}>
+ <Theme theme={canvasEditorTheme} mode="light">
+ <AspectRatio
+ ratio={FRAME.width / FRAME.height}
+ fit="cover"
+ xstyle={styles.artboard(scale)}>
+ <img
+ src={PHOTO_LAYER_SRC}
+ alt={photo.content}
+ {...stylex.props(
+ paint.photo(
+ filterCss(
+ photo.filters ?? NO_FILTERS,
+ ),
+ ),
+ )}
+ />
+ {/* Both text layers share one column, so
+ vertical alignment is a property of the
+ column and the headline speaks for it. */}
+ <VStack
+ padding={6}
+ gap={3}
+ vAlign={
+ V_ALIGN[headline.alignY ?? 'start']
+ }
+ xstyle={styles.textLayers}>
+ <Text
+ type="supporting"
+ display="block"
+ xstyle={[
+ styles.type(
+ dateline.size ?? 0,
+ dateline.tracking ?? 0,
+ dateline.line ?? 100,
+ dateline.color ?? '#111111',
+ dateline.stroke ?? 0,
+ shadowCss(dateline.textShadow),
+ ),
+ typeAlign[dateline.alignX ?? 'start'],
+ typeCase[
+ dateline.transform ?? 'none'
+ ],
+ typeLine[
+ dateline.decoration ?? 'none'
+ ],
+ typeSlant[
+ dateline.isItalic
+ ? 'italic'
+ : 'normal'
+ ],
+ ]}>
+ {dateline.content}
+ </Text>
+ <Heading
+ level={2}
+ type="display-1"
+ textWrap="balance"
+ xstyle={[
+ styles.type(
+ headline.size ?? 0,
+ headline.tracking ?? 0,
+ headline.line ?? 100,
+ headline.color ?? '#111111',
+ headline.stroke ?? 0,
+ shadowCss(headline.textShadow),
+ ),
+ typeAlign[headline.alignX ?? 'start'],
+ typeCase[
+ headline.transform ?? 'none'
+ ],
+ typeLine[
+ headline.decoration ?? 'none'
+ ],
+ typeSlant[
+ headline.isItalic
+ ? 'italic'
+ : 'normal'
+ ],
+ ]}>
+ {headline.content}
+ </Heading>
+ </VStack>
+ </AspectRatio>
+ </Theme>
+ </Card>
+ </HStack>
+ </LayoutContent>
+ }
+ footer={
+ chrome.toolbar ? (
+ <LayoutFooter>
+ <Center>
+ {/* Padding of one step, and the controls
+ inside round to the card's radius less that
+ step — see styles.toolBarControl. */}
+ <Card padding={1} elevation="high">
+ <Toolbar
+ label="Canvas tools"
+ size="sm"
+ startContent={
+ <>
+ <IconButton
+ label="Undo"
+ tooltip="Undo"
+ variant="ghost"
+ icon={
+ <Icon icon={Undo2} size={ICON} />
+ }
+ xstyle={styles.toolBarControl}
+ />
+ <IconButton
+ label="Redo"
+ tooltip="Redo"
+ variant="ghost"
+ icon={
+ <Icon icon={Redo2} size={ICON} />
+ }
+ xstyle={styles.toolBarControl}
+ />
+ <Divider
+ orientation="vertical"
+ xstyle={styles.toolBarRule}
+ />
+ <IconButton
+ label="Add frame"
+ tooltip="Add frame"
+ variant="ghost"
+ icon={
+ <Icon icon={Frame} size={ICON} />
+ }
+ xstyle={styles.toolBarControl}
+ />
+ <IconButton
+ label="Add text"
+ tooltip="Add text"
+ variant="ghost"
+ icon={
+ <Icon icon={Type} size={ICON} />
+ }
+ xstyle={styles.toolBarControl}
+ />
+ <IconButton
+ label="Add image"
+ tooltip="Add image"
+ variant="ghost"
+ icon={
+ <Icon
+ icon={ImageIcon}
+ size={ICON}
+ />
+ }
+ xstyle={styles.toolBarControl}
+ />
+ <Divider
+ orientation="vertical"
+ xstyle={styles.toolBarRule}
+ />
+ <Selector
+ label="Zoom"
+ isLabelHidden
+ variant="ghost"
+ value={zoom}
+ onChange={setZoom}
+ options={ZOOM_OPTIONS}
+ placement="above"
+ // Fixed so the bar does not reflow
+ // as the value changes, and wide
+ // enough for the longest option
+ // ("100%") to avoid truncation.
+ width={92}
+ xstyle={[
+ styles.toolBarControl,
+ styles.toolBarTrailing,
+ ]}
+ />
+ </>
+ }
+ />
+ </Card>
+ </Center>
+ </LayoutFooter>
+ ) : undefined
+ }
+ />
+ </Section>
+ </LayoutContent>
+ }
+ end={
+ chrome.right ? (
+ <>
+ <ResizeHandle
+ resizable={inspector.props}
+ isReversed
+ isAlwaysVisible={false}
+ pillPlacement="center"
+ label="Resize properties panel"
+ xstyle={styles.foldsAtInspector}
+ />
+ <LayoutPanel
+ resizable={inspector.props}
+ hasDivider
+ padding={0}
+ isScrollable
+ label={`${selected.name} properties`}
+ xstyle={styles.foldsAtInspector}>
+ <InspectorSection title="Layout">
+ <InspectorRow label="Padding">
+ <AxisInput
+ icon={PanelLeftRightDashed}
+ label="Horizontal padding"
+ value={selected.paddingInline}
+ onChange={next =>
+ updateSelected({paddingInline: next})
+ }
+ />
+ <AxisInput
+ icon={PanelTopBottomDashed}
+ label="Vertical padding"
+ value={selected.paddingBlock}
+ onChange={next =>
+ updateSelected({paddingBlock: next})
+ }
+ />
+ <IconButton
+ label="Set padding per side"
+ tooltip="Per side"
+ size="sm"
+ variant="ghost"
+ icon={<Icon icon={SquareSquare} size={ICON} />}
+ />
+ </InspectorRow>
+ </InspectorSection>
+
+ <InspectorSection title="Layer">
+ <InspectorRow label="Position">
+ <AxisInput
+ icon={GLYPH.x}
+ label="Horizontal position"
+ value={selected.x}
+ onChange={next => updateSelected({x: next})}
+ />
+ <AxisInput
+ icon={GLYPH.y}
+ label="Vertical position"
+ value={selected.y}
+ onChange={next => updateSelected({y: next})}
+ />
+ </InspectorRow>
+ <InspectorRow label="Size">
+ <AxisInput
+ icon={GLYPH.width}
+ label="Width"
+ value={selected.width}
+ onChange={next => updateSelected({width: next})}
+ />
+ <AxisInput
+ icon={GLYPH.height}
+ label="Height"
+ value={selected.height}
+ onChange={next => updateSelected({height: next})}
+ />
+ </InspectorRow>
+ </InspectorSection>
+
+ <InspectorSection title="Styles">
+ <InspectorRow label="Radius">
+ <AxisInput
+ icon={Scan}
+ label="Corner radius"
+ value={selected.radius}
+ onChange={next => updateSelected({radius: next})}
+ />
+ <IconButton
+ label="Set radius per corner"
+ tooltip="Per corner"
+ size="sm"
+ variant="ghost"
+ icon={
+ <Icon icon={SquareRoundCorner} size={ICON} />
+ }
+ />
+ </InspectorRow>
+ <StyleRow
+ label="Border"
+ value={selected.border}
+ placeholder="Add…"
+ onChange={next => updateSelected({border: next})}
+ onClear={() => updateSelected({border: undefined})}
+ />
+ <StyleRow
+ label="Shadow"
+ name="Box shadow"
+ value={selected.shadow?.color}
+ placeholder="Add…"
+ 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}
+ placeholder="Add…"
+ onChange={next => updateSelected({fill: next})}
+ onClear={() => updateSelected({fill: undefined})}
+ />
+ </InspectorSection>
+
+ <InspectorSection title="Transforms">
+ <InspectorRow label="Rotate">
+ <AxisInput
+ icon={TriangleRight}
+ label="Rotation"
+ value={selected.rotation}
+ onChange={next =>
+ updateSelected({rotation: next})
+ }
+ />
+ <IconButton
+ label="Rotate counterclockwise"
+ tooltip="−90°"
+ size="sm"
+ variant="ghost"
+ onClick={() =>
+ updateSelected({
+ rotation: (selected.rotation + 270) % 360,
+ })
+ }
+ icon={<Icon icon={RotateCcw} size={ICON} />}
+ />
+ <IconButton
+ label="Rotate clockwise"
+ tooltip="+90°"
+ size="sm"
+ variant="ghost"
+ onClick={() =>
+ updateSelected({
+ rotation: (selected.rotation + 90) % 360,
+ })
+ }
+ icon={<Icon icon={RotateCw} size={ICON} />}
+ />
+ </InspectorRow>
+ <InspectorRow label="Flip" hAlign="end">
+ <IconButton
+ label="Flip horizontally"
+ tooltip="Flip horizontally"
+ size="sm"
+ variant="ghost"
+ icon={<Icon icon={FlipHorizontal2} size={ICON} />}
+ />
+ <IconButton
+ label="Flip vertically"
+ tooltip="Flip vertically"
+ size="sm"
+ variant="ghost"
+ icon={<Icon icon={FlipVertical2} size={ICON} />}
+ />
+ </InspectorRow>
+ </InspectorSection>
+
+ {selected.kind === 'text' ? (
+ <InspectorSection title="Text">
+ <TextArea
+ label="Content"
+ isLabelHidden
+ size="sm"
+ rows={2}
+ value={selected.content}
+ onChange={next => updateSelected({content: next})}
+ />
+ <InspectorRow label="Font">
+ <StackItem size="fill">
+ <Selector
+ label="Font family"
+ isLabelHidden
+ size="sm"
+ value={selected.family}
+ onChange={next =>
+ updateSelected({family: next})
+ }
+ options={FONT_OPTIONS}
+ />
+ </StackItem>
+ </InspectorRow>
+ <InspectorRow label="Weight">
+ <StackItem size="fill">
+ <Selector
+ label="Font weight"
+ isLabelHidden
+ size="sm"
+ value={selected.weight}
+ onChange={next =>
+ updateSelected({weight: next})
+ }
+ options={WEIGHT_OPTIONS}
+ />
+ </StackItem>
+ </InspectorRow>
+ <InspectorRow label="Color">
+ <StackItem size="fill">
+ <TextInput
+ label="Text colour"
+ isLabelHidden
+ size="sm"
+ value={selected.color ?? ''}
+ onChange={next =>
+ updateSelected({color: next})
+ }
+ />
+ </StackItem>
+ <Swatch
+ label="Text colour"
+ value={selected.color}
+ onChange={next => updateSelected({color: next})}
+ />
+ </InspectorRow>
+ <StepperRow
+ label="Size"
+ value={selected.size ?? 0}
+ 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">
+ <StackItem size="fill">
+ <SegmentedControl
+ label="Horizontal alignment"
+ size="sm"
+ layout="fill"
+ value={selected.alignX ?? 'start'}
+ onChange={next =>
+ updateSelected({alignX: next as AlignX})
+ }>
+ {ALIGN_X.map(option => (
+ <SegmentedControlItem
+ key={option.value}
+ value={option.value}
+ label={option.label}
+ isLabelHidden
+ icon={
+ <Icon icon={option.icon} size={ICON} />
+ }
+ />
+ ))}
+ </SegmentedControl>
+ </StackItem>
+ </InspectorRow>
+ <InspectorRow label="Align">
+ <StackItem size="fill">
+ <SegmentedControl
+ label="Vertical alignment"
+ size="sm"
+ layout="fill"
+ value={selected.alignY ?? 'start'}
+ onChange={next =>
+ updateSelected({alignY: next as AlignY})
+ }>
+ {ALIGN_Y.map(option => (
+ <SegmentedControlItem
+ key={option.value}
+ value={option.value}
+ label={option.label}
+ isLabelHidden
+ icon={
+ <Icon icon={option.icon} size={ICON} />
+ }
+ />
+ ))}
+ </SegmentedControl>
+ </StackItem>
+ </InspectorRow>
+ <InspectorRow label="Style">
+ <StackItem size="fill">
+ <SegmentedControl
+ label="Font style"
+ size="sm"
+ layout="fill"
+ value={
+ selected.isItalic ? 'italic' : 'normal'
+ }
+ onChange={next =>
+ updateSelected({
+ isItalic: next === 'italic',
+ })
+ }>
+ <SegmentedControlItem
+ value="normal"
+ label="Regular"
+ isLabelHidden
+ icon={<Icon icon={Baseline} size={ICON} />}
+ />
+ <SegmentedControlItem
+ value="italic"
+ label="Italic"
+ isLabelHidden
+ icon={<Icon icon={Italic} size={ICON} />}
+ />
+ </SegmentedControl>
+ </StackItem>
+ </InspectorRow>
+ <InspectorRow label="Decoration">
+ <StackItem size="fill">
+ <SegmentedControl
+ label="Text decoration"
+ size="sm"
+ layout="fill"
+ value={selected.decoration ?? 'none'}
+ onChange={next =>
+ updateSelected({
+ decoration: next as Decoration,
+ })
+ }>
+ {DECORATIONS.map(option => (
+ <SegmentedControlItem
+ key={option.value}
+ value={option.value}
+ label={option.label}
+ isLabelHidden
+ icon={
+ <Icon icon={option.icon} size={ICON} />
+ }
+ />
+ ))}
+ </SegmentedControl>
+ </StackItem>
+ </InspectorRow>
+ <InspectorRow label="Transform">
+ <StackItem size="fill">
+ <SegmentedControl
+ label="Text transform"
+ size="sm"
+ layout="fill"
+ value={selected.transform ?? 'none'}
+ onChange={next =>
+ updateSelected({
+ transform: next as Transform,
+ })
+ }>
+ {TRANSFORMS.map(option => (
+ <SegmentedControlItem
+ key={option.value}
+ value={option.value}
+ label={option.label}
+ isLabelHidden
+ icon={
+ <Icon icon={option.icon} size={ICON} />
+ }
+ />
+ ))}
+ </SegmentedControl>
+ </StackItem>
+ </InspectorRow>
+ <StyleRow
+ label="Shadow"
+ name="Text shadow"
+ value={selected.textShadow?.color}
+ placeholder="Add…"
+ 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">
+ <StackItem size="fill">
+ <NumberInput
+ label="Text stroke"
+ isLabelHidden
+ size="sm"
+ value={selected.stroke ?? 0}
+ onChange={next =>
+ updateSelected({stroke: next})
+ }
+ isWheelEnabled={false}
+ />
+ </StackItem>
+ <IconButton
+ label="Clear stroke"
+ tooltip="Clear"
+ size="sm"
+ variant="ghost"
+ isDisabled={!selected.stroke}
+ onClick={() => updateSelected({stroke: 0})}
+ icon={<Icon icon={X} size={ICON} />}
+ />
+ </InspectorRow>
+ </InspectorSection>
+ ) : (
+ <>
+ <InspectorSection title="Image">
+ <InspectorRow label="Edit">
+ <StackItem size="fill">
+ <TextInput
+ label="Image source"
+ isLabelHidden
+ size="sm"
+ value={imageName}
+ isReadOnly
+ />
+ </StackItem>
+ {/* Astryx's FileInput is fixed at the medium
+ element height, and this row is built on the
+ 28px rhythm the rest of the inspector keeps,
+ so the picker is driven from the thumbnail
+ instead. The input stays in the DOM — hiding
+ it with the attribute rather than unmounting
+ it is what lets the button open it. */}
+ <input
+ ref={fileRef}
+ type="file"
+ accept="image/*"
+ hidden
+ onChange={event => {
+ const file = event.target.files?.[0];
+ if (file) {
+ setImageName(file.name);
+ }
+ }}
+ />
+ {/* The trigger shows the picture rather than
+ an icon standing in for one: the row is about
+ which image this is. `onClick` is what gives
+ Thumbnail its button semantics and hover
+ overlay, and `label` doubles as the tooltip. */}
+ <Thumbnail
+ src={PHOTO_LAYER_SRC}
+ alt={`Current image, ${imageName}`}
+ label="Replace image"
+ onClick={() => fileRef.current?.click()}
+ xstyle={styles.sourceThumbnail}
+ />
+ </InspectorRow>
+ <InspectorRow label="Fit">
+ <StackItem size="fill">
+ <Selector
+ label="Image fit"
+ isLabelHidden
+ size="sm"
+ value={selected.fit ?? 'Cover'}
+ onChange={next =>
+ updateSelected({fit: next})
+ }
+ options={['Cover', 'Contain', 'Fill']}
+ />
+ </StackItem>
+ </InspectorRow>
+ </InspectorSection>
+ <InspectorSection title="Filters">
+ {FILTERS.map(filter => (
+ <FilterRow
+ key={filter.key}
+ filter={filter}
+ value={
+ (selected.filters ?? NO_FILTERS)[filter.key]
+ }
+ onChange={next =>
+ updateSelected({
+ filters: {
+ ...(selected.filters ?? NO_FILTERS),
+ [filter.key]: next,
+ },
+ })
+ }
+ />
+ ))}
+ </InspectorSection>
+ </>
+ )}
+ </LayoutPanel>
+ </>
+ ) : undefined
+ }
+ />
+ </LayoutContent>
+ }
+ />
+ </Section>
+ </Theme>
+ );
+}
diff --git a/packages/cli/assets/templates/pages/canvas-editor/template.doc.mjs b/packages/cli/assets/templates/pages/canvas-editor/template.doc.mjs
new file mode 100644
index 0000000000..bfb99dcdd7
--- /dev/null
+++ b/packages/cli/assets/templates/pages/canvas-editor/template.doc.mjs
@@ -0,0 +1,12 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
+export const doc = {
+ type: 'page',
+ name: 'Canvas Editor',
+ displayName: 'Canvas Editor',
+ description:
+ 'Layered artboard workspace: document tabs over a layer rail, a fixed-size frame you zoom on a muted backdrop, and an inspector of position, type, and filter fields that retargets to the selected layer. Objects hold a coordinate rather than reflowing, so moving one never moves another. Design tool, artboard, poster, graphic, image, or slide editor.',
+ isReady: true,
+ category: 'Tools - Canvas Editor',
+};
diff --git a/packages/cli/authoring/doctypes/template/type.ts b/packages/cli/authoring/doctypes/template/type.ts
index f36fe4ecc5..59082b1610 100644
--- a/packages/cli/authoring/doctypes/template/type.ts
+++ b/packages/cli/authoring/doctypes/template/type.ts
@@ -138,6 +138,7 @@ export type TemplateCategory =
| 'Login - SSO'
| 'Login - Split'
// Tools
+ | 'Tools - Canvas Editor'
| 'Tools - File Explorer'
| 'Tools - Page Editor'
| 'Tools - IDE'
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 2eaeb7dfde..d140f79d43 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -512,6 +512,9 @@ importers:
'@stylexjs/stylex':
specifier: 'catalog:'
version: 0.19.0
+ lucide-react:
+ specifier: ^1.18.0
+ version: 1.23.0([email protected])
react:
specifier: ^19.2.7
version: 19.2.7