@pairdraw/design-jsx 0.19.0 → 0.19.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { behaviourFromSpec, withBehaviour } from "@pairdraw/scene-graph/behaviours";
1
+ import { behaviourFromSpec, validateChoiceValues, withBehaviour } from "@pairdraw/scene-graph/behaviours";
2
2
  import { createComponentPropertyId } from "@pairdraw/scene-graph/components";
3
3
  import { createSlotProperty } from "@pairdraw/scene-graph/slots";
4
4
  function inlineFragments(children) {
@@ -289,6 +289,7 @@ function finishRoot(graph, scope, props) {
289
289
  ...behaviour.texts,
290
290
  ...Object.fromEntries([...scope.texts].map(([valueId, id]) => [valueId, { propertyId: id }]))
291
291
  };
292
+ validateChoiceValues(graph, owner, behaviour);
292
293
  graph.updateNode(owner.id, { pluginData: withBehaviour(owner, behaviour) });
293
294
  }
294
295
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"elements.js","names":[],"sources":["../../../src/tree.ts","../../../src/behaviours/index.ts","../../../src/behaviours/elements.ts"],"sourcesContent":["import type { Effect, Fill } from '@pairdraw/scene-graph'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\n\nimport type { ComponentProperty } from './component-properties'\nimport type { DesignMode, DesignVariable } from './variables'\n\nexport interface TreeNode {\n type: string\n props: Record<string, unknown>\n children: (TreeNode | string)[]\n /** Where the element was written, when the source is known. */\n source?: { line: number }\n}\n\n/** A fragment (`<>…</>`) groups siblings without creating a node of its own. */\nexport const FRAGMENT = ''\n\nfunction inlineFragments(children: (TreeNode | string)[]): (TreeNode | string)[] {\n return children.flatMap((child) =>\n typeof child !== 'string' && child.type === FRAGMENT ? child.children : [child]\n )\n}\n\n/**\n * The text an element holds as children, such as a sticky note's body or a connector's label.\n * Elements among its children are not text and are skipped.\n */\nexport function plainTextOf(tree: TreeNode): string {\n return tree.children.filter((child): child is string => typeof child === 'string').join('')\n}\n\nexport function isTreeNode(x: unknown): x is TreeNode {\n if (x === null || typeof x !== 'object') return false\n return (\n 'type' in x &&\n typeof x.type === 'string' &&\n 'props' in x &&\n 'children' in x &&\n Array.isArray(x.children)\n )\n}\n\ntype FunctionComponent = (props: Record<string, unknown>) => unknown\n\ninterface ReactElement {\n type: unknown\n props: Record<string, unknown>\n}\n\nfunction isReactElement(x: unknown): x is ReactElement {\n return x !== null && typeof x === 'object' && 'type' in x && 'props' in x\n}\n\n/**\n * Resolve any element-like value (ReactElement, TreeNode, function component)\n * into a TreeNode. Handles recursive function components up to depth 100.\n */\nexport function resolveToTree(element: unknown, depth = 0): TreeNode | null {\n if (depth > 100) throw new Error('Component resolution depth exceeded')\n if (element == null) return null\n if (isTreeNode(element)) return element\n if (!isReactElement(element)) return null\n\n if (typeof element.type === 'function') {\n const component = element.type as FunctionComponent\n return resolveToTree(component(element.props), depth + 1)\n }\n\n if (typeof element.type === 'string') {\n const children: (TreeNode | string)[] = []\n const elChildren = element.props.children\n if (elChildren != null) {\n const childArray = Array.isArray(elChildren) ? elChildren : [elChildren]\n for (const child of childArray.flat()) {\n if (child == null) continue\n if (typeof child === 'string' || typeof child === 'number') {\n children.push(String(child))\n } else {\n const resolved = resolveToTree(child, depth + 1)\n if (resolved) children.push(resolved)\n }\n }\n }\n const { children: _, ...props } = element.props\n return { type: element.type, props, children: inlineFragments(children) }\n }\n\n return null\n}\n\nfunction resolveChild(child: unknown): TreeNode | string | null {\n if (child == null) return null\n if (typeof child === 'string' || typeof child === 'number') return String(child)\n return resolveToTree(child)\n}\n\nexport function node(\n type: string,\n props: { children?: unknown; [key: string]: unknown }\n): TreeNode {\n const { children, ...rest } = props\n const processed = [children]\n .flat(Infinity)\n .map(resolveChild)\n .filter((c): c is TreeNode | string => c !== null)\n return { type, props: rest, children: inlineFragments(processed) }\n}\n\nexport type PaintProp = string | Color | Fill | DesignVariable\n\nexport type StyleProps = {\n flex?: 'row' | 'col' | 'column'\n flow?: 'auto' | 'ltr' | 'rtl'\n dir?: 'auto' | 'ltr' | 'rtl'\n gap?: number | DesignVariable\n wrap?: boolean\n rowGap?: number | DesignVariable\n columnGap?: number | DesignVariable\n justify?: 'start' | 'end' | 'center' | 'between' | 'around'\n justifyContent?: 'start' | 'end' | 'center' | 'between' | 'around'\n items?: 'start' | 'end' | 'center' | 'stretch' | 'baseline'\n align?: 'start' | 'end' | 'center' | 'stretch' | 'baseline'\n alignItems?: 'start' | 'end' | 'center' | 'stretch' | 'baseline'\n grow?: number\n\n w?: number | 'fill' | 'hug' | DesignVariable\n h?: number | 'fill' | 'hug' | DesignVariable\n minW?: number\n maxW?: number\n minH?: number\n maxH?: number\n\n x?: number\n y?: number\n\n p?: number | DesignVariable\n px?: number | DesignVariable\n py?: number | DesignVariable\n pt?: number | DesignVariable\n pr?: number | DesignVariable\n pb?: number | DesignVariable\n pl?: number | DesignVariable\n\n bg?: PaintProp\n fill?: PaintProp\n fills?: PaintProp[]\n stroke?: PaintProp\n strokeWidth?: number | DesignVariable\n strokeAlign?: 'inside' | 'outside' | 'center'\n strokeDash?: number[] | boolean\n dashPattern?: number[]\n rounded?: number | DesignVariable\n roundedTL?: number | DesignVariable\n roundedTR?: number | DesignVariable\n roundedBL?: number | DesignVariable\n roundedBR?: number | DesignVariable\n cornerSmoothing?: number\n opacity?: number | DesignVariable\n blendMode?: string\n mask?: boolean | 'alpha' | 'luminance' | 'vector'\n rotate?: number\n rotation?: number\n /** Reflects the layer across its vertical centre line, before it turns. */\n flipX?: boolean\n /** Reflects the layer across its horizontal centre line, before it turns. */\n flipY?: boolean\n overflow?: 'hidden' | 'visible'\n shadow?: string\n blur?: number\n effects?: Effect[]\n\n size?: number | DesignVariable\n fontSize?: number | DesignVariable\n /** Pixels, or a percent of the font size such as `'150%'`. */\n lineHeight?: number | `${number}%` | 'auto' | DesignVariable\n /** Pixels, or a percent of the font size such as `'5%'`. */\n letterSpacing?: number | `${number}%` | DesignVariable\n /** OpenType features on or off by tag, as CSS's `font-feature-settings`: `{ tnum: true }`. */\n fontFeatures?: Record<string, boolean>\n /** Variable-font axis values by tag, as CSS's `font-variation-settings`: `{ wght: 650 }`. */\n fontVariations?: Record<string, number>\n /** The language the text is in, as a BCP 47 tag such as `de` or `sr-Latn`. */\n lang?: string | null\n /**\n * Whether a variable font's optical size follows the font size (`auto`, the default) or takes\n * the `opsz` in `fontVariations` (`none`), as CSS's `font-optical-sizing`.\n */\n fontOpticalSizing?: 'auto' | 'none'\n font?: string\n fontFamily?: string\n weight?: number | 'bold' | 'medium' | 'normal'\n fontWeight?: number | 'bold' | 'medium' | 'normal'\n color?: PaintProp\n text?: string | ComponentProperty<string>\n characters?: string\n textAlign?: 'left' | 'center' | 'right' | 'justified'\n textAlignHorizontal?: 'LEFT' | 'CENTER' | 'RIGHT' | 'JUSTIFIED'\n textHorizontalAlignment?: 'LEFT' | 'CENTER' | 'RIGHT' | 'JUSTIFIED'\n textAlignVertical?: 'TOP' | 'CENTER' | 'BOTTOM'\n textVerticalAlignment?: 'TOP' | 'CENTER' | 'BOTTOM'\n textAutoResize?: 'none' | 'width' | 'height'\n}\n\ntype NodeProps = StyleProps & {\n name?: string\n key?: string | number\n children?: unknown\n bind?: Record<string, unknown>\n visible?: boolean | ComponentProperty<boolean>\n /** The modes the layer shows collections in, as the Appearance panel sets them. */\n mode?: DesignMode | DesignMode[]\n [key: string]: unknown\n}\n\nexport type BaseProps = NodeProps & { properties?: never }\n\n/** An `<Ellipse>`'s arc: angles in degrees, clockwise from three o'clock, and its hole. */\nexport type EllipseProps = {\n startAngle?: number\n endAngle?: number\n /** The hole as a share of the ellipse, from 0 (none) to 1. */\n innerRadius?: number\n}\n/** A `<Vector>`'s path, in SVG's syntax as `d` or as Figma's `vectorPaths`. */\nexport type VectorProps = {\n /** Path data as SVG writes it, filled under `fillRule`; an open subpath fills only without a stroke. */\n d?: string\n fillRule?: 'nonzero' | 'evenodd'\n /** Paths with their own winding rules, as export writes them; `NONE` draws an open path. */\n paths?: Array<{ windingRule: 'NONZERO' | 'EVENODD' | 'NONE'; data: string }>\n}\nexport type TextProps = BaseProps\n\n/** A `<Span>`'s props: the character styles of `<Text>`, under the same names. */\nexport type SpanProps = Pick<\n StyleProps,\n | 'size'\n | 'fontSize'\n | 'font'\n | 'fontFamily'\n | 'weight'\n | 'fontWeight'\n | 'color'\n | 'fill'\n | 'fills'\n | 'lineHeight'\n | 'letterSpacing'\n | 'fontFeatures'\n | 'fontVariations'\n | 'lang'\n> & {\n key?: string | number\n style?: Record<string, unknown>\n italic?: boolean\n textDecoration?: 'none' | 'underline' | 'strikethrough'\n textDecorationStyle?: 'solid' | 'dotted' | 'wavy'\n textDecorationColor?: string | Color | Fill\n textDecorationThickness?: number | 'auto'\n textUnderlineOffset?: number | 'auto'\n textDecorationSkipInk?: boolean\n children?: unknown\n}\n\n/** A `<Paragraph>`'s props: a list item at `level` 1–5, or a plain paragraph, and its spacing. */\nexport type ParagraphProps = {\n key?: string | number\n list?: 'ordered' | 'unordered'\n level?: number\n spacing?: number\n listSpacing?: number\n indent?: number\n children?: unknown\n}\n\nexport type ComponentProps = BaseProps\n\nexport type InstanceProps = NodeProps & {\n component?: string\n componentId?: string\n of?: string | ComponentProperty<string>\n /** Show the instance's own properties on instances of the component it is in, as Figma does. */\n exposed?: boolean\n /** Values by property ID or name, or an exposed nested instance's values by its name. */\n properties?: Record<string, string | boolean | number | Record<string, string | boolean | number>>\n}\n","import type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'\nimport {\n behaviourFromSpec,\n withBehaviour,\n type BehaviourKind,\n type BehaviourSpec\n} from '@pairdraw/scene-graph/behaviours'\nimport { createComponentPropertyId } from '@pairdraw/scene-graph/components'\nimport { createSlotProperty } from '@pairdraw/scene-graph/slots'\n\nimport { node, type TreeNode } from '../tree'\n\n/** What a Reka UI element is to the component it builds. */\nexport type RekaRole =\n | { role: 'root'; kind: BehaviourKind }\n /** A Reka subcomponent drawn by a slot of the component, such as a switch's thumb. */\n | { role: 'part'; part: string }\n /** One of a slot's repeated parts, such as a tab trigger in the tab list. */\n | { role: 'repeat'; container: string }\n /** The text layer a text value shows, which becomes the field's text property. */\n | { role: 'input'; valueId: string }\n /** A Reka wrapper with no state of its own, drawn as a plain frame. */\n | { role: 'frame' }\n\nconst root = (kind: BehaviourKind): RekaRole => ({ role: 'root', kind })\nconst part = (id: string): RekaRole => ({ role: 'part', part: id })\nconst repeat = (container: string): RekaRole => ({ role: 'repeat', container })\nconst input = (valueId: string): RekaRole => ({ role: 'input', valueId })\n\n/**\n * Design JSX's Reka UI elements, by namespace and part, after Reka's own anatomy: `Switch.Root`\n * is a main component that behaves as a switch and `Switch.Thumb` its thumb slot. A group's\n * `Item` is the component of its items when written on its own, and an item when it names one\n * with `of`, as an `Instance` does.\n */\nconst REKA_PARTS = {\n Button: { Root: root('button') },\n Toggle: { Root: root('toggle') },\n Switch: { Root: root('switch'), Thumb: part('thumb') },\n Checkbox: { Root: root('checkbox'), Indicator: part('indicator') },\n RadioGroup: { Root: root('radioGroup'), Item: root('radio'), Indicator: part('indicator') },\n ToggleGroup: { Root: root('toggleGroup'), Item: root('toggle') },\n Slider: {\n Root: root('slider'),\n Track: part('track'),\n Range: part('range'),\n Thumb: part('thumb')\n },\n Progress: { Root: root('progress'), Track: part('track'), Indicator: part('indicator') },\n Tabs: {\n Root: root('tabs'),\n List: part('list'),\n Trigger: repeat('list'),\n Content: repeat('panels')\n },\n Collapsible: { Root: root('collapsible'), Trigger: part('trigger'), Content: part('content') },\n Accordion: {\n Root: root('accordion'),\n Item: root('collapsible'),\n Header: { role: 'frame' },\n Trigger: part('trigger'),\n Content: part('content')\n },\n NumberField: {\n Root: root('numberField'),\n Input: input('text'),\n Increment: part('increment'),\n Decrement: part('decrement')\n },\n TextField: { Root: root('textField'), Input: input('value') },\n Textarea: { Root: root('textarea'), Input: input('value') }\n} as const satisfies Readonly<Record<string, Readonly<Record<string, RekaRole>>>>\n\n/** Each Reka namespace and its parts, as typed elements are built from them. */\nexport type RekaNamespaces = typeof REKA_PARTS\n\n/** The same elements, looked up by any element name, as parsing and export do. */\nexport const REKA_ELEMENTS: Readonly<Record<string, Readonly<Record<string, RekaRole>>>> =\n REKA_PARTS\n\n/** The container a repeated part goes in when written directly under its root. */\nconst CONTAINER_NAMES: Record<string, string> = { list: 'List', panels: 'Panels', items: 'Items' }\n\n/** The role of a Reka element type such as `Switch.Thumb`, or undefined for other elements. */\nexport function rekaRole(type: string): RekaRole | undefined {\n const dot = type.indexOf('.')\n if (dot === -1) return undefined\n const namespace = REKA_ELEMENTS[type.slice(0, dot)] as Record<string, RekaRole> | undefined\n return namespace?.[type.slice(dot + 1)]\n}\n\n/** The element type for a part container that JSX leaves implicit. */\nconst containerType = (container: string) => `reka-container:${container}`\n\nexport function containerPart(type: string): string | undefined {\n return type.startsWith('reka-container:') ? type.slice('reka-container:'.length) : undefined\n}\n\n/** Whether an element names an existing component, as an item of a group does. */\nexport function namesComponent(props: Record<string, unknown>): boolean {\n return props.of !== undefined || props.component !== undefined || props.componentId !== undefined\n}\n\nconst GROUPS = new Set<BehaviourKind>(['radioGroup', 'toggleGroup', 'accordion'])\n\n/** The container slot a child written directly under a root belongs in, if any. */\nfunction containerOf(child: TreeNode, kind: BehaviourKind): string | undefined {\n const role = rekaRole(child.type)\n if (role?.role === 'repeat') return role.container\n if (GROUPS.has(kind) && role?.role === 'root' && namesComponent(child.props)) return 'items'\n return undefined\n}\n\n/**\n * A root's children with repeated parts and group items that are written directly under it\n * wrapped in their container slot, as the behaviour binds them: tab panels in Panels, a group's\n * items in Items. Containers the JSX writes itself are kept.\n */\nexport function wrapRepeatedParts(tree: TreeNode, kind: BehaviourKind): TreeNode['children'] {\n const result: TreeNode['children'] = []\n let open: TreeNode | null = null\n for (const child of tree.children) {\n const container = typeof child === 'string' ? undefined : containerOf(child, kind)\n if (!container || typeof child === 'string') {\n open = null\n result.push(child)\n continue\n }\n if (open?.type !== containerType(container)) {\n open = node(containerType(container), {\n name: CONTAINER_NAMES[container] ?? container,\n flex: kind === 'toggleGroup' ? 'row' : 'col',\n gap: kind === 'toggleGroup' ? 4 : 8\n })\n result.push(open)\n }\n open.children.push(child)\n }\n return result\n}\n\n/** What a root collects from its parts while they render. */\nexport interface RekaScope {\n kind: BehaviourKind\n ownerId: string\n /** Slot property ids by part, shared by every variant of a set. */\n slots: Map<string, string>\n /** Text property ids by value, defined once on the root. */\n texts: Map<string, string>\n}\n\nexport function createScope(kind: BehaviourKind, ownerId: string): RekaScope {\n return { kind, ownerId, slots: new Map(), texts: new Map() }\n}\n\n/** Make a rendered part frame its part's slot, with the id the part has in this component. */\nexport function bindPart(graph: SceneGraph, scope: RekaScope, frame: SceneNode, partId: string) {\n const id = scope.slots.get(partId) ?? createComponentPropertyId()\n if (!createSlotProperty(graph, frame.id, id))\n throw new Error(`<${partId}> must be inside a main component`)\n scope.slots.set(partId, id)\n}\n\n/** Make a rendered text layer show the value's text property, defined on the root. */\nexport function bindInput(\n graph: SceneGraph,\n scope: RekaScope,\n text: SceneNode,\n valueId: string,\n propertyName: string\n) {\n let id = scope.texts.get(valueId)\n if (!id) {\n id = createComponentPropertyId()\n scope.texts.set(valueId, id)\n const owner = graph.getNode(scope.ownerId)\n graph.updateNode(scope.ownerId, {\n componentPropertyDefinitions: [\n ...(owner?.componentPropertyDefinitions ?? []),\n { id, name: propertyName, type: 'TEXT', defaultValue: text.text }\n ]\n })\n }\n graph.updateNode(text.id, {\n componentPropertyReferences: [\n ...text.componentPropertyReferences,\n { propertyId: id, field: 'TEXT' }\n ]\n })\n}\n\n/** Root props that describe the behaviour rather than the drawing. */\nexport const BEHAVIOUR_PROPS = [\n 'modelValue',\n 'open',\n 'disabled',\n 'filled',\n 'states',\n 'min',\n 'max',\n 'step',\n 'defaultValue'\n] as const\n\n/** A value bound to a component property by name; a variant property may name its on and off. */\nexport type BindingProp = string | { property: string; on?: string; off?: string }\n\nfunction isBinding(value: unknown): value is BindingProp {\n return (\n typeof value === 'string' ||\n (typeof value === 'object' &&\n value !== null &&\n 'property' in value &&\n typeof value.property === 'string')\n )\n}\n\n/** The spec a root's props give: values by property name, a range, and states. */\nfunction rootSpec(kind: BehaviourKind, props: Record<string, unknown>): BehaviourSpec {\n const values: NonNullable<BehaviourSpec['values']> = {}\n const main = kind === 'collapsible' ? props.open : props.modelValue\n if (isBinding(main)) values[kind === 'collapsible' ? 'open' : 'value'] = main\n if (isBinding(props.disabled)) values.disabled = props.disabled\n if (isBinding(props.filled)) values.filled = props.filled\n const range = Object.fromEntries(\n (['min', 'max', 'step'] as const).flatMap((key) =>\n typeof props[key] === 'number' ? [[key, props[key]]] : []\n )\n )\n if (typeof props.defaultValue === 'number') range.default = props.defaultValue\n const spec: BehaviourSpec = { kind }\n if (Object.keys(values).length) spec.values = values\n if (Object.keys(range).length) spec.numbers = { value: range }\n if (typeof props.states === 'string') spec.states = props.states\n return spec\n}\n\n/** Store the behaviour a rendered root describes, with the slots and texts its parts made. */\nexport function finishRoot(\n graph: SceneGraph,\n scope: RekaScope,\n props: Record<string, unknown>\n): void {\n const owner = graph.getNode(scope.ownerId)\n if (!owner) return\n const behaviour = behaviourFromSpec(graph, owner, rootSpec(scope.kind, props))\n behaviour.parts = { ...behaviour.parts, ...Object.fromEntries(scope.slots) }\n behaviour.texts = {\n ...behaviour.texts,\n ...Object.fromEntries([...scope.texts].map(([valueId, id]) => [valueId, { propertyId: id }]))\n }\n graph.updateNode(owner.id, { pluginData: withBehaviour(owner, behaviour) })\n}\n","import { node, type BaseProps, type TreeNode } from '../tree'\nimport { REKA_ELEMENTS, type BindingProp, type RekaNamespaces } from './index'\n\n/** Props of a Reka element: a frame's, plus the behaviour a root binds and a group item's component. */\nexport interface RekaProps extends BaseProps {\n modelValue?: BindingProp\n open?: BindingProp\n disabled?: BindingProp\n filled?: BindingProp\n /** The variant property whose values draw rest, hover, pressed, focus, and disabled. */\n states?: string\n min?: number\n max?: number\n step?: number\n defaultValue?: number\n /** For a group's item: the component or set it is an instance of. */\n of?: string\n}\n\ntype Child = TreeNode | string\nexport type RekaElement = (props?: RekaProps, ...children: Child[]) => TreeNode\n\n/** One Reka namespace as element functions, such as `Switch.Root` and `Switch.Thumb`. */\nfunction namespace<N extends keyof RekaNamespaces>(name: N) {\n const element =\n (part: string): RekaElement =>\n (props = {}, ...children) =>\n node(`${name}.${part}`, children.length > 0 ? { ...props, children } : props)\n return Object.fromEntries(\n Object.keys(REKA_ELEMENTS[name]).map((part) => [part, element(part)])\n ) as { [P in keyof RekaNamespaces[N]]: RekaElement }\n}\n\nexport const Button = namespace('Button')\nexport const Toggle = namespace('Toggle')\nexport const Switch = namespace('Switch')\nexport const Checkbox = namespace('Checkbox')\nexport const RadioGroup = namespace('RadioGroup')\nexport const ToggleGroup = namespace('ToggleGroup')\nexport const Slider = namespace('Slider')\nexport const Progress = namespace('Progress')\nexport const Tabs = namespace('Tabs')\nexport const Collapsible = namespace('Collapsible')\nexport const Accordion = namespace('Accordion')\nexport const NumberField = namespace('NumberField')\nexport const TextField = namespace('TextField')\nexport const Textarea = namespace('Textarea')\n"],"mappings":";;;AAiBA,SAAS,gBAAgB,UAAwD;CAC/E,OAAO,SAAS,SAAS,UACvB,OAAO,UAAU,YAAY,MAAM,SAAA,KAAoB,MAAM,WAAW,CAAC,KAAK,CAChF;AACF;;;;;AAMA,SAAgB,YAAY,MAAwB;CAClD,OAAO,KAAK,SAAS,QAAQ,UAA2B,OAAO,UAAU,QAAQ,CAAC,CAAC,KAAK,EAAE;AAC5F;AAEA,SAAgB,WAAW,GAA2B;CACpD,IAAI,MAAM,QAAQ,OAAO,MAAM,UAAU,OAAO;CAChD,OACE,UAAU,KACV,OAAO,EAAE,SAAS,YAClB,WAAW,KACX,cAAc,KACd,MAAM,QAAQ,EAAE,QAAQ;AAE5B;AASA,SAAS,eAAe,GAA+B;CACrD,OAAO,MAAM,QAAQ,OAAO,MAAM,YAAY,UAAU,KAAK,WAAW;AAC1E;;;;;AAMA,SAAgB,cAAc,SAAkB,QAAQ,GAAoB;CAC1E,IAAI,QAAQ,KAA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,CAAC,SAAS,EAAE,YAAY,GAAG,CAAC,CAAC,CAAC;CAC9F;CACA,MAAM,WAAW,MAAM,IAAI,EAAE,YAAY,cAAc,OAAO,SAAS,EAAE,CAAC;AAC5E;;;;ACrOA,SAAS,UAA0C,MAAS;CAC1D,MAAM,WACH,UACA,QAAQ,CAAC,GAAG,GAAG,aACd,KAAK,GAAG,KAAK,GAAG,QAAQ,SAAS,SAAS,IAAI;EAAE,GAAG;EAAO;CAAS,IAAI,KAAK;CAChF,OAAO,OAAO,YACZ,OAAO,KAAK,cAAc,KAAK,CAAC,CAAC,KAAK,SAAS,CAAC,MAAM,QAAQ,IAAI,CAAC,CAAC,CACtE;AACF;AAEA,MAAa,SAAS,UAAU,QAAQ;AACxC,MAAa,SAAS,UAAU,QAAQ;AACxC,MAAa,SAAS,UAAU,QAAQ;AACxC,MAAa,WAAW,UAAU,UAAU;AAC5C,MAAa,aAAa,UAAU,YAAY;AAChD,MAAa,cAAc,UAAU,aAAa;AAClD,MAAa,SAAS,UAAU,QAAQ;AACxC,MAAa,WAAW,UAAU,UAAU;AAC5C,MAAa,OAAO,UAAU,MAAM;AACpC,MAAa,cAAc,UAAU,aAAa;AAClD,MAAa,YAAY,UAAU,WAAW;AAC9C,MAAa,cAAc,UAAU,aAAa;AAClD,MAAa,YAAY,UAAU,WAAW;AAC9C,MAAa,WAAW,UAAU,UAAU"}
1
+ {"version":3,"file":"elements.js","names":[],"sources":["../../../src/tree.ts","../../../src/behaviours/index.ts","../../../src/behaviours/elements.ts"],"sourcesContent":["import type { Effect, Fill } from '@pairdraw/scene-graph'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\n\nimport type { ComponentProperty } from './component-properties'\nimport type { DesignMode, DesignVariable } from './variables'\n\nexport interface TreeNode {\n type: string\n props: Record<string, unknown>\n children: (TreeNode | string)[]\n /** Where the element was written, when the source is known. */\n source?: { line: number }\n}\n\n/** A fragment (`<>…</>`) groups siblings without creating a node of its own. */\nexport const FRAGMENT = ''\n\nfunction inlineFragments(children: (TreeNode | string)[]): (TreeNode | string)[] {\n return children.flatMap((child) =>\n typeof child !== 'string' && child.type === FRAGMENT ? child.children : [child]\n )\n}\n\n/**\n * The text an element holds as children, such as a sticky note's body or a connector's label.\n * Elements among its children are not text and are skipped.\n */\nexport function plainTextOf(tree: TreeNode): string {\n return tree.children.filter((child): child is string => typeof child === 'string').join('')\n}\n\nexport function isTreeNode(x: unknown): x is TreeNode {\n if (x === null || typeof x !== 'object') return false\n return (\n 'type' in x &&\n typeof x.type === 'string' &&\n 'props' in x &&\n 'children' in x &&\n Array.isArray(x.children)\n )\n}\n\ntype FunctionComponent = (props: Record<string, unknown>) => unknown\n\ninterface ReactElement {\n type: unknown\n props: Record<string, unknown>\n}\n\nfunction isReactElement(x: unknown): x is ReactElement {\n return x !== null && typeof x === 'object' && 'type' in x && 'props' in x\n}\n\n/**\n * Resolve any element-like value (ReactElement, TreeNode, function component)\n * into a TreeNode. Handles recursive function components up to depth 100.\n */\nexport function resolveToTree(element: unknown, depth = 0): TreeNode | null {\n if (depth > 100) throw new Error('Component resolution depth exceeded')\n if (element == null) return null\n if (isTreeNode(element)) return element\n if (!isReactElement(element)) return null\n\n if (typeof element.type === 'function') {\n const component = element.type as FunctionComponent\n return resolveToTree(component(element.props), depth + 1)\n }\n\n if (typeof element.type === 'string') {\n const children: (TreeNode | string)[] = []\n const elChildren = element.props.children\n if (elChildren != null) {\n const childArray = Array.isArray(elChildren) ? elChildren : [elChildren]\n for (const child of childArray.flat()) {\n if (child == null) continue\n if (typeof child === 'string' || typeof child === 'number') {\n children.push(String(child))\n } else {\n const resolved = resolveToTree(child, depth + 1)\n if (resolved) children.push(resolved)\n }\n }\n }\n const { children: _, ...props } = element.props\n return { type: element.type, props, children: inlineFragments(children) }\n }\n\n return null\n}\n\nfunction resolveChild(child: unknown): TreeNode | string | null {\n if (child == null) return null\n if (typeof child === 'string' || typeof child === 'number') return String(child)\n return resolveToTree(child)\n}\n\nexport function node(\n type: string,\n props: { children?: unknown; [key: string]: unknown }\n): TreeNode {\n const { children, ...rest } = props\n const processed = [children]\n .flat(Infinity)\n .map(resolveChild)\n .filter((c): c is TreeNode | string => c !== null)\n return { type, props: rest, children: inlineFragments(processed) }\n}\n\nexport type PaintProp = string | Color | Fill | DesignVariable\n\nexport type StyleProps = {\n flex?: 'row' | 'col' | 'column'\n flow?: 'auto' | 'ltr' | 'rtl'\n dir?: 'auto' | 'ltr' | 'rtl'\n gap?: number | DesignVariable\n wrap?: boolean\n rowGap?: number | DesignVariable\n columnGap?: number | DesignVariable\n justify?: 'start' | 'end' | 'center' | 'between' | 'around'\n justifyContent?: 'start' | 'end' | 'center' | 'between' | 'around'\n items?: 'start' | 'end' | 'center' | 'stretch' | 'baseline'\n align?: 'start' | 'end' | 'center' | 'stretch' | 'baseline'\n alignItems?: 'start' | 'end' | 'center' | 'stretch' | 'baseline'\n grow?: number\n\n w?: number | 'fill' | 'hug' | DesignVariable\n h?: number | 'fill' | 'hug' | DesignVariable\n minW?: number\n maxW?: number\n minH?: number\n maxH?: number\n\n x?: number\n y?: number\n\n p?: number | DesignVariable\n px?: number | DesignVariable\n py?: number | DesignVariable\n pt?: number | DesignVariable\n pr?: number | DesignVariable\n pb?: number | DesignVariable\n pl?: number | DesignVariable\n\n bg?: PaintProp\n fill?: PaintProp\n fills?: PaintProp[]\n stroke?: PaintProp\n strokeWidth?: number | DesignVariable\n strokeAlign?: 'inside' | 'outside' | 'center'\n strokeDash?: number[] | boolean\n dashPattern?: number[]\n rounded?: number | DesignVariable\n roundedTL?: number | DesignVariable\n roundedTR?: number | DesignVariable\n roundedBL?: number | DesignVariable\n roundedBR?: number | DesignVariable\n cornerSmoothing?: number\n opacity?: number | DesignVariable\n blendMode?: string\n mask?: boolean | 'alpha' | 'luminance' | 'vector'\n rotate?: number\n rotation?: number\n /** Reflects the layer across its vertical centre line, before it turns. */\n flipX?: boolean\n /** Reflects the layer across its horizontal centre line, before it turns. */\n flipY?: boolean\n overflow?: 'hidden' | 'visible'\n shadow?: string\n blur?: number\n effects?: Effect[]\n\n size?: number | DesignVariable\n fontSize?: number | DesignVariable\n /** Pixels, or a percent of the font size such as `'150%'`. */\n lineHeight?: number | `${number}%` | 'auto' | DesignVariable\n /** Pixels, or a percent of the font size such as `'5%'`. */\n letterSpacing?: number | `${number}%` | DesignVariable\n /** OpenType features on or off by tag, as CSS's `font-feature-settings`: `{ tnum: true }`. */\n fontFeatures?: Record<string, boolean>\n /** Variable-font axis values by tag, as CSS's `font-variation-settings`: `{ wght: 650 }`. */\n fontVariations?: Record<string, number>\n /** The language the text is in, as a BCP 47 tag such as `de` or `sr-Latn`. */\n lang?: string | null\n /**\n * Whether a variable font's optical size follows the font size (`auto`, the default) or takes\n * the `opsz` in `fontVariations` (`none`), as CSS's `font-optical-sizing`.\n */\n fontOpticalSizing?: 'auto' | 'none'\n font?: string\n fontFamily?: string\n weight?: number | 'bold' | 'medium' | 'normal'\n fontWeight?: number | 'bold' | 'medium' | 'normal'\n color?: PaintProp\n text?: string | ComponentProperty<string>\n characters?: string\n textAlign?: 'left' | 'center' | 'right' | 'justified'\n textAlignHorizontal?: 'LEFT' | 'CENTER' | 'RIGHT' | 'JUSTIFIED'\n textHorizontalAlignment?: 'LEFT' | 'CENTER' | 'RIGHT' | 'JUSTIFIED'\n textAlignVertical?: 'TOP' | 'CENTER' | 'BOTTOM'\n textVerticalAlignment?: 'TOP' | 'CENTER' | 'BOTTOM'\n textAutoResize?: 'none' | 'width' | 'height'\n}\n\ntype NodeProps = StyleProps & {\n name?: string\n key?: string | number\n children?: unknown\n bind?: Record<string, unknown>\n visible?: boolean | ComponentProperty<boolean>\n /** The modes the layer shows collections in, as the Appearance panel sets them. */\n mode?: DesignMode | DesignMode[]\n [key: string]: unknown\n}\n\nexport type BaseProps = NodeProps & { properties?: never }\n\n/** An `<Ellipse>`'s arc: angles in degrees, clockwise from three o'clock, and its hole. */\nexport type EllipseProps = {\n startAngle?: number\n endAngle?: number\n /** The hole as a share of the ellipse, from 0 (none) to 1. */\n innerRadius?: number\n}\n/** A `<Vector>`'s path, in SVG's syntax as `d` or as Figma's `vectorPaths`. */\nexport type VectorProps = {\n /** Path data as SVG writes it, filled under `fillRule`; an open subpath fills only without a stroke. */\n d?: string\n fillRule?: 'nonzero' | 'evenodd'\n /** Paths with their own winding rules, as export writes them; `NONE` draws an open path. */\n paths?: Array<{ windingRule: 'NONZERO' | 'EVENODD' | 'NONE'; data: string }>\n}\nexport type TextProps = BaseProps\n\n/** A `<Span>`'s props: the character styles of `<Text>`, under the same names. */\nexport type SpanProps = Pick<\n StyleProps,\n | 'size'\n | 'fontSize'\n | 'font'\n | 'fontFamily'\n | 'weight'\n | 'fontWeight'\n | 'color'\n | 'fill'\n | 'fills'\n | 'lineHeight'\n | 'letterSpacing'\n | 'fontFeatures'\n | 'fontVariations'\n | 'lang'\n> & {\n key?: string | number\n style?: Record<string, unknown>\n italic?: boolean\n textDecoration?: 'none' | 'underline' | 'strikethrough'\n textDecorationStyle?: 'solid' | 'dotted' | 'wavy'\n textDecorationColor?: string | Color | Fill\n textDecorationThickness?: number | 'auto'\n textUnderlineOffset?: number | 'auto'\n textDecorationSkipInk?: boolean\n children?: unknown\n}\n\n/** A `<Paragraph>`'s props: a list item at `level` 1–5, or a plain paragraph, and its spacing. */\nexport type ParagraphProps = {\n key?: string | number\n list?: 'ordered' | 'unordered'\n level?: number\n spacing?: number\n listSpacing?: number\n indent?: number\n children?: unknown\n}\n\nexport type ComponentProps = BaseProps\n\nexport type InstanceProps = NodeProps & {\n component?: string\n componentId?: string\n of?: string | ComponentProperty<string>\n /** Show the instance's own properties on instances of the component it is in, as Figma does. */\n exposed?: boolean\n /** Values by property ID or name, or an exposed nested instance's values by its name. */\n properties?: Record<string, string | boolean | number | Record<string, string | boolean | number>>\n}\n","import type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'\nimport {\n behaviourFromSpec,\n validateChoiceValues,\n withBehaviour,\n type BehaviourKind,\n type BehaviourSpec\n} from '@pairdraw/scene-graph/behaviours'\nimport { createComponentPropertyId } from '@pairdraw/scene-graph/components'\nimport { createSlotProperty } from '@pairdraw/scene-graph/slots'\n\nimport { node, type TreeNode } from '../tree'\n\n/** What a Reka UI element is to the component it builds. */\nexport type RekaRole =\n | { role: 'root'; kind: BehaviourKind }\n /** A Reka subcomponent drawn by a slot of the component, such as a switch's thumb. */\n | { role: 'part'; part: string }\n /** One of a slot's repeated parts, such as a tab trigger in the tab list. */\n | { role: 'repeat'; container: string }\n /** The text layer a text value shows, which becomes the field's text property. */\n | { role: 'input'; valueId: string }\n /** A Reka wrapper with no state of its own, drawn as a plain frame. */\n | { role: 'frame' }\n\nconst root = (kind: BehaviourKind): RekaRole => ({ role: 'root', kind })\nconst part = (id: string): RekaRole => ({ role: 'part', part: id })\nconst repeat = (container: string): RekaRole => ({ role: 'repeat', container })\nconst input = (valueId: string): RekaRole => ({ role: 'input', valueId })\n\n/**\n * Design JSX's Reka UI elements, by namespace and part, after Reka's own anatomy: `Switch.Root`\n * is a main component that behaves as a switch and `Switch.Thumb` its thumb slot. A group's\n * `Item` is the component of its items when written on its own, and an item when it names one\n * with `of`, as an `Instance` does.\n */\nconst REKA_PARTS = {\n Button: { Root: root('button') },\n Toggle: { Root: root('toggle') },\n Switch: { Root: root('switch'), Thumb: part('thumb') },\n Checkbox: { Root: root('checkbox'), Indicator: part('indicator') },\n RadioGroup: { Root: root('radioGroup'), Item: root('radio'), Indicator: part('indicator') },\n ToggleGroup: { Root: root('toggleGroup'), Item: root('toggle') },\n Slider: {\n Root: root('slider'),\n Track: part('track'),\n Range: part('range'),\n Thumb: part('thumb')\n },\n Progress: { Root: root('progress'), Track: part('track'), Indicator: part('indicator') },\n Tabs: {\n Root: root('tabs'),\n List: part('list'),\n Trigger: repeat('list'),\n Content: repeat('panels')\n },\n Collapsible: { Root: root('collapsible'), Trigger: part('trigger'), Content: part('content') },\n Accordion: {\n Root: root('accordion'),\n Item: root('collapsible'),\n Header: { role: 'frame' },\n Trigger: part('trigger'),\n Content: part('content')\n },\n NumberField: {\n Root: root('numberField'),\n Input: input('text'),\n Increment: part('increment'),\n Decrement: part('decrement')\n },\n TextField: { Root: root('textField'), Input: input('value') },\n Textarea: { Root: root('textarea'), Input: input('value') }\n} as const satisfies Readonly<Record<string, Readonly<Record<string, RekaRole>>>>\n\n/** Each Reka namespace and its parts, as typed elements are built from them. */\nexport type RekaNamespaces = typeof REKA_PARTS\n\n/** The same elements, looked up by any element name, as parsing and export do. */\nexport const REKA_ELEMENTS: Readonly<Record<string, Readonly<Record<string, RekaRole>>>> =\n REKA_PARTS\n\n/** The container a repeated part goes in when written directly under its root. */\nconst CONTAINER_NAMES: Record<string, string> = { list: 'List', panels: 'Panels', items: 'Items' }\n\n/** The role of a Reka element type such as `Switch.Thumb`, or undefined for other elements. */\nexport function rekaRole(type: string): RekaRole | undefined {\n const dot = type.indexOf('.')\n if (dot === -1) return undefined\n const namespace = REKA_ELEMENTS[type.slice(0, dot)] as Record<string, RekaRole> | undefined\n return namespace?.[type.slice(dot + 1)]\n}\n\n/** The element type for a part container that JSX leaves implicit. */\nconst containerType = (container: string) => `reka-container:${container}`\n\nexport function containerPart(type: string): string | undefined {\n return type.startsWith('reka-container:') ? type.slice('reka-container:'.length) : undefined\n}\n\n/** Whether an element names an existing component, as an item of a group does. */\nexport function namesComponent(props: Record<string, unknown>): boolean {\n return props.of !== undefined || props.component !== undefined || props.componentId !== undefined\n}\n\nconst GROUPS = new Set<BehaviourKind>(['radioGroup', 'toggleGroup', 'accordion'])\n\n/** The container slot a child written directly under a root belongs in, if any. */\nfunction containerOf(child: TreeNode, kind: BehaviourKind): string | undefined {\n const role = rekaRole(child.type)\n if (role?.role === 'repeat') return role.container\n if (GROUPS.has(kind) && role?.role === 'root' && namesComponent(child.props)) return 'items'\n return undefined\n}\n\n/**\n * A root's children with repeated parts and group items that are written directly under it\n * wrapped in their container slot, as the behaviour binds them: tab panels in Panels, a group's\n * items in Items. Containers the JSX writes itself are kept.\n */\nexport function wrapRepeatedParts(tree: TreeNode, kind: BehaviourKind): TreeNode['children'] {\n const result: TreeNode['children'] = []\n let open: TreeNode | null = null\n for (const child of tree.children) {\n const container = typeof child === 'string' ? undefined : containerOf(child, kind)\n if (!container || typeof child === 'string') {\n open = null\n result.push(child)\n continue\n }\n if (open?.type !== containerType(container)) {\n open = node(containerType(container), {\n name: CONTAINER_NAMES[container] ?? container,\n flex: kind === 'toggleGroup' ? 'row' : 'col',\n gap: kind === 'toggleGroup' ? 4 : 8\n })\n result.push(open)\n }\n open.children.push(child)\n }\n return result\n}\n\n/** What a root collects from its parts while they render. */\nexport interface RekaScope {\n kind: BehaviourKind\n ownerId: string\n /** Slot property ids by part, shared by every variant of a set. */\n slots: Map<string, string>\n /** Text property ids by value, defined once on the root. */\n texts: Map<string, string>\n}\n\nexport function createScope(kind: BehaviourKind, ownerId: string): RekaScope {\n return { kind, ownerId, slots: new Map(), texts: new Map() }\n}\n\n/** Make a rendered part frame its part's slot, with the id the part has in this component. */\nexport function bindPart(graph: SceneGraph, scope: RekaScope, frame: SceneNode, partId: string) {\n const id = scope.slots.get(partId) ?? createComponentPropertyId()\n if (!createSlotProperty(graph, frame.id, id))\n throw new Error(`<${partId}> must be inside a main component`)\n scope.slots.set(partId, id)\n}\n\n/** Make a rendered text layer show the value's text property, defined on the root. */\nexport function bindInput(\n graph: SceneGraph,\n scope: RekaScope,\n text: SceneNode,\n valueId: string,\n propertyName: string\n) {\n let id = scope.texts.get(valueId)\n if (!id) {\n id = createComponentPropertyId()\n scope.texts.set(valueId, id)\n const owner = graph.getNode(scope.ownerId)\n graph.updateNode(scope.ownerId, {\n componentPropertyDefinitions: [\n ...(owner?.componentPropertyDefinitions ?? []),\n { id, name: propertyName, type: 'TEXT', defaultValue: text.text }\n ]\n })\n }\n graph.updateNode(text.id, {\n componentPropertyReferences: [\n ...text.componentPropertyReferences,\n { propertyId: id, field: 'TEXT' }\n ]\n })\n}\n\n/** Root props that describe the behaviour rather than the drawing. */\nexport const BEHAVIOUR_PROPS = [\n 'modelValue',\n 'open',\n 'disabled',\n 'filled',\n 'states',\n 'min',\n 'max',\n 'step',\n 'defaultValue'\n] as const\n\n/** A value bound to a component property by name; a variant property may name its on and off. */\nexport type BindingProp = string | { property: string; on?: string; off?: string }\n\nfunction isBinding(value: unknown): value is BindingProp {\n return (\n typeof value === 'string' ||\n (typeof value === 'object' &&\n value !== null &&\n 'property' in value &&\n typeof value.property === 'string')\n )\n}\n\n/** The spec a root's props give: values by property name, a range, and states. */\nfunction rootSpec(kind: BehaviourKind, props: Record<string, unknown>): BehaviourSpec {\n const values: NonNullable<BehaviourSpec['values']> = {}\n const main = kind === 'collapsible' ? props.open : props.modelValue\n if (isBinding(main)) values[kind === 'collapsible' ? 'open' : 'value'] = main\n if (isBinding(props.disabled)) values.disabled = props.disabled\n if (isBinding(props.filled)) values.filled = props.filled\n const range = Object.fromEntries(\n (['min', 'max', 'step'] as const).flatMap((key) =>\n typeof props[key] === 'number' ? [[key, props[key]]] : []\n )\n )\n if (typeof props.defaultValue === 'number') range.default = props.defaultValue\n const spec: BehaviourSpec = { kind }\n if (Object.keys(values).length) spec.values = values\n if (Object.keys(range).length) spec.numbers = { value: range }\n if (typeof props.states === 'string') spec.states = props.states\n return spec\n}\n\n/** Store the behaviour a rendered root describes, with the slots and texts its parts made. */\nexport function finishRoot(\n graph: SceneGraph,\n scope: RekaScope,\n props: Record<string, unknown>\n): void {\n const owner = graph.getNode(scope.ownerId)\n if (!owner) return\n const behaviour = behaviourFromSpec(graph, owner, rootSpec(scope.kind, props))\n behaviour.parts = { ...behaviour.parts, ...Object.fromEntries(scope.slots) }\n behaviour.texts = {\n ...behaviour.texts,\n ...Object.fromEntries([...scope.texts].map(([valueId, id]) => [valueId, { propertyId: id }]))\n }\n // The parts are made while the root's children render, so their triggers are checked now.\n validateChoiceValues(graph, owner, behaviour)\n graph.updateNode(owner.id, { pluginData: withBehaviour(owner, behaviour) })\n}\n","import { node, type BaseProps, type TreeNode } from '../tree'\nimport { REKA_ELEMENTS, type BindingProp, type RekaNamespaces } from './index'\n\n/** Props of a Reka element: a frame's, plus the behaviour a root binds and a group item's component. */\nexport interface RekaProps extends BaseProps {\n modelValue?: BindingProp\n open?: BindingProp\n disabled?: BindingProp\n filled?: BindingProp\n /** The variant property whose values draw rest, hover, pressed, focus, and disabled. */\n states?: string\n min?: number\n max?: number\n step?: number\n defaultValue?: number\n /** For a group's item: the component or set it is an instance of. */\n of?: string\n}\n\ntype Child = TreeNode | string\nexport type RekaElement = (props?: RekaProps, ...children: Child[]) => TreeNode\n\n/** One Reka namespace as element functions, such as `Switch.Root` and `Switch.Thumb`. */\nfunction namespace<N extends keyof RekaNamespaces>(name: N) {\n const element =\n (part: string): RekaElement =>\n (props = {}, ...children) =>\n node(`${name}.${part}`, children.length > 0 ? { ...props, children } : props)\n return Object.fromEntries(\n Object.keys(REKA_ELEMENTS[name]).map((part) => [part, element(part)])\n ) as { [P in keyof RekaNamespaces[N]]: RekaElement }\n}\n\nexport const Button = namespace('Button')\nexport const Toggle = namespace('Toggle')\nexport const Switch = namespace('Switch')\nexport const Checkbox = namespace('Checkbox')\nexport const RadioGroup = namespace('RadioGroup')\nexport const ToggleGroup = namespace('ToggleGroup')\nexport const Slider = namespace('Slider')\nexport const Progress = namespace('Progress')\nexport const Tabs = namespace('Tabs')\nexport const Collapsible = namespace('Collapsible')\nexport const Accordion = namespace('Accordion')\nexport const NumberField = namespace('NumberField')\nexport const TextField = namespace('TextField')\nexport const Textarea = namespace('Textarea')\n"],"mappings":";;;AAiBA,SAAS,gBAAgB,UAAwD;CAC/E,OAAO,SAAS,SAAS,UACvB,OAAO,UAAU,YAAY,MAAM,SAAA,KAAoB,MAAM,WAAW,CAAC,KAAK,CAChF;AACF;;;;;AAMA,SAAgB,YAAY,MAAwB;CAClD,OAAO,KAAK,SAAS,QAAQ,UAA2B,OAAO,UAAU,QAAQ,CAAC,CAAC,KAAK,EAAE;AAC5F;AAEA,S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,6 +1,6 @@
1
- import { REKA_ELEMENTS, isTreeNode, resolveToTree } from "./behaviours/elements.js";
2
- import { BLEND_MODE, CONSTRAINT, ENUM_PROPS, LayerRefs, MASK_TYPE, TEXT_ALIGN, TEXT_ALIGN_VERTICAL, TEXT_AUTO_RESIZE, TEXT_CASE, TEXT_DECORATION, TEXT_DIRECTION, applyStrokeOverrides, assignComponentProperties, assignNamedProperties, bindProperties, componentPropNames as componentPropNames$1, elementPropWarnings, enumProp, exposeInstance, fillFromValue, inferComponentSetProperties, isColor, isFillValue, isVariable, layerPropsSchema, parseScriptInput, readElementProps, readLayerProps, svgLayerPropsSchema } from "./component-properties.js";
3
- import { DESIGN_JSX_STYLE_KEYS, designJSXProp, renderRekaNode } from "./behaviours/render.js";
1
+ import { REKA_ELEMENTS, isTreeNode, namesComponent, rekaRole, resolveToTree } from "./behaviours/elements.js";
2
+ import { BLEND_MODE, CONSTRAINT, ENUM_PROPS, LayerRefs, MASK_TYPE, TEXT_ALIGN, TEXT_ALIGN_VERTICAL, TEXT_AUTO_RESIZE, TEXT_CASE, TEXT_DECORATION, TEXT_DIRECTION, applyStrokeOverrides, assignComponentProperties, assignNamedProperties, bindProperties, componentPropNames as componentPropNames$1, elementPropWarnings, enumProp, exposeInstance, fillFromValue, inferComponentSetProperties, isColor, isComponentProperty, isFillValue, isLayerRef, isVariable, layerPropsSchema, parseScriptInput, readElementProps, readLayerProps, svgLayerPropsSchema } from "./component-properties.js";
3
+ import { DESIGN_JSX_STYLE_KEYS, DESIGN_JSX_SUPPORTED_PROPERTIES, designJSXProp, renderRekaNode } from "./behaviours/render.js";
4
4
  import { DESIGN_JSX_HELPERS, TEXT_CONTENT_NAMES, applyVariableDefinitions, bindVariableProp, designJSXHelpers, isShaderFill, isTextContent, requireVariableId, resolveForLayer, textContentFields, variableModes } from "./export/index.js";
5
5
  import { resolveConnectorEnds } from "./connectors.js";
6
6
  import { elementBindings, elementNodeType, elementOwnLayer, elementProps, elementSchema } from "./elements.js";
@@ -12,7 +12,7 @@ import * as v from "valibot";
12
12
  import { shaderUniformValueSchema, withShaderPaints } from "@pairdraw/scene-graph/shaders";
13
13
  import { omitBy } from "es-toolkit/object";
14
14
  import { uniq } from "es-toolkit/array";
15
- import { omit, pickBy } from "es-toolkit";
15
+ import { compact as compact$1, isPlainObject, isString, omit, pickBy, pull, range, uniq as uniq$1 } from "es-toolkit";
16
16
  import { parseCSSGridTracks, parseCSSNumber, parseCSSShadows } from "@pairdraw/scene-graph/css";
17
17
  import { autoLayoutSizingFields, fillSizingFields, parseAutoLayoutDirection, parseCounterAxisAlign, parsePrimaryAxisAlign } from "@pairdraw/scene-graph/layout";
18
18
  import { normalizeEffects } from "@pairdraw/scene-graph/effects";
@@ -497,6 +497,77 @@ function propsToOverrides(props, isText, parentLayout) {
497
497
  return o;
498
498
  }
499
499
  //#endregion
500
+ //#region src/order.ts
501
+ /** Whether an element defines a component: a component, a set, or a Reka root naming none. */
502
+ function definesComponent(node) {
503
+ const nodeType = elementNodeType(node.type);
504
+ if (nodeType === "COMPONENT" || nodeType === "COMPONENT_SET") return true;
505
+ return rekaRole(node.type)?.role === "root" && !namesComponent(node.props);
506
+ }
507
+ /** What the element itself defines or names, without its descendants. */
508
+ function ownUse(node) {
509
+ const { props } = node;
510
+ if (definesComponent(node)) {
511
+ const name = isString(props.name) ? props.name : "";
512
+ return {
513
+ defines: compact$1([name, isLayerRef(props.ref) && props.ref]),
514
+ names: [],
515
+ mayName: []
516
+ };
517
+ }
518
+ const of = props.component ?? props.componentId ?? props.of;
519
+ const component = isComponentProperty(of) ? of.defaultValue : of;
520
+ const assigned = [...Object.entries(props).filter(([key]) => !DESIGN_JSX_SUPPORTED_PROPERTIES.has(key)).map(([, value]) => value), ...isPlainObject(props.properties) ? Object.values(props.properties) : []];
521
+ const nested = assigned.filter(isPlainObject).flatMap((values) => Object.values(values));
522
+ return {
523
+ defines: [],
524
+ names: [...isString(component) || isLayerRef(component) ? [component] : [], ...assigned.filter(isLayerRef)],
525
+ mayName: [...assigned, ...nested].filter(isString)
526
+ };
527
+ }
528
+ /** Reads each element's components once, for every level an order is asked at. */
529
+ var RenderOrder = class {
530
+ uses = /* @__PURE__ */ new WeakMap();
531
+ use(node) {
532
+ const known = this.uses.get(node);
533
+ if (known) return known;
534
+ const parts = [ownUse(node), ...node.children.filter(isTreeNode).map((child) => this.use(child))];
535
+ const use = {
536
+ defines: uniq$1(parts.flatMap((part) => part.defines)),
537
+ names: uniq$1(parts.flatMap((part) => part.names)),
538
+ mayName: uniq$1(parts.flatMap((part) => part.mayName))
539
+ };
540
+ this.uses.set(node, use);
541
+ return use;
542
+ }
543
+ /**
544
+ * The indices of `siblings` in render order: those that define a component before those that
545
+ * name it, otherwise as written. When none is ready, what text values may name gives way
546
+ * first, so a text that matches a component's name never holds back a real reference; only
547
+ * components that do name each other keep the written order.
548
+ */
549
+ of(siblings) {
550
+ const uses = siblings.map((sibling) => this.use(sibling));
551
+ if (uses.every((use) => use.defines.length === 0)) return range(siblings.length);
552
+ const owners = /* @__PURE__ */ new Map();
553
+ uses.forEach((use, index) => {
554
+ for (const key of use.defines) owners.set(key, [...owners.get(key) ?? [], index]);
555
+ });
556
+ const siblingsDefining = (keys, index) => uniq$1(keys.flatMap((key) => owners.get(key) ?? [])).filter((owner) => owner !== index);
557
+ const needs = uses.map((use, index) => siblingsDefining(use.names, index));
558
+ const mayNeed = uses.map((use, index) => siblingsDefining(use.mayName, index));
559
+ const order = [];
560
+ const pending = range(siblings.length);
561
+ const rendered = (indices) => indices.every((index) => order.includes(index));
562
+ while (pending.length > 0) {
563
+ const next = pending.find((index) => rendered(needs[index]) && rendered(mayNeed[index])) ?? pending.find((index) => rendered(needs[index])) ?? pending[0];
564
+ order.push(next);
565
+ pull(pending, [next]);
566
+ }
567
+ return order;
568
+ }
569
+ };
570
+ //#endregion
500
571
  //#region src/overrides/vector.ts
501
572
  const FILL_RULES = {
502
573
  nonzero: "NONZERO",
@@ -616,6 +687,8 @@ async function renderRoots(services, graph, tree, options = {}) {
616
687
  if (roots.length === 0) throw new Error("JSX must return a Figma element (Frame, Text, etc)");
617
688
  const parentId = options.parentId ?? graph.getPages()[0].id;
618
689
  applyVariableDefinitions(graph, tree);
690
+ const originalChildCount = graph.getChildren(parentId).length;
691
+ const order = new RenderOrder();
619
692
  const nodes = [];
620
693
  const connectors = [];
621
694
  const refs = new LayerRefs();
@@ -627,12 +700,14 @@ async function renderRoots(services, graph, tree, options = {}) {
627
700
  else refs.mark(element.props.ref, node);
628
701
  options.onNode?.(element, node);
629
702
  };
630
- for (const root of roots) {
631
- const node = await renderNode(services, graph, root, parentId, onNode);
632
- if (options.x !== void 0) graph.updateNode(node.id, { x: options.x });
633
- if (options.y !== void 0) graph.updateNode(node.id, { y: options.y });
634
- nodes.push(node);
703
+ for (const index of order.of(roots)) {
704
+ const node = await renderNode(services, graph, roots[index], parentId, onNode, void 0, refs);
705
+ const { x, y } = options.positions?.[index] ?? options;
706
+ if (x !== void 0) graph.updateNode(node.id, { x });
707
+ if (y !== void 0) graph.updateNode(node.id, { y });
708
+ nodes[index] = node;
635
709
  }
710
+ nodes.forEach((node, index) => graph.insertChildAt(node.id, parentId, originalChildCount + index));
636
711
  const rootIds = nodes.map((node) => node.id);
637
712
  const warnings = [...refs.warnings, ...resolveConnectorEnds(graph, rootIds, connectors, refs)];
638
713
  if (!options.deferLayout) services.layout(graph, rootIds);
@@ -785,8 +860,12 @@ function selectsVariant(set, props) {
785
860
  * the props select one of its variants, and the first otherwise; the warning from
786
861
  * `componentReferenceWarnings` says so and how to pick one by ID.
787
862
  */
788
- function namedComponent(graph, props) {
863
+ function namedComponent(graph, props, refs) {
789
864
  const ref = props.component ?? props.componentId ?? props.of;
865
+ if (isLayerRef(ref)) {
866
+ const marked = graph.getNode(refs?.layerOf(ref) ?? "");
867
+ return marked?.type === "COMPONENT" || marked?.type === "COMPONENT_SET" ? marked : void 0;
868
+ }
790
869
  if (typeof ref !== "string") return void 0;
791
870
  const matches = componentsNamed(graph, ref);
792
871
  if (matches.length <= 1) return matches[0];
@@ -808,8 +887,8 @@ function findVariantInSet(graph, componentSet, props) {
808
887
  const variants = graph.getChildren(componentSet.id).filter((node) => node.type === "COMPONENT");
809
888
  return variants.find((variant) => Object.entries(requested).every(([key, value]) => variant.componentPropertyValues[key] === value)) ?? variants[0];
810
889
  }
811
- function resolveComponent(graph, props) {
812
- const named = namedComponent(graph, props);
890
+ function resolveComponent(graph, props, refs) {
891
+ const named = namedComponent(graph, props, refs);
813
892
  return named?.type === "COMPONENT_SET" ? findVariantInSet(graph, named, props) : named;
814
893
  }
815
894
  /**
@@ -820,17 +899,18 @@ function componentPropNames(graph, props) {
820
899
  const component = resolveComponent(graph, props);
821
900
  return component ? componentPropNames$1(graph, component) : [];
822
901
  }
823
- async function renderInstanceNode(graph, tree, parentId) {
902
+ async function renderInstanceNode(graph, tree, parentId, refs) {
824
903
  const parentLayout = graph.getNode(parentId)?.layoutMode ?? "NONE";
825
904
  const modes = variableModes(graph, tree.props.mode);
826
- const bound = bindProperties(graph, tree.props, "INSTANCE", parentId, componentIdNamed(graph));
905
+ const bound = bindProperties(graph, tree.props, "INSTANCE", parentId, componentIdNamed(graph, refs));
827
906
  const { props, bindings } = preparePropsForRender(graph, bound.props, false, {
828
907
  parentId,
829
908
  modes
830
909
  });
831
- const component = resolveComponent(graph, props);
910
+ const component = resolveComponent(graph, props, refs);
832
911
  if (!component) {
833
912
  const ref = props.component ?? props.componentId ?? props.of;
913
+ if (isLayerRef(ref)) throw new Error("<Instance> ref() marks no component rendered before it");
834
914
  throw new Error(`<Instance> component not found: ${typeof ref === "string" || typeof ref === "number" ? String(ref) : ""}`);
835
915
  }
836
916
  const overrides = {
@@ -852,8 +932,8 @@ async function renderInstanceNode(graph, tree, parentId) {
852
932
  graph.updateNode(instance.id, { instanceOverrides: instance.instanceOverrides });
853
933
  applyBindings(graph, instance.id, bindings);
854
934
  applyInstanceOverrides(graph, instance, tree.props.overrides);
855
- assignNamedProperties(graph, instance, props, componentIdNamed(graph));
856
- assignComponentProperties(graph, instance, props.properties, componentIdNamed(graph));
935
+ assignNamedProperties(graph, instance, props, componentIdNamed(graph, refs));
936
+ assignComponentProperties(graph, instance, props.properties, componentIdNamed(graph, refs));
857
937
  if (props.exposed === true) exposeInstance(graph, instance);
858
938
  return instance;
859
939
  } catch (error) {
@@ -914,8 +994,8 @@ function layerMetadata(modes, references) {
914
994
  };
915
995
  }
916
996
  /** The component a swap property's default names, by ID or name, as `<Instance of>` finds it. */
917
- function componentIdNamed(graph) {
918
- return (name) => resolveComponent(graph, { of: name })?.id;
997
+ function componentIdNamed(graph, refs) {
998
+ return (name) => resolveComponent(graph, { of: name }, refs)?.id;
919
999
  }
920
1000
  /** The fields and variable bindings an element's props set on a `nodeType` node under `parentId`. */
921
1001
  function elementOverrides(graph, nodeType, tree, parentId) {
@@ -944,8 +1024,8 @@ function elementOverrides(graph, nodeType, tree, parentId) {
944
1024
  bindings
945
1025
  };
946
1026
  }
947
- async function renderNode(services, graph, tree, parentId, onNode, scope) {
948
- const node = await renderNodeContent(services, graph, tree, parentId, onNode, scope);
1027
+ async function renderNode(services, graph, tree, parentId, onNode, scope, refs) {
1028
+ const node = await renderNodeContent(services, graph, tree, parentId, onNode, scope, refs);
949
1029
  onNode?.(tree, node);
950
1030
  return node;
951
1031
  }
@@ -953,22 +1033,22 @@ async function renderNode(services, graph, tree, parentId, onNode, scope) {
953
1033
  * The elements rendered their own way rather than as the layer their definition names, or null
954
1034
  * for any other element.
955
1035
  */
956
- function renderOwnElement(services, graph, tree, parentId) {
1036
+ function renderOwnElement(services, graph, tree, parentId, refs) {
957
1037
  switch (tree.type) {
958
1038
  case "icon":
959
1039
  case "svg": return renderArtworkNode(services, graph, tree, parentId);
960
- case "instance": return renderInstanceNode(graph, tree, parentId);
1040
+ case "instance": return renderInstanceNode(graph, tree, parentId, refs);
961
1041
  default: {
962
1042
  const element = elementOwnLayer(tree.type);
963
1043
  return element ? Promise.resolve(renderOwnLayerElement(graph, tree, parentId, element)) : null;
964
1044
  }
965
1045
  }
966
1046
  }
967
- async function renderNodeContent(services, graph, tree, parentId, onNode, scope) {
968
- const own = renderOwnElement(services, graph, tree, parentId);
1047
+ async function renderNodeContent(services, graph, tree, parentId, onNode, scope, refs) {
1048
+ const own = renderOwnElement(services, graph, tree, parentId, refs);
969
1049
  if (own) return own;
970
1050
  const reka = await renderRekaNode(graph, tree, parentId, scope, {
971
- render: (child, childParentId, childScope) => renderNode(services, graph, child, childParentId, onNode, childScope),
1051
+ render: (child, childParentId, childScope) => renderNode(services, graph, child, childParentId, onNode, childScope, refs),
972
1052
  create: (nodeType, element, elementParentId) => {
973
1053
  const { overrides, bindings } = elementOverrides(graph, nodeType, element, elementParentId);
974
1054
  const created = graph.createNode(nodeType, elementParentId, overrides);
@@ -976,7 +1056,7 @@ async function renderNodeContent(services, graph, tree, parentId, onNode, scope)
976
1056
  placeVectorPaths(graph, created, element.props, (network) => services.vectorBounds(network));
977
1057
  return created;
978
1058
  },
979
- instance: (element, elementParentId) => renderInstanceNode(graph, element, elementParentId),
1059
+ instance: (element, elementParentId) => renderInstanceNode(graph, element, elementParentId, refs),
980
1060
  finishSet: (setId) => inferComponentSetProperties(graph, setId)
981
1061
  });
982
1062
  if (reka) return reka;
@@ -991,7 +1071,7 @@ async function renderNodeContent(services, graph, tree, parentId, onNode, scope)
991
1071
  if (typeof child === "string" || node.type === "TEXT" && isTextContent(child)) continue;
992
1072
  if (!isTreeNode(child)) continue;
993
1073
  if (node.type === "TEXT") throw new Error(`<${child.type}> cannot be inside <Text>`);
994
- await renderNode(services, graph, child, node.id, onNode, scope);
1074
+ await renderNode(services, graph, child, node.id, onNode, scope, refs);
995
1075
  }
996
1076
  if (node.type === "COMPONENT_SET") inferComponentSetProperties(graph, node.id);
997
1077
  return node;
@@ -1241,7 +1321,9 @@ function createDesignJSXRenderer(services) {
1241
1321
  /** Render a Design JSX string into the graph, one result per top-level element. */
1242
1322
  renderJSX: (graph, jsxString, options) => renderJSX(services, graph, jsxString, options),
1243
1323
  /** Render a tree built with the element functions into the graph. */
1244
- renderTree: (graph, tree, options) => renderTree(services, graph, tree, options)
1324
+ renderTree: (graph, tree, options) => renderTree(services, graph, tree, options),
1325
+ /** Render every top-level element of a tree at once, one result per root. */
1326
+ renderRoots: (graph, tree, options) => renderRoots(services, graph, tree, options)
1245
1327
  };
1246
1328
  }
1247
1329
  //#endregion