@pairdraw/design-jsx 0.19.1 → 0.20.0

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,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