@pairdraw/design-jsx 0.0.0-stage → 0.16.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.
- package/LICENSE +21 -0
- package/README.md +48 -2
- package/dist/chunks/attributes.js +32 -0
- package/dist/chunks/attributes.js.map +1 -0
- package/dist/chunks/behaviours/elements.js +321 -0
- package/dist/chunks/behaviours/elements.js.map +1 -0
- package/dist/chunks/behaviours/render.js +368 -0
- package/dist/chunks/behaviours/render.js.map +1 -0
- package/dist/chunks/component-properties.js +809 -0
- package/dist/chunks/component-properties.js.map +1 -0
- package/dist/chunks/components.js +78 -0
- package/dist/chunks/components.js.map +1 -0
- package/dist/chunks/connectors.js +290 -0
- package/dist/chunks/connectors.js.map +1 -0
- package/dist/chunks/effects.js +57 -0
- package/dist/chunks/effects.js.map +1 -0
- package/dist/chunks/elements.js +618 -0
- package/dist/chunks/elements.js.map +1 -0
- package/dist/chunks/export/behaviours.js +113 -0
- package/dist/chunks/export/behaviours.js.map +1 -0
- package/dist/chunks/export/bindings.js +273 -0
- package/dist/chunks/export/bindings.js.map +1 -0
- package/dist/chunks/export/decoration.js +96 -0
- package/dist/chunks/export/decoration.js.map +1 -0
- package/dist/chunks/export/font.js +17 -0
- package/dist/chunks/export/font.js.map +1 -0
- package/dist/chunks/export/icons.js +34 -0
- package/dist/chunks/export/icons.js.map +1 -0
- package/dist/chunks/export/index.js +1390 -0
- package/dist/chunks/export/index.js.map +1 -0
- package/dist/chunks/fields.js +1065 -0
- package/dist/chunks/fields.js.map +1 -0
- package/dist/chunks/index.js +438 -0
- package/dist/chunks/index.js.map +1 -0
- package/dist/chunks/jsx-dev-runtime.js +16 -0
- package/dist/chunks/jsx-dev-runtime.js.map +1 -0
- package/dist/index.d.ts +543 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +11 -0
- package/dist/jsx-dev-runtime.d.ts +2 -0
- package/dist/jsx-dev-runtime.js +2 -0
- package/dist/jsx-runtime.d.ts +44 -0
- package/dist/jsx-runtime.d.ts.map +1 -0
- package/dist/jsx-runtime.js +2 -0
- package/dist/tree.d.ts +261 -0
- package/dist/tree.d.ts.map +1 -0
- package/package.json +54 -4
- package/src/attributes.ts +30 -0
- package/src/behaviours/elements.ts +47 -0
- package/src/behaviours/index.ts +253 -0
- package/src/behaviours/render.ts +144 -0
- package/src/component-properties.ts +428 -0
- package/src/components.ts +109 -0
- package/src/connectors.ts +316 -0
- package/src/definitions.ts +277 -0
- package/src/effects.ts +80 -0
- package/src/elements.ts +321 -0
- package/src/enums.ts +182 -0
- package/src/export/behaviours.ts +143 -0
- package/src/export/bindings.ts +155 -0
- package/src/export/decoration.ts +39 -0
- package/src/export/font.ts +25 -0
- package/src/export/helpers.ts +75 -0
- package/src/export/icons.ts +42 -0
- package/src/export/index.ts +297 -0
- package/src/export/paint.ts +276 -0
- package/src/export/props.ts +369 -0
- package/src/export/state.ts +52 -0
- package/src/export/text.ts +155 -0
- package/src/export/value.ts +99 -0
- package/src/export/variables.ts +393 -0
- package/src/fields.ts +39 -0
- package/src/figjam-text.ts +37 -0
- package/src/global.d.ts +4 -0
- package/src/helpers.ts +135 -0
- package/src/index.ts +155 -0
- package/src/jsx-dev-runtime.ts +1 -0
- package/src/jsx-runtime.ts +51 -0
- package/src/mini-react.ts +23 -0
- package/src/overrides/effects.ts +39 -0
- package/src/overrides/fills.ts +56 -0
- package/src/overrides/state.ts +55 -0
- package/src/overrides/strokes.ts +109 -0
- package/src/overrides/text.ts +116 -0
- package/src/overrides/vector.ts +122 -0
- package/src/paints.ts +230 -0
- package/src/props-overrides.ts +481 -0
- package/src/reconcile.ts +134 -0
- package/src/reference/authoring.md +76 -0
- package/src/reference/examples.ts +49 -0
- package/src/reference.ts +19 -0
- package/src/refs.ts +48 -0
- package/src/render.ts +147 -0
- package/src/renderer.ts +598 -0
- package/src/scalar-bindings.ts +36 -0
- package/src/schema.ts +213 -0
- package/src/services.ts +36 -0
- package/src/shapes-with-text.ts +73 -0
- package/src/stickies.ts +72 -0
- package/src/streaming/index.ts +47 -0
- package/src/streaming/literals.ts +82 -0
- package/src/streaming/projection.ts +189 -0
- package/src/text-content.ts +233 -0
- package/src/transform.ts +78 -0
- package/src/tree.ts +285 -0
- package/src/types.ts +13 -0
- package/src/variables/graph.ts +265 -0
- package/src/variables/index.ts +124 -0
- package/src/variables/props.ts +77 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"elements.js","names":[],"sources":["../../src/export/helpers.ts","../../src/export/paint.ts","../../src/figjam-text.ts","../../src/shapes-with-text.ts","../../src/stickies.ts","../../src/elements.ts"],"sourcesContent":["import type { SceneGraph, SceneNode, Effect, GridTrack } from '@pairdraw/scene-graph'\nimport { colorToHex8 } from '@pairdraw/scene-graph/color'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\n\nexport function formatColor(color: Color, opacity = 1): string {\n return colorToHex8(color, opacity)\n}\n\nexport function formatShadow(e: Effect): string | null {\n if (e.type !== 'DROP_SHADOW' && e.type !== 'INNER_SHADOW') return null\n return `${e.offset.x} ${e.offset.y} ${e.radius} ${formatColor(e.color, e.color.a)}`\n}\n\nexport function getNodeContext(node: SceneNode, graph: SceneGraph) {\n const parent = node.parentId ? graph.getNode(node.parentId) : null\n return {\n isAutoLayout: node.layoutMode !== 'NONE',\n isGrid: node.layoutMode === 'GRID',\n isFlex: node.layoutMode === 'HORIZONTAL' || node.layoutMode === 'VERTICAL',\n parentIsAutoLayout: parent ? parent.layoutMode !== 'NONE' : false,\n parentIsGrid: parent ? parent.layoutMode === 'GRID' : false\n }\n}\n\nexport type PaddingEdges = { pt: number; pr: number; pb: number; pl: number }\n\nexport function collectPadding(node: SceneNode): PaddingEdges | null {\n const { paddingTop: pt, paddingRight: pr, paddingBottom: pb, paddingLeft: pl } = node\n if (pt === 0 && pr === 0 && pb === 0 && pl === 0) return null\n return { pt, pr, pb, pl }\n}\n\nexport function emitPadding<T>(\n edges: PaddingEdges,\n uniform: (v: number) => T,\n symmetric: (y: number, x: number) => T[],\n individual: (edges: PaddingEdges) => T[]\n): T[] {\n const { pt, pr, pb, pl } = edges\n if (pt === pr && pr === pb && pb === pl) return [uniform(pt)]\n if (pt === pb && pl === pr) return symmetric(pt, pl)\n return individual(edges)\n}\n\nexport interface CornerRadii {\n tl: number\n tr: number\n br: number\n bl: number\n}\n\nexport function collectCornerRadii(node: SceneNode): CornerRadii | null {\n if (node.independentCorners) {\n const corners = {\n tl: node.topLeftRadius,\n tr: node.topRightRadius,\n br: node.bottomRightRadius,\n bl: node.bottomLeftRadius\n }\n return Object.values(corners).some((radius) => radius > 0) ? corners : null\n }\n if (node.cornerRadius <= 0) return null\n const r = node.cornerRadius\n return { tl: r, tr: r, br: r, bl: r }\n}\n\nfunction formatTrack(t: GridTrack): string {\n if (t.sizing === 'FR') return `${t.value}fr`\n if (t.sizing === 'FIXED') return `${t.value}px`\n return 'auto'\n}\n\nexport function formatTracks(tracks: GridTrack[]): string {\n return tracks.map(formatTrack).join(' ')\n}\n","import type {\n Effect,\n Fill,\n GradientTransform,\n SceneNode,\n ShadowEffect,\n Stroke\n} from '@pairdraw/scene-graph'\nimport { gradientTransformRows, isIdentityGradientTransform } from '@pairdraw/scene-graph/gradient'\nimport { isShaderPresetPaint, shaderOfPaint } from '@pairdraw/scene-graph/shaders'\n\nimport { STROKE_ALIGN, STROKE_CAP, STROKE_JOIN } from '../enums'\nimport { formatColor, formatShadow } from './helpers'\nimport { helperCall, plainValue, type HelperCall, type JSXProp, type JSXValue } from './value'\n\nconst GRADIENT_HELPERS: Partial<Record<Fill['type'], string>> = {\n GRADIENT_LINEAR: 'linearGradient',\n GRADIENT_RADIAL: 'radialGradient',\n GRADIENT_ANGULAR: 'angularGradient',\n GRADIENT_DIAMOND: 'diamondGradient'\n}\n\nfunction isIdentity(transform: GradientTransform | undefined): boolean {\n return !transform || isIdentityGradientTransform(transform)\n}\n\n/** A paint transform as authors write it, in Figma's rows. */\nfunction rows(transform: GradientTransform | undefined) {\n return transform && gradientTransformRows(transform)\n}\n\n/** Paints and effects imported from Figma often spell out the default blend mode. */\nfunction blendMode(mode: Fill['blendMode']): Fill['blendMode'] {\n return mode === 'NORMAL' || mode === 'PASS_THROUGH' ? undefined : mode\n}\n\ntype Options = Record<string, JSXValue | undefined>\n\n/** Helper options with defaults left out, or `undefined` when none differ. */\nfunction options(entries: Options): Options | undefined {\n return Object.values(entries).some((value) => value !== undefined) ? entries : undefined\n}\n\nfunction fillValue(fill: Fill, node: SceneNode): JSXValue {\n const visible = fill.visible ? undefined : false\n const shader = shaderOfPaint(node, fill)\n if (shader && isShaderPresetPaint(shader)) {\n // A preset with nothing but effects is written as just its effects.\n const { components, ...rest } = shader.preset\n return helperCall(\n 'shader',\n plainValue(Object.keys(rest).length === 0 ? components : shader.preset),\n options({\n opacity: fill.opacity === 1 ? undefined : fill.opacity,\n visible,\n blendMode: blendMode(fill.blendMode)\n })\n )\n }\n // Code the user wrote comes back as the same paint only through its own helper.\n if (shader) {\n const uniforms = shader.uniforms ?? {}\n return helperCall(\n 'shaderSource',\n shader.source,\n options({\n uniforms: Object.keys(uniforms).length === 0 ? undefined : plainValue(uniforms),\n opacity: fill.opacity === 1 ? undefined : fill.opacity,\n visible,\n blendMode: blendMode(fill.blendMode)\n })\n )\n }\n if (fill.type === 'SOLID') {\n const color = formatColor(fill.color, fill.color.a)\n const opacity = fill.opacity === fill.color.a ? undefined : fill.opacity\n return helperCall(\n 'solid',\n color,\n options({ opacity, visible, blendMode: blendMode(fill.blendMode) })\n )\n }\n const helper = GRADIENT_HELPERS[fill.type]\n if (helper && fill.gradientStops) {\n const stops = fill.gradientStops.map((stop) => [\n formatColor(stop.color, stop.color.a),\n stop.position\n ])\n return helperCall(\n helper,\n stops,\n options({\n opacity: fill.opacity === 1 ? undefined : fill.opacity,\n visible,\n blendMode: blendMode(fill.blendMode),\n transform: isIdentity(fill.gradientTransform)\n ? undefined\n : plainValue(rows(fill.gradientTransform))\n })\n )\n }\n // Image, pattern, and other paints have no helper; they render back from their fields.\n return plainValue({\n ...fill,\n gradientTransform: rows(fill.gradientTransform),\n imageTransform: rows(fill.imageTransform)\n })\n}\n\n/** A single visible solid paint fits the `bg` or text `color` shorthand. */\nfunction solidShorthand(fills: Fill[]): string | null {\n if (fills.length !== 1) return null\n const [fill] = fills\n if (fill.type !== 'SOLID' || !fill.visible || blendMode(fill.blendMode)) return null\n // The shorthand has one alpha; a fill whose opacity differs from its colour's needs `solid`.\n if (fill.opacity !== fill.color.a) return null\n return formatColor(fill.color, fill.color.a)\n}\n\n/** One paint as a colour prop takes it: a colour string when it is plain, its helper otherwise. */\nexport function paintPropValue(fill: Fill, node: SceneNode): JSXValue {\n return solidShorthand([fill]) ?? fillValue(fill, node)\n}\n\nexport function collectFillProps(node: SceneNode, props: JSXProp[]): void {\n if (node.fills.length === 0) {\n // A text is painted black unless it says it is not painted.\n if (node.type === 'TEXT') props.push(['fills', []])\n return\n }\n const shorthand = solidShorthand(node.fills)\n if (shorthand) props.push([node.type === 'TEXT' ? 'color' : 'bg', shorthand])\n else props.push(['fills', node.fills.map((fill) => fillValue(fill, node))])\n}\n\ninterface StrokeValue {\n [key: string]: JSXValue | undefined\n color: string\n /** Only when it differs from the colour's alpha, which the colour already carries. */\n opacity?: number\n weight?: number\n align?: string\n dash?: number[]\n cap?: string\n join?: string\n visible?: false\n}\n\nfunction strokeValue(stroke: Stroke): StrokeValue {\n return {\n color: formatColor(stroke.color, stroke.color.a),\n opacity: stroke.opacity === stroke.color.a ? undefined : stroke.opacity,\n weight: stroke.weight === 1 ? undefined : stroke.weight,\n align: stroke.align === 'INSIDE' ? undefined : STROKE_ALIGN.print(stroke.align),\n dash: stroke.dashPattern && stroke.dashPattern.length > 0 ? [...stroke.dashPattern] : undefined,\n cap: stroke.cap && STROKE_CAP.print(stroke.cap),\n join: stroke.join && STROKE_JOIN.print(stroke.join),\n visible: stroke.visible ? undefined : false\n }\n}\n\nconst STROKE_SHORTHAND: Record<string, string> = {\n color: 'stroke',\n weight: 'strokeWidth',\n align: 'strokeAlign',\n dash: 'strokeDash'\n}\n\n/** Node-level cap and join apply to strokes that do not set their own. */\nconst DEFAULT_STROKE_CAP = 'NONE'\nconst DEFAULT_STROKE_JOIN = 'MITER'\n\n/**\n * The shorthand props describe one stroke, and `strokeCap`/`strokeJoin` also set the node's\n * cap and join; they fit only when the stroke agrees with the node on both.\n */\nfunction fitsStrokeShorthand(node: SceneNode, stroke: StrokeValue): boolean {\n if (stroke.visible !== undefined || stroke.opacity !== undefined) return false\n const nodeCap = STROKE_CAP.print(node.strokeCap)\n const nodeJoin = STROKE_JOIN.print(node.strokeJoin)\n return (stroke.cap ?? nodeCap) === nodeCap && (stroke.join ?? nodeJoin) === nodeJoin\n}\n\nexport function collectStrokeProps(node: SceneNode, props: JSXProp[]): void {\n const strokes = node.strokes.map(strokeValue)\n const [only] = strokes\n const shorthand = strokes.length === 1 && fitsStrokeShorthand(node, only)\n if (shorthand) {\n for (const [key, value] of Object.entries(only)) {\n if (value !== undefined && key !== 'cap' && key !== 'join') {\n props.push([STROKE_SHORTHAND[key], value])\n }\n }\n } else if (strokes.length > 0) {\n props.push(['strokes', strokes])\n }\n if (node.strokeCap !== DEFAULT_STROKE_CAP)\n props.push(['strokeCap', STROKE_CAP.print(node.strokeCap)])\n if (node.strokeJoin !== DEFAULT_STROKE_JOIN) {\n props.push(['strokeJoin', STROKE_JOIN.print(node.strokeJoin)])\n }\n if (node.dashPattern.length > 0) props.push(['dashPattern', [...node.dashPattern]])\n if (node.independentStrokeWeights) {\n props.push([\n 'strokeWeights',\n {\n top: node.borderTopWeight,\n right: node.borderRightWeight,\n bottom: node.borderBottomWeight,\n left: node.borderLeftWeight\n }\n ])\n }\n}\n\nconst EFFECT_HELPERS: Record<ShadowEffect['type'], string> = {\n DROP_SHADOW: 'dropShadow',\n INNER_SHADOW: 'innerShadow',\n LAYER_BLUR: 'layerBlur',\n BACKGROUND_BLUR: 'backgroundBlur',\n FOREGROUND_BLUR: 'foregroundBlur'\n}\n\nfunction effectValue(effect: ShadowEffect): HelperCall {\n const visible = effect.visible ? undefined : false\n if (effect.type === 'DROP_SHADOW' || effect.type === 'INNER_SHADOW') {\n return helperCall(\n EFFECT_HELPERS[effect.type],\n options({\n x: effect.offset.x,\n y: effect.offset.y,\n radius: effect.radius,\n spread: effect.spread === 0 ? undefined : effect.spread,\n color: formatColor(effect.color, effect.color.a),\n visible,\n blendMode: blendMode(effect.blendMode),\n showShadowBehindNode: effect.showShadowBehindNode\n })\n )\n }\n return helperCall(\n EFFECT_HELPERS[effect.type],\n visible === undefined ? effect.radius : { radius: effect.radius, visible }\n )\n}\n\nfunction plainDropShadow(effect: Effect): string | null {\n const plain =\n effect.type === 'DROP_SHADOW' &&\n effect.spread === 0 &&\n !blendMode(effect.blendMode) &&\n effect.showShadowBehindNode === undefined\n return plain ? formatShadow(effect) : null\n}\n\n/**\n * `shadow` and `blur` describe a plain drop shadow followed by a layer blur, each optional,\n * in the order the renderer appends them; anything else needs `effects`.\n */\nfunction effectShorthand(effects: ShadowEffect[]): JSXProp[] | null {\n if (effects.some((effect) => !effect.visible)) return null\n const shadow = effects.length > 0 ? plainDropShadow(effects[0]) : null\n const rest = shadow ? effects.slice(1) : effects\n if (rest.length > 1 || rest.some((effect) => effect.type !== 'LAYER_BLUR')) return null\n const props: JSXProp[] = []\n if (shadow) props.push(['shadow', shadow])\n for (const blur of rest) props.push(['blur', blur.radius])\n return props\n}\n\nexport function collectEffectProps(node: SceneNode, props: JSXProp[]): void {\n // A shader effect has no JSX helper yet; leaving it out keeps the source importable.\n const effects = node.effects.filter((effect): effect is ShadowEffect => effect.type !== 'SHADER')\n if (effects.length === 0) return\n props.push(...(effectShorthand(effects) ?? [['effects', effects.map(effectValue)]]))\n}\n","import type { SceneNode } from '@pairdraw/scene-graph'\nimport {\n figJamTextSize,\n figJamTextSizeFields,\n figJamTypeface,\n figJamTypefaceFields,\n type FigJamTextSize,\n type FigJamTypeface\n} from '@pairdraw/scene-graph/figjam'\n\nimport { FIGJAM_TEXT_SIZE, FIGJAM_TYPEFACE } from './enums'\n\n/**\n * The fields a sticky note's body or a shape's label takes from `textSize` and `typeface`, as\n * FigJam's text menus set them; the typeface keeps the size the text ends up at.\n */\nexport function figJamTextFields(\n text: Pick<SceneNode, 'fontSize'>,\n textSize: FigJamTextSize | undefined,\n typeface: FigJamTypeface | undefined\n): Partial<SceneNode> {\n const sized = textSize ? figJamTextSizeFields(textSize, typeface) : {}\n if (!typeface) return sized\n return figJamTypefaceFields(typeface, { fontSize: sized.fontSize ?? text.fontSize })\n}\n\n/** `textSize` and `typeface` as an element writes them, each left out at FigJam's default. */\nexport function figJamTextProps(\n text: Pick<SceneNode, 'fontSize' | 'fontFamily'>\n): Array<[string, string]> {\n const props: Array<[string, string]> = []\n const size = figJamTextSize(text)\n if (size !== 'small') props.push(['textSize', FIGJAM_TEXT_SIZE.print(size)])\n const typeface = figJamTypeface(text)\n if (typeface && typeface !== 'simple') props.push(['typeface', FIGJAM_TYPEFACE.print(typeface)])\n return props\n}\n","import type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'\nimport {\n createShapeWithText,\n SHAPE_WITH_TEXT_CORNER_RADIUS,\n SHAPE_WITH_TEXT_SIZE,\n shapeWithTextLabel\n} from '@pairdraw/scene-graph/generated'\n\nimport { SHAPE_KIND } from './enums'\nimport { collectFillProps, collectStrokeProps } from './export/paint'\nimport type { JSXProp } from './export/value'\nimport { figJamTextFields, figJamTextProps } from './figjam-text'\nimport { readElementProps, shapePropsSchema } from './schema'\nimport { plainTextOf, type TreeNode } from './tree'\n\n/**\n * The shape an element describes, with `layer`'s fields; it is named by its label, as FigJam\n * names a shape, until given a name.\n */\nexport function renderShapeNode(\n graph: SceneGraph,\n tree: TreeNode,\n parentId: string,\n layer: Partial<SceneNode>\n) {\n const props = readElementProps(shapePropsSchema, tree.props)\n const text = plainTextOf(tree)\n const shape = createShapeWithText(\n graph,\n parentId,\n {\n ...layer,\n name: layer.name ?? (text.trim() || 'Shape with text'),\n autoRename: !layer.name,\n shapeWithTextType: props.kind ?? 'SQUARE',\n shapeTruncates: props.truncate ?? false\n },\n { text }\n )\n const label = shapeWithTextLabel(graph, shape)\n if (label) graph.updateNode(label.id, figJamTextFields(label, props.textSize, props.typeface))\n return shape\n}\n\n/**\n * A shape's own props as `<Shape>` writes them, after its name and position: the height it was\n * given rather than the height its label grew it to, so it grows the same way when read back.\n */\nexport function shapeWithTextProps(graph: SceneGraph, node: SceneNode): JSXProp[] {\n const props: JSXProp[] = []\n if (node.shapeWithTextType !== 'SQUARE') {\n props.push(['kind', SHAPE_KIND.print(node.shapeWithTextType)])\n }\n const label = shapeWithTextLabel(graph, node)\n if (label) props.push(...figJamTextProps(label))\n // A truncating shape keeps the height it has; any other grows from the height it was given.\n const height =\n !node.shapeTruncates && node.shapeUserHeight > 0 ? node.shapeUserHeight : node.height\n if (node.width !== SHAPE_WITH_TEXT_SIZE) props.push(['w', node.width])\n if (height !== SHAPE_WITH_TEXT_SIZE) props.push(['h', height])\n if (node.shapeTruncates) props.push(['truncate', true])\n if (node.rotation !== 0) props.push(['rotate', Math.round(node.rotation * 100) / 100])\n collectFillProps(node, props)\n collectStrokeProps(node, props)\n if (node.cornerRadius !== SHAPE_WITH_TEXT_CORNER_RADIUS)\n props.push(['rounded', node.cornerRadius])\n return props\n}\n\n/** The label a shape writes as its children. */\nexport function shapeWithTextLabelText(graph: SceneGraph, node: SceneNode): string {\n return shapeWithTextLabel(graph, node)?.text ?? ''\n}\n","import type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'\nimport { colorToHex } from '@pairdraw/scene-graph/color'\nimport {\n createSticky,\n isWideSticky,\n STICKY_COLORS,\n stickyScale,\n stickySublayers\n} from '@pairdraw/scene-graph/generated'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\n\nimport { figJamTextFields, figJamTextProps } from './figjam-text'\nimport { readElementProps, stickyPropsSchema } from './schema'\nimport { plainTextOf, type TreeNode } from './tree'\n\n/**\n * The note an element describes, with `layer`'s fields; it is named by its body, as FigJam names\n * a note, until given a name.\n */\nexport function renderStickyNode(\n graph: SceneGraph,\n tree: TreeNode,\n parentId: string,\n layer: Partial<SceneNode>\n) {\n const props = readElementProps(stickyPropsSchema, tree.props)\n const text = plainTextOf(tree)\n const author = props.author ?? ''\n const sticky = createSticky(\n graph,\n parentId,\n {\n text,\n author,\n authorVisible: props.authorVisible !== false && author !== '',\n color: props.color,\n wide: props.wide === true,\n scale: props.scale ?? 1\n },\n { ...layer, name: layer.name ?? (text.trim() || 'Sticky'), autoRename: !layer.name }\n )\n const body = stickySublayers(graph, sticky)?.body\n if (body) graph.updateNode(body.id, figJamTextFields(body, props.textSize, props.typeface))\n return sticky\n}\n\n/** The colour as `<Sticky>` writes it: its palette name, or a hex colour off the palette. */\nfunction colorName(color: Color): string {\n const hex = colorToHex(color)\n const named = Object.entries(STICKY_COLORS).find(([, value]) => colorToHex(value) === hex)\n return named ? named[0] : hex\n}\n\n/** A note's own props as `<Sticky>` writes them, after its name and position. */\nexport function stickyProps(graph: SceneGraph, node: SceneNode): Array<[string, unknown]> {\n const layers = stickySublayers(graph, node)\n const color = node.fills.at(0)?.color\n const props: Array<[string, unknown]> = []\n if (color) props.push(['color', colorName(color)])\n if (layers?.author.text) props.push(['author', layers.author.text])\n if (layers?.author.text && !layers.author.visible) props.push(['authorVisible', false])\n if (isWideSticky(graph, node)) props.push(['wide', true])\n if (layers) props.push(...figJamTextProps(layers.body))\n const scale = layers ? stickyScale(layers.author) : 1\n if (scale !== 1) props.push(['scale', scale])\n return props\n}\n\n/** The body a note writes as its children. */\nexport function stickyBody(graph: SceneGraph, node: SceneNode): string {\n return stickySublayers(graph, node)?.body.text ?? ''\n}\n","import { difference } from 'es-toolkit/array'\n\nimport type { NodeType, SceneGraph, SceneNode } from '@pairdraw/scene-graph'\n\nimport { REKA_ELEMENTS, rekaRole } from './behaviours'\nimport { connectorBindingTarget, renderConnectorNode } from './connectors'\nimport {\n DESIGN_JSX_PARAGRAPH_PROPERTY_NAMES,\n DESIGN_JSX_SPAN_PROPERTY_NAMES,\n DESIGN_JSX_SUPPORTED_PROPERTY_NAMES,\n DESIGN_JSX_TEXT_PARAGRAPH_PROPERTY_NAMES\n} from './definitions'\nimport {\n connectorPropsSchema,\n ownLayerPropsSchema,\n placedOwnLayerPropsSchema,\n shapeLayerPropsSchema,\n shapePropsSchema,\n stickyPropsSchema,\n type ElementPropsSchema\n} from './schema'\nimport { renderShapeNode } from './shapes-with-text'\nimport { renderStickyNode } from './stickies'\nimport type { TreeNode } from './tree'\n\n/** How an element that draws a layer of its own, such as a sticky note, renders it. */\nexport interface OwnLayerRenderer {\n /** The layer props it takes, made into fields as any layer's are. */\n layer: ElementPropsSchema\n render(graph: SceneGraph, tree: TreeNode, parentId: string, layer: Partial<SceneNode>): SceneNode\n /** The layer a variable binding of `field` goes on, when not the element's own. */\n bindingTarget?(graph: SceneGraph, node: SceneNode, field: string): string\n}\n\n/**\n * One design JSX element: what JSX names it, what it makes, the props it takes, and which layers\n * export writes as it. The renderer, the export, the prop checks, the streaming preview, and the\n * authoring reference all read this list rather than keeping their own.\n */\nexport type DesignJSXElementDefinition = {\n name: string\n /** The type its tree nodes carry, such as `frame`. */\n runtimeType: string\n description: string\n /** The layer a plain element makes; an element rendered its own way, such as `Icon`, has none. */\n nodeType?: NodeType\n /** The props it takes; every layer prop when left out. */\n props?: readonly string[]\n /** The props it takes and what each holds, for an element that reads them by this schema. */\n schema?: ElementPropsSchema\n /** How it draws its own layer, for an element that does. */\n ownLayer?: OwnLayerRenderer\n /** The layers export writes as this element. */\n writes?: readonly NodeType[]\n}\n\nfunction rekaDescription(namespace: string, part: string): string {\n const role = rekaRole(`${namespace}.${part}`)\n if (role?.role === 'root')\n return `A main component that behaves as Reka UI's ${namespace} ${part}.`\n if (role?.role === 'input') return `The text layer of a ${namespace}'s text property.`\n return `The ${namespace} ${part}, drawn by a slot of its component.`\n}\n\n/** A Reka UI element as the element list describes it. */\nfunction rekaElementDefinitions(): DesignJSXElementDefinition[] {\n return Object.entries(REKA_ELEMENTS).flatMap(([namespace, parts]) =>\n Object.keys(parts).map((part) => {\n const type = `${namespace}.${part}`\n return { name: type, runtimeType: type, description: rekaDescription(namespace, part) }\n })\n )\n}\n\nexport const DESIGN_JSX_ELEMENTS: DesignJSXElementDefinition[] = [\n {\n name: 'Frame',\n runtimeType: 'frame',\n description: 'A frame or auto-layout container.',\n nodeType: 'FRAME',\n // A set and an instance read back as frames: JSX cannot name what they come from.\n writes: ['FRAME', 'COMPONENT_SET', 'INSTANCE']\n },\n {\n name: 'Text',\n runtimeType: 'text',\n description: 'A text layer.',\n nodeType: 'TEXT',\n writes: ['TEXT']\n },\n {\n name: 'Span',\n runtimeType: 'text-span',\n description: 'Characters inside a Text, styled apart from the rest.',\n props: ['key', ...DESIGN_JSX_SPAN_PROPERTY_NAMES]\n },\n {\n name: 'Paragraph',\n runtimeType: 'text-paragraph',\n description: 'One paragraph of a Text, plain or a list item.',\n props: ['key', ...DESIGN_JSX_PARAGRAPH_PROPERTY_NAMES]\n },\n {\n name: 'Rectangle',\n runtimeType: 'rectangle',\n description: 'A rectangle layer.',\n nodeType: 'RECTANGLE',\n writes: ['RECTANGLE', 'ROUNDED_RECTANGLE']\n },\n {\n name: 'Ellipse',\n runtimeType: 'ellipse',\n description: 'An ellipse layer.',\n nodeType: 'ELLIPSE',\n writes: ['ELLIPSE']\n },\n {\n name: 'Line',\n runtimeType: 'line',\n description: 'A line layer.',\n nodeType: 'LINE',\n writes: ['LINE']\n },\n {\n name: 'Star',\n runtimeType: 'star',\n description: 'A star layer.',\n nodeType: 'STAR',\n writes: ['STAR']\n },\n {\n name: 'Polygon',\n runtimeType: 'polygon',\n description: 'A polygon layer.',\n nodeType: 'POLYGON',\n writes: ['POLYGON']\n },\n {\n name: 'Vector',\n runtimeType: 'vector',\n description: 'A vector layer.',\n nodeType: 'VECTOR',\n writes: ['VECTOR']\n },\n {\n name: 'Group',\n runtimeType: 'group',\n description: 'A group of layers.',\n nodeType: 'GROUP',\n writes: ['GROUP']\n },\n {\n name: 'Section',\n runtimeType: 'section',\n description: 'A canvas section.',\n nodeType: 'SECTION',\n writes: ['SECTION']\n },\n {\n name: 'Component',\n runtimeType: 'component',\n description: 'A reusable component.',\n nodeType: 'COMPONENT',\n writes: ['COMPONENT']\n },\n {\n name: 'ComponentSet',\n runtimeType: 'component-set',\n description: 'A component variant set.',\n nodeType: 'COMPONENT_SET'\n },\n { name: 'Instance', runtimeType: 'instance', description: 'An instance of a component.' },\n { name: 'View', runtimeType: 'frame', description: 'An alias for Frame.', nodeType: 'FRAME' },\n {\n name: 'Rect',\n runtimeType: 'rectangle',\n description: 'An alias for Rectangle.',\n nodeType: 'RECTANGLE'\n },\n { name: 'Icon', runtimeType: 'icon', description: 'An Iconify icon.' },\n {\n name: 'Sticky',\n runtimeType: 'sticky',\n description: 'A FigJam sticky note; its text is the body.',\n schema: stickyPropsSchema,\n ownLayer: { layer: placedOwnLayerPropsSchema, render: renderStickyNode },\n writes: ['STICKY']\n },\n {\n name: 'Shape',\n runtimeType: 'shape',\n description: 'A FigJam shape with text; its text is the label.',\n schema: shapePropsSchema,\n ownLayer: { layer: shapeLayerPropsSchema, render: renderShapeNode },\n writes: ['SHAPE_WITH_TEXT']\n },\n {\n name: 'Connector',\n runtimeType: 'connector',\n description:\n 'A FigJam connector between two layers of the same JSX, named by `from` and `to`, or points.',\n schema: connectorPropsSchema,\n ownLayer: {\n layer: ownLayerPropsSchema,\n render: renderConnectorNode,\n bindingTarget: connectorBindingTarget\n },\n writes: ['CONNECTOR']\n },\n ...rekaElementDefinitions()\n]\n\n/** Props an inline `<svg>` takes besides a layer's: its markup's view box and body. */\nconst SVG_PROPERTY_NAMES = ['viewBox', 'body'] as const\n\n/**\n * Lowercase tags JSX also accepts, as HTML names them, with the layer each makes; they are\n * not written back.\n */\nconst INTRINSIC_ELEMENTS: Readonly<Record<string, NodeType | null>> = {\n componentset: 'COMPONENT_SET',\n div: 'FRAME',\n main: 'FRAME',\n header: 'FRAME',\n footer: 'FRAME',\n nav: 'FRAME',\n article: 'FRAME',\n aside: 'FRAME',\n span: 'TEXT',\n p: 'TEXT',\n h1: 'TEXT',\n h2: 'TEXT',\n h3: 'TEXT',\n h4: 'TEXT',\n h5: 'TEXT',\n h6: 'TEXT',\n // Inline SVG markup, which the artwork service draws.\n svg: null\n}\n\n/** Paragraph props describe a paragraph of a text, never a layer, unless a text sets them too. */\nconst LAYER_PROPS: ReadonlySet<string> = new Set<string>(\n difference(\n DESIGN_JSX_SUPPORTED_PROPERTY_NAMES,\n difference(DESIGN_JSX_PARAGRAPH_PROPERTY_NAMES, DESIGN_JSX_TEXT_PARAGRAPH_PROPERTY_NAMES)\n )\n)\n\nconst BY_RUNTIME_TYPE = new Map(\n DESIGN_JSX_ELEMENTS.map((element): [string, DesignJSXElementDefinition] => [\n element.runtimeType,\n element\n ]).reverse()\n)\n\nconst PROPS_BY_RUNTIME_TYPE = new Map<string, ReadonlySet<string>>([\n ['svg', new Set([...LAYER_PROPS, ...SVG_PROPERTY_NAMES])],\n ...DESIGN_JSX_ELEMENTS.flatMap((element): [string, ReadonlySet<string>][] => {\n const props = element.schema ? Object.keys(element.schema.entries) : element.props\n return props ? [[element.runtimeType, new Set(props)]] : []\n })\n])\n\nconst TAG_BY_NODE_TYPE = new Map(\n DESIGN_JSX_ELEMENTS.flatMap((element) =>\n (element.writes ?? []).map((type): [NodeType, string] => [type, element.name])\n )\n)\n\n/** The layer an element of `runtimeType` makes, for an element without its own renderer. */\nexport function elementNodeType(runtimeType: string): NodeType | undefined {\n return BY_RUNTIME_TYPE.get(runtimeType)?.nodeType ?? INTRINSIC_ELEMENTS[runtimeType] ?? undefined\n}\n\n/** The props an element of `runtimeType` takes. */\nexport function elementProps(runtimeType: string): ReadonlySet<string> {\n return PROPS_BY_RUNTIME_TYPE.get(runtimeType) ?? LAYER_PROPS\n}\n\nconst BY_NAME = new Map(\n DESIGN_JSX_ELEMENTS.map((element): [string, DesignJSXElementDefinition] => [\n element.name,\n element\n ])\n)\n\n/**\n * The props an element written `<name>` takes, as the renderer checks them, for an editor that\n * checks them as they are typed; null for a name that is no element, and for an instance, which\n * also takes its component's properties by name.\n */\nexport function elementPropsByName(name: string): ReadonlySet<string> | null {\n const element = BY_NAME.get(name)\n if (!element) return Object.hasOwn(INTRINSIC_ELEMENTS, name) ? elementProps(name) : null\n return element.runtimeType === 'instance' ? null : elementProps(element.runtimeType)\n}\n\n/** The schema an element of `runtimeType` reads its props by, if it has one. */\nexport function elementSchema(runtimeType: string): ElementPropsSchema | undefined {\n return BY_RUNTIME_TYPE.get(runtimeType)?.schema\n}\n\n/** How an element of `runtimeType` draws its own layer, if it does. */\nexport function elementOwnLayer(runtimeType: string): OwnLayerRenderer | undefined {\n return BY_RUNTIME_TYPE.get(runtimeType)?.ownLayer\n}\n\n/** The element export writes a layer of `type` as, if any. */\nexport function elementTag(type: NodeType): string | undefined {\n return TAG_BY_NODE_TYPE.get(type)\n}\n\n/**\n * `const Frame = 'frame', …`: the element names a JSX string's code can use, bound to their\n * runtime types. Reka UI elements, named `Switch.Root`, are bound by their namespaces.\n */\nexport function elementBindings(): string {\n return DESIGN_JSX_ELEMENTS.filter((element) => !element.name.includes('.'))\n .map((element) => `const ${element.name} = '${element.runtimeType}'`)\n .join('\\n')\n}\n"],"mappings":";;;;;;;;;;;AAIA,SAAgB,YAAY,OAAc,UAAU,GAAW;CAC7D,OAAO,YAAY,OAAO,OAAO;AACnC;AAEA,SAAgB,aAAa,GAA0B;CACrD,IAAI,EAAE,SAAS,iBAAiB,EAAE,SAAS,gBAAgB,OAAO;CAClE,OAAO,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,OAAO,GAAG,YAAY,EAAE,OAAO,EAAE,MAAM,CAAC;AAClF;AAEA,SAAgB,eAAe,MAAiB,OAAmB;CACjE,MAAM,SAAS,KAAK,WAAW,MAAM,QA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AM,QAAQ,IAAI,CAAC,CAC/E,CACF;;AAGA,SAAgB,gBAAgB,aAA2C;CACzE,OAAO,gBAAgB,IAAI,WAAW,CAAC,EAAE,YAAY,mBAAmB,gBAAgB,KAAA;AAC1F;;AAGA,SAAgB,aAAa,aAA0C;CACrE,OAAO,sBAAsB,IAAI,WAAW,KAAK;AACnD;AAEA,MAAM,UAAU,IAAI,IAClB,oBAAoB,KAAK,YAAkD,CACzE,QAAQ,MACR,OACF,CAAC,CACH;;;;;;AAOA,SAAgB,mBAAmB,MAA0C;CAC3E,MAAM,UAAU,QAAQ,IAAI,IAAI;CAChC,IAAI,CAAC,SAAS,OAAO,OAAO,OAAO,oBAAoB,IAAI,IAAI,aAAa,IAAI,IAAI;CACpF,OAAO,QAAQ,gBAAgB,aAAa,OAAO,aAAa,QAAQ,WAAW;AACrF;;AAGA,SAAgB,cAAc,aAAqD;CACjF,OAAO,gBAAgB,IAAI,WAAW,CAAC,EAAE;AAC3C;;AAGA,SAAgB,gBAAgB,aAAmD;CACjF,OAAO,gBAAgB,IAAI,WAAW,CAAC,EAAE;AAC3C;;AAGA,SAAgB,WAAW,MAAoC;CAC7D,OAAO,iBAAiB,IAAI,IAAI;AAClC;;;;;AAMA,SAAgB,kBAA0B;CACxC,OAAO,oBAAoB,QAAQ,YAAY,CAAC,QAAQ,KAAK,SAAS,GAAG,CAAC,CAAC,CACxE,KAAK,YAAY,SAAS,QAAQ,KAAK,MAAM,QAAQ,YAAY,EAAE,CAAC,CACpE,KAAK,IAAI;AACd"}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { REKA_ELEMENTS, rekaRole } from "../behaviours/elements.js";
|
|
2
|
+
import { behaviourToSpec, readBehaviour, textBinding } from "@pairdraw/scene-graph/behaviours";
|
|
3
|
+
import { slotPropertyId } from "@pairdraw/scene-graph/slots";
|
|
4
|
+
import { instanceMainComponent } from "@pairdraw/scene-graph/instances";
|
|
5
|
+
//#region src/export/behaviours.ts
|
|
6
|
+
/** The Reka namespace and element a kind's component is written as. */
|
|
7
|
+
const ROOTS = {
|
|
8
|
+
button: ["Button", "Root"],
|
|
9
|
+
toggle: ["Toggle", "Root"],
|
|
10
|
+
switch: ["Switch", "Root"],
|
|
11
|
+
checkbox: ["Checkbox", "Root"],
|
|
12
|
+
radio: ["RadioGroup", "Item"],
|
|
13
|
+
radioGroup: ["RadioGroup", "Root"],
|
|
14
|
+
toggleGroup: ["ToggleGroup", "Root"],
|
|
15
|
+
slider: ["Slider", "Root"],
|
|
16
|
+
progress: ["Progress", "Root"],
|
|
17
|
+
tabs: ["Tabs", "Root"],
|
|
18
|
+
collapsible: ["Collapsible", "Root"],
|
|
19
|
+
accordion: ["Accordion", "Root"],
|
|
20
|
+
numberField: ["NumberField", "Root"],
|
|
21
|
+
textField: ["TextField", "Root"],
|
|
22
|
+
textarea: ["Textarea", "Root"]
|
|
23
|
+
};
|
|
24
|
+
/** The element a part is written as in a namespace, such as `Thumb` for a switch's thumb. */
|
|
25
|
+
function elementFor(namespace, match) {
|
|
26
|
+
const parts = REKA_ELEMENTS[namespace] ?? {};
|
|
27
|
+
const found = Object.keys(parts).find((element) => match(rekaRole(`${namespace}.${element}`)));
|
|
28
|
+
return found ? `${namespace}.${found}` : void 0;
|
|
29
|
+
}
|
|
30
|
+
function rootProps(graph, owner) {
|
|
31
|
+
const behaviour = readBehaviour(owner);
|
|
32
|
+
if (!behaviour) return [];
|
|
33
|
+
const spec = behaviourToSpec(graph, owner, behaviour);
|
|
34
|
+
const props = [];
|
|
35
|
+
const valueProp = (value) => typeof value === "string" ? value : {
|
|
36
|
+
property: value.property,
|
|
37
|
+
on: value.on,
|
|
38
|
+
off: value.off
|
|
39
|
+
};
|
|
40
|
+
for (const [valueId, value] of Object.entries(spec.values ?? {})) {
|
|
41
|
+
if (Object.hasOwn(behaviour.texts, valueId)) continue;
|
|
42
|
+
const name = valueId === "value" ? "modelValue" : valueId;
|
|
43
|
+
props.push([name, valueProp(value)]);
|
|
44
|
+
}
|
|
45
|
+
const range = spec.numbers?.value;
|
|
46
|
+
if (range) {
|
|
47
|
+
for (const key of [
|
|
48
|
+
"min",
|
|
49
|
+
"max",
|
|
50
|
+
"step"
|
|
51
|
+
]) {
|
|
52
|
+
const value = range[key];
|
|
53
|
+
if (value !== void 0) props.push([key, value]);
|
|
54
|
+
}
|
|
55
|
+
if (range.default !== void 0) props.push(["defaultValue", range.default]);
|
|
56
|
+
}
|
|
57
|
+
if (spec.states) props.push(["states", typeof spec.states === "string" ? spec.states : spec.states.property]);
|
|
58
|
+
return props;
|
|
59
|
+
}
|
|
60
|
+
/** A part's slot frame as its element, and its children as the repeated parts or items. */
|
|
61
|
+
function exportPart(graph, namespace, layer, partId, result) {
|
|
62
|
+
const tag = elementFor(namespace, (role) => role?.role === "part" && role.part === partId);
|
|
63
|
+
const repeated = elementFor(namespace, (role) => role?.role === "repeat" && role.container === partId);
|
|
64
|
+
if (tag) result.tags.set(layer.id, tag);
|
|
65
|
+
else result.flatten.add(layer.id);
|
|
66
|
+
for (const child of graph.getChildren(layer.id)) {
|
|
67
|
+
if (repeated) result.tags.set(child.id, repeated);
|
|
68
|
+
const item = child.type === "INSTANCE" ? instanceMainComponent(graph, child) : void 0;
|
|
69
|
+
if (partId !== "items" || !item) continue;
|
|
70
|
+
const set = item.parentId ? graph.getNode(item.parentId) : void 0;
|
|
71
|
+
result.tags.set(child.id, `${namespace}.Item`);
|
|
72
|
+
result.props.set(child.id, [["of", (set?.type === "COMPONENT_SET" ? set : item).id]]);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/** Every layer below a node, depth first. */
|
|
76
|
+
function descendants(graph, node) {
|
|
77
|
+
return graph.getChildren(node.id).flatMap((child) => [child, ...descendants(graph, child)]);
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* How a main component or component set with a behaviour is written: `Switch.Root` and its
|
|
81
|
+
* `Switch.Thumb`, `TextField.Input`, tab triggers and panels, and a group's items as
|
|
82
|
+
* `RadioGroup.Item of="…"`. Null for other layers.
|
|
83
|
+
*/
|
|
84
|
+
function rekaExport(graph, owner) {
|
|
85
|
+
const behaviour = readBehaviour(owner);
|
|
86
|
+
if (!behaviour || owner.type !== "COMPONENT" && owner.type !== "COMPONENT_SET") return null;
|
|
87
|
+
const [namespace, element] = ROOTS[behaviour.kind];
|
|
88
|
+
const result = {
|
|
89
|
+
tags: /* @__PURE__ */ new Map([[owner.id, `${namespace}.${element}`]]),
|
|
90
|
+
props: /* @__PURE__ */ new Map([[owner.id, rootProps(graph, owner)]]),
|
|
91
|
+
flatten: /* @__PURE__ */ new Set()
|
|
92
|
+
};
|
|
93
|
+
const textIds = new Map(Object.keys(behaviour.texts).map((valueId) => [textBinding(behaviour, valueId), valueId]));
|
|
94
|
+
for (const layer of descendants(graph, owner)) {
|
|
95
|
+
if (layer.type === "INSTANCE") continue;
|
|
96
|
+
const partId = Object.entries(behaviour.parts).find(([, id]) => id === slotPropertyId(layer))?.[0];
|
|
97
|
+
if (partId) {
|
|
98
|
+
exportPart(graph, namespace, layer, partId, result);
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
const reference = layer.componentPropertyReferences.find((item) => item.field === "TEXT");
|
|
102
|
+
const valueId = reference && textIds.get(reference.propertyId);
|
|
103
|
+
if (layer.type === "TEXT" && valueId) {
|
|
104
|
+
const tag = elementFor(namespace, (role) => role?.role === "input" && role.valueId === valueId);
|
|
105
|
+
if (tag) result.tags.set(layer.id, tag);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return result;
|
|
109
|
+
}
|
|
110
|
+
//#endregion
|
|
111
|
+
export { rekaExport };
|
|
112
|
+
|
|
113
|
+
//# sourceMappingURL=behaviours.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"behaviours.js","names":[],"sources":["../../../src/export/behaviours.ts"],"sourcesContent":["import type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'\nimport {\n behaviourToSpec,\n readBehaviour,\n textBinding,\n type BehaviourKind\n} from '@pairdraw/scene-graph/behaviours'\nimport { instanceMainComponent } from '@pairdraw/scene-graph/instances'\nimport { slotPropertyId } from '@pairdraw/scene-graph/slots'\n\nimport { REKA_ELEMENTS, rekaRole } from '../behaviours'\nimport type { JSXProp, JSXValue } from './value'\n\n/** The Reka namespace and element a kind's component is written as. */\nconst ROOTS: Record<BehaviourKind, [namespace: string, element: string]> = {\n button: ['Button', 'Root'],\n toggle: ['Toggle', 'Root'],\n switch: ['Switch', 'Root'],\n checkbox: ['Checkbox', 'Root'],\n radio: ['RadioGroup', 'Item'],\n radioGroup: ['RadioGroup', 'Root'],\n toggleGroup: ['ToggleGroup', 'Root'],\n slider: ['Slider', 'Root'],\n progress: ['Progress', 'Root'],\n tabs: ['Tabs', 'Root'],\n collapsible: ['Collapsible', 'Root'],\n accordion: ['Accordion', 'Root'],\n numberField: ['NumberField', 'Root'],\n textField: ['TextField', 'Root'],\n textarea: ['Textarea', 'Root']\n}\n\n/** How the layers of a component with a behaviour are written as Reka elements. */\nexport interface RekaExport {\n /** Element names by layer id: the root, its parts, its input, and repeated parts. */\n tags: Map<string, string>\n /** Props a layer adds: the root's behaviour, an item's component. */\n props: Map<string, JSXProp[]>\n /** Containers JSX leaves implicit, written as their children alone. */\n flatten: Set<string>\n}\n\n/** The element a part is written as in a namespace, such as `Thumb` for a switch's thumb. */\nfunction elementFor(namespace: string, match: (role: ReturnType<typeof rekaRole>) => boolean) {\n const parts = REKA_ELEMENTS[namespace] ?? {}\n const found = Object.keys(parts).find((element) => match(rekaRole(`${namespace}.${element}`)))\n return found ? `${namespace}.${found}` : undefined\n}\n\nfunction rootProps(graph: SceneGraph, owner: SceneNode): JSXProp[] {\n const behaviour = readBehaviour(owner)\n if (!behaviour) return []\n const spec = behaviourToSpec(graph, owner, behaviour)\n const props: JSXProp[] = []\n const valueProp = (value: NonNullable<typeof spec.values>[string]): JSXValue =>\n typeof value === 'string' ? value : { property: value.property, on: value.on, off: value.off }\n for (const [valueId, value] of Object.entries(spec.values ?? {})) {\n if (Object.hasOwn(behaviour.texts, valueId)) continue\n const name = valueId === 'value' ? 'modelValue' : valueId\n props.push([name, valueProp(value)])\n }\n const range = spec.numbers?.value\n if (range) {\n for (const key of ['min', 'max', 'step'] as const) {\n const value = range[key]\n if (value !== undefined) props.push([key, value])\n }\n if (range.default !== undefined) props.push(['defaultValue', range.default])\n }\n if (spec.states)\n props.push(['states', typeof spec.states === 'string' ? spec.states : spec.states.property])\n return props\n}\n\n/** A part's slot frame as its element, and its children as the repeated parts or items. */\nfunction exportPart(\n graph: SceneGraph,\n namespace: string,\n layer: SceneNode,\n partId: string,\n result: RekaExport\n): void {\n const tag = elementFor(namespace, (role) => role?.role === 'part' && role.part === partId)\n const repeated = elementFor(\n namespace,\n (role) => role?.role === 'repeat' && role.container === partId\n )\n if (tag) result.tags.set(layer.id, tag)\n else result.flatten.add(layer.id)\n for (const child of graph.getChildren(layer.id)) {\n if (repeated) result.tags.set(child.id, repeated)\n const item = child.type === 'INSTANCE' ? instanceMainComponent(graph, child) : undefined\n if (partId !== 'items' || !item) continue\n // A group's items are written as the group's Item, naming their component.\n const set = item.parentId ? graph.getNode(item.parentId) : undefined\n result.tags.set(child.id, `${namespace}.Item`)\n result.props.set(child.id, [['of', (set?.type === 'COMPONENT_SET' ? set : item).id]])\n }\n}\n\n/** Every layer below a node, depth first. */\nfunction descendants(graph: SceneGraph, node: SceneNode): SceneNode[] {\n return graph.getChildren(node.id).flatMap((child) => [child, ...descendants(graph, child)])\n}\n\n/**\n * How a main component or component set with a behaviour is written: `Switch.Root` and its\n * `Switch.Thumb`, `TextField.Input`, tab triggers and panels, and a group's items as\n * `RadioGroup.Item of=\"…\"`. Null for other layers.\n */\nexport function rekaExport(graph: SceneGraph, owner: SceneNode): RekaExport | null {\n const behaviour = readBehaviour(owner)\n if (!behaviour || (owner.type !== 'COMPONENT' && owner.type !== 'COMPONENT_SET')) return null\n const [namespace, element] = ROOTS[behaviour.kind]\n const result: RekaExport = {\n tags: new Map([[owner.id, `${namespace}.${element}`]]),\n props: new Map([[owner.id, rootProps(graph, owner)]]),\n flatten: new Set()\n }\n const textIds = new Map(\n Object.keys(behaviour.texts).map((valueId) => [textBinding(behaviour, valueId), valueId])\n )\n for (const layer of descendants(graph, owner)) {\n if (layer.type === 'INSTANCE') continue\n const partId = Object.entries(behaviour.parts).find(\n ([, id]) => id === slotPropertyId(layer)\n )?.[0]\n if (partId) {\n exportPart(graph, namespace, layer, partId, result)\n continue\n }\n const reference = layer.componentPropertyReferences.find((item) => item.field === 'TEXT')\n const valueId = reference && textIds.get(reference.propertyId)\n if (layer.type === 'TEXT' && valueId) {\n const tag = elementFor(\n namespace,\n (role) => role?.role === 'input' && role.valueId === valueId\n )\n if (tag) result.tags.set(layer.id, tag)\n }\n }\n return result\n}\n"],"mappings":";;;;;;AAcA,MAAM,QAAqE;CACzE,QAAQ,CAAC,UAAU,MAAM;CACzB,QAAQ,CAAC,UAAU,MAAM;CACzB,QAAQ,CAAC,UAAU,MAAM;CACzB,UAAU,CAAC,YAAY,MAAM;CAC7B,OAAO,CAAC,cAAc,MAAM;CAC5B,YAAY,CAAC,cAAc,MAAM;CACjC,aAAa,CAAC,eAAe,MAAM;CACnC,QAAQ,CAAC,UAAU,MAAM;CACzB,UAAU,CAAC,YAAY,MAAM;CAC7B,MAAM,CAAC,QAAQ,MAAM;CACrB,aAAa,CAAC,eAAe,MAAM;CACnC,WAAW,CAAC,aAAa,MAAM;CAC/B,aAAa,CAAC,eAAe,MAAM;CACnC,WAAW,CAAC,aAAa,MAAM;CAC/B,UAAU,CAAC,YAAY,MAAM;AAC/B;;AAaA,SAAS,WAAW,WAAmB,OAAuD;CAC5F,MAAM,QAAQ,cAAc,cAAc,CAAC;CAC3C,MAAM,QAAQ,OAAO,KAAK,KAAK,CAAC,CAAC,MAAM,YAAY,MAAM,SAAS,GAAG,UAAU,GAAG,SAAS,CAAC,CAAC;CAC7F,OAAO,QAAQ,GAAG,UAA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,QAAQ,UAAU,KAAK,CAAC,CAAC,MAC5C,GAAG,QAAQ,OAAO,eAAe,KAAK,CACzC,CAAC,GAAG;EACJ,IAAI,QAAQ;GACV,WAAW,OAAO,WAAW,OAAO,QAAQ,MAAM;GAClD;EACF;EACA,MAAM,YAAY,MAAM,4BAA4B,MAAM,SAAS,KAAK,UAAU,MAAM;EACxF,MAAM,UAAU,aAAa,QAAQ,IAAI,UAAU,UAAU;EAC7D,IAAI,MAAM,SAAS,UAAU,SAAS;GACpC,MAAM,MAAM,WACV,YACC,SAAS,MAAM,SAAS,WAAW,KAAK,YAAY,OACvD;GACA,IAAI,KAAK,OAAO,KAAK,IAAI,MAAM,IAAI,GAAG;EACxC;CACF;CACA,OAAO;AACT"}
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
import { isEqual } from "es-toolkit";
|
|
2
|
+
//#region src/variables/props.ts
|
|
3
|
+
const PADDING_FIELDS = [
|
|
4
|
+
"paddingTop",
|
|
5
|
+
"paddingRight",
|
|
6
|
+
"paddingBottom",
|
|
7
|
+
"paddingLeft"
|
|
8
|
+
];
|
|
9
|
+
/**
|
|
10
|
+
* The number props a FLOAT variable binds, in the order rendering reads them: shorthands before
|
|
11
|
+
* their longhands, as `propsToOverrides` gives them precedence, so a literal longhand also
|
|
12
|
+
* overrides a bound shorthand on that edge.
|
|
13
|
+
*/
|
|
14
|
+
function scalarProps({ text, grid, wrap }) {
|
|
15
|
+
const props = [
|
|
16
|
+
{
|
|
17
|
+
prop: "w",
|
|
18
|
+
fields: ["width"]
|
|
19
|
+
},
|
|
20
|
+
{
|
|
21
|
+
prop: "h",
|
|
22
|
+
fields: ["height"]
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
prop: "p",
|
|
26
|
+
fields: PADDING_FIELDS
|
|
27
|
+
},
|
|
28
|
+
{
|
|
29
|
+
prop: "px",
|
|
30
|
+
fields: ["paddingLeft", "paddingRight"]
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
prop: "py",
|
|
34
|
+
fields: ["paddingTop", "paddingBottom"]
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
prop: "pt",
|
|
38
|
+
fields: ["paddingTop"]
|
|
39
|
+
},
|
|
40
|
+
{
|
|
41
|
+
prop: "pr",
|
|
42
|
+
fields: ["paddingRight"]
|
|
43
|
+
},
|
|
44
|
+
{
|
|
45
|
+
prop: "pb",
|
|
46
|
+
fields: ["paddingBottom"]
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
prop: "pl",
|
|
50
|
+
fields: ["paddingLeft"]
|
|
51
|
+
},
|
|
52
|
+
{
|
|
53
|
+
prop: "rounded",
|
|
54
|
+
fields: ["cornerRadius"]
|
|
55
|
+
},
|
|
56
|
+
{
|
|
57
|
+
prop: "roundedTL",
|
|
58
|
+
fields: ["topLeftRadius"]
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
prop: "roundedTR",
|
|
62
|
+
fields: ["topRightRadius"]
|
|
63
|
+
},
|
|
64
|
+
{
|
|
65
|
+
prop: "roundedBL",
|
|
66
|
+
fields: ["bottomLeftRadius"]
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
prop: "roundedBR",
|
|
70
|
+
fields: ["bottomRightRadius"]
|
|
71
|
+
},
|
|
72
|
+
{
|
|
73
|
+
prop: "strokeWidth",
|
|
74
|
+
fields: ["strokeWeight"]
|
|
75
|
+
},
|
|
76
|
+
{
|
|
77
|
+
prop: "opacity",
|
|
78
|
+
fields: ["opacity"]
|
|
79
|
+
}
|
|
80
|
+
];
|
|
81
|
+
if (grid) props.push({
|
|
82
|
+
prop: "columnGap",
|
|
83
|
+
fields: ["gridColumnGap"]
|
|
84
|
+
}, {
|
|
85
|
+
prop: "rowGap",
|
|
86
|
+
fields: ["gridRowGap"]
|
|
87
|
+
}, {
|
|
88
|
+
prop: "gap",
|
|
89
|
+
fields: ["gridColumnGap", "gridRowGap"]
|
|
90
|
+
});
|
|
91
|
+
else {
|
|
92
|
+
props.push({
|
|
93
|
+
prop: "gap",
|
|
94
|
+
fields: ["itemSpacing"]
|
|
95
|
+
});
|
|
96
|
+
if (wrap) props.push({
|
|
97
|
+
prop: "rowGap",
|
|
98
|
+
fields: ["counterAxisSpacing"]
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
if (text) props.push({
|
|
102
|
+
prop: "fontSize",
|
|
103
|
+
fields: ["fontSize"]
|
|
104
|
+
}, {
|
|
105
|
+
prop: "size",
|
|
106
|
+
fields: ["fontSize"]
|
|
107
|
+
}, {
|
|
108
|
+
prop: "lineHeight",
|
|
109
|
+
fields: ["lineHeight"]
|
|
110
|
+
}, {
|
|
111
|
+
prop: "letterSpacing",
|
|
112
|
+
fields: ["letterSpacing"]
|
|
113
|
+
});
|
|
114
|
+
return props;
|
|
115
|
+
}
|
|
116
|
+
/** The paint props a COLOR variable binds: the first fill's colour, or the first stroke's. */
|
|
117
|
+
function paintProps({ text }) {
|
|
118
|
+
const fill = ["fills/0/color"];
|
|
119
|
+
const stroke = ["strokes/0/color"];
|
|
120
|
+
return [
|
|
121
|
+
{
|
|
122
|
+
prop: "bg",
|
|
123
|
+
fields: fill
|
|
124
|
+
},
|
|
125
|
+
{
|
|
126
|
+
prop: "fill",
|
|
127
|
+
fields: fill
|
|
128
|
+
},
|
|
129
|
+
{
|
|
130
|
+
prop: "background",
|
|
131
|
+
fields: fill
|
|
132
|
+
},
|
|
133
|
+
{
|
|
134
|
+
prop: "backgroundColor",
|
|
135
|
+
fields: fill
|
|
136
|
+
},
|
|
137
|
+
...text ? [{
|
|
138
|
+
prop: "color",
|
|
139
|
+
fields: fill
|
|
140
|
+
}] : [],
|
|
141
|
+
{
|
|
142
|
+
prop: "stroke",
|
|
143
|
+
fields: stroke
|
|
144
|
+
},
|
|
145
|
+
{
|
|
146
|
+
prop: "border",
|
|
147
|
+
fields: stroke
|
|
148
|
+
},
|
|
149
|
+
{
|
|
150
|
+
prop: "borderColor",
|
|
151
|
+
fields: stroke
|
|
152
|
+
}
|
|
153
|
+
];
|
|
154
|
+
}
|
|
155
|
+
//#endregion
|
|
156
|
+
//#region src/export/bindings.ts
|
|
157
|
+
/** Sizes are not added when the export left them out, as a fixed size would replace Hug or Fill. */
|
|
158
|
+
const NOT_ADDED = /* @__PURE__ */ new Set(["width", "height"]);
|
|
159
|
+
/** The corner props, which make the corners independent wherever one of them is written. */
|
|
160
|
+
const CORNER_PROPS = [
|
|
161
|
+
"roundedTL",
|
|
162
|
+
"roundedTR",
|
|
163
|
+
"roundedBR",
|
|
164
|
+
"roundedBL"
|
|
165
|
+
];
|
|
166
|
+
function bindingContext(node) {
|
|
167
|
+
return {
|
|
168
|
+
text: node.type === "TEXT",
|
|
169
|
+
grid: node.layoutMode === "GRID",
|
|
170
|
+
wrap: node.layoutWrap === "WRAP"
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* The prop `field` is written through on `node`: one the export printed that sets that field
|
|
175
|
+
* alone, or else the last number prop that does, as rendering reads it, or none, when only
|
|
176
|
+
* `bind` can set it. A paint prop is printed only for a single solid paint, which a colour
|
|
177
|
+
* variable can stand for; a number prop printed as a word, such as `w="fill"`, keeps it.
|
|
178
|
+
*/
|
|
179
|
+
function fieldProp(node, field, props) {
|
|
180
|
+
const context = bindingContext(node);
|
|
181
|
+
const sets = ({ fields }) => fields.length === 1 && fields[0] === field;
|
|
182
|
+
const scalar = scalarProps(context).filter(sets);
|
|
183
|
+
const printedAs = (prop, numeric) => props.some(([name, value]) => name === prop && (!numeric || typeof value === "number"));
|
|
184
|
+
const printed = scalar.find(({ prop }) => printedAs(prop, true)) ?? paintProps(context).filter(sets).find(({ prop }) => printedAs(prop, false));
|
|
185
|
+
if (printed) return {
|
|
186
|
+
prop: printed.prop,
|
|
187
|
+
add: false
|
|
188
|
+
};
|
|
189
|
+
const last = scalar.at(-1);
|
|
190
|
+
return last && !NOT_ADDED.has(field) ? {
|
|
191
|
+
prop: last.prop,
|
|
192
|
+
add: true
|
|
193
|
+
} : void 0;
|
|
194
|
+
}
|
|
195
|
+
function setProp(props, name, value, add) {
|
|
196
|
+
const index = props.findIndex(([prop]) => prop === name);
|
|
197
|
+
if (index !== -1) props[index] = [name, value];
|
|
198
|
+
else if (add) props.push([name, value]);
|
|
199
|
+
return index !== -1 || add;
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Write the padding again when a side is bound, each bound side as its variable, grouped as
|
|
203
|
+
* `p`, `py` and `px`, or one prop per side, as the export groups literal padding.
|
|
204
|
+
*/
|
|
205
|
+
function writePadding(node, props, remaining, variables, named) {
|
|
206
|
+
const sides = PADDING_FIELDS.map((field) => {
|
|
207
|
+
const variableId = remaining.get(field);
|
|
208
|
+
return variableId && named(variableId) ? variables.variable(variableId) : node[field];
|
|
209
|
+
});
|
|
210
|
+
if (sides.every((side) => typeof side === "number")) return;
|
|
211
|
+
const paddingProps = new Set(scalarProps(bindingContext(node)).filter(({ fields }) => fields.every((field) => PADDING_FIELDS.includes(field))).map(({ prop }) => prop));
|
|
212
|
+
for (let index = props.length - 1; index >= 0; index--) if (paddingProps.has(props[index][0])) props.splice(index, 1);
|
|
213
|
+
const [top, right, bottom, left] = sides;
|
|
214
|
+
if ([
|
|
215
|
+
right,
|
|
216
|
+
bottom,
|
|
217
|
+
left
|
|
218
|
+
].every((side) => isEqual(side, top))) props.push(["p", top]);
|
|
219
|
+
else if (isEqual(top, bottom) && isEqual(left, right)) props.push(["py", top], ["px", left]);
|
|
220
|
+
else [
|
|
221
|
+
"pt",
|
|
222
|
+
"pr",
|
|
223
|
+
"pb",
|
|
224
|
+
"pl"
|
|
225
|
+
].forEach((prop, index) => {
|
|
226
|
+
if (sides[index] !== 0) props.push([prop, sides[index]]);
|
|
227
|
+
});
|
|
228
|
+
for (const field of PADDING_FIELDS) {
|
|
229
|
+
const variableId = remaining.get(field);
|
|
230
|
+
if (variableId && named(variableId)) remaining.delete(field);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Write corners printed together as `rounded` one by one when a corner is bound, since the
|
|
235
|
+
* bound corner's own prop makes the corners independent and the others would then be 0.
|
|
236
|
+
*/
|
|
237
|
+
function expandCorners(node, props, remaining, named) {
|
|
238
|
+
const corners = new Set(scalarProps(bindingContext(node)).filter(({ prop }) => CORNER_PROPS.includes(prop)).flatMap(({ fields }) => fields));
|
|
239
|
+
const bound = [...remaining].some(([field, id]) => corners.has(field) && named(id));
|
|
240
|
+
const index = props.findIndex(([prop]) => prop === "rounded");
|
|
241
|
+
if (!bound || index === -1) return;
|
|
242
|
+
const [, radius] = props[index];
|
|
243
|
+
props.splice(index, 1, ...CORNER_PROPS.map((prop) => [prop, radius]));
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Write the variables `node` binds through the props that set those fields, such as
|
|
247
|
+
* `bg={theme.Surface}` and `p={density.Pad}`, and the rest in `bind`. Padding stays in `bind`
|
|
248
|
+
* on a layer without auto layout, where a padding prop would turn it on.
|
|
249
|
+
*/
|
|
250
|
+
function collectBindingProps(node, props, variables) {
|
|
251
|
+
const remaining = new Map(Object.entries(node.boundVariables));
|
|
252
|
+
const named = (variableId) => typeof variables.variable(variableId) !== "string";
|
|
253
|
+
const laidOut = node.layoutMode !== "NONE";
|
|
254
|
+
if (laidOut) writePadding(node, props, remaining, variables, named);
|
|
255
|
+
expandCorners(node, props, remaining, named);
|
|
256
|
+
for (const [field, variableId] of remaining) {
|
|
257
|
+
if (!named(variableId) || !laidOut && PADDING_FIELDS.includes(field)) continue;
|
|
258
|
+
const target = fieldProp(node, field, props);
|
|
259
|
+
if (target && setProp(props, target.prop, variables.variable(variableId), target.add)) remaining.delete(field);
|
|
260
|
+
}
|
|
261
|
+
if (remaining.size === 0) return;
|
|
262
|
+
const bindings = [...remaining].toSorted(([a], [b]) => a.localeCompare(b));
|
|
263
|
+
props.push(["bind", Object.fromEntries(bindings.map(([field, id]) => [field, variables.variable(id)]))]);
|
|
264
|
+
}
|
|
265
|
+
/** The modes a layer pins; one is written without a list. */
|
|
266
|
+
function collectModeProps(node, props, variables) {
|
|
267
|
+
const modes = Object.entries(node.variableModes).map(([collectionId, modeId]) => variables.mode(collectionId, modeId));
|
|
268
|
+
if (modes.length > 0) props.push(["mode", modes.length === 1 ? modes[0] : modes]);
|
|
269
|
+
}
|
|
270
|
+
//#endregion
|
|
271
|
+
export { collectBindingProps, collectModeProps, paintProps, scalarProps };
|
|
272
|
+
|
|
273
|
+
//# sourceMappingURL=bindings.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bindings.js","names":[],"sources":["../../../src/variables/props.ts","../../../src/export/bindings.ts"],"sourcesContent":["/** What decides which props bind a variable on a layer. */\nexport interface BindingContext {\n text: boolean\n grid: boolean\n wrap: boolean\n}\n\n/** A prop a variable binds through, and the fields it sets. */\nexport interface BoundProp {\n prop: string\n fields: readonly string[]\n}\n\nexport const PADDING_FIELDS = ['paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft']\n\n/**\n * The number props a FLOAT variable binds, in the order rendering reads them: shorthands before\n * their longhands, as `propsToOverrides` gives them precedence, so a literal longhand also\n * overrides a bound shorthand on that edge.\n */\nexport function scalarProps({ text, grid, wrap }: BindingContext): BoundProp[] {\n const props: BoundProp[] = [\n { prop: 'w', fields: ['width'] },\n { prop: 'h', fields: ['height'] },\n { prop: 'p', fields: PADDING_FIELDS },\n { prop: 'px', fields: ['paddingLeft', 'paddingRight'] },\n { prop: 'py', fields: ['paddingTop', 'paddingBottom'] },\n { prop: 'pt', fields: ['paddingTop'] },\n { prop: 'pr', fields: ['paddingRight'] },\n { prop: 'pb', fields: ['paddingBottom'] },\n { prop: 'pl', fields: ['paddingLeft'] },\n { prop: 'rounded', fields: ['cornerRadius'] },\n { prop: 'roundedTL', fields: ['topLeftRadius'] },\n { prop: 'roundedTR', fields: ['topRightRadius'] },\n { prop: 'roundedBL', fields: ['bottomLeftRadius'] },\n { prop: 'roundedBR', fields: ['bottomRightRadius'] },\n { prop: 'strokeWidth', fields: ['strokeWeight'] },\n { prop: 'opacity', fields: ['opacity'] }\n ]\n if (grid) {\n // Grid authoring gives `gap` precedence over the axis-specific props.\n props.push(\n { prop: 'columnGap', fields: ['gridColumnGap'] },\n { prop: 'rowGap', fields: ['gridRowGap'] },\n { prop: 'gap', fields: ['gridColumnGap', 'gridRowGap'] }\n )\n } else {\n props.push({ prop: 'gap', fields: ['itemSpacing'] })\n if (wrap) props.push({ prop: 'rowGap', fields: ['counterAxisSpacing'] })\n }\n if (text) {\n props.push(\n { prop: 'fontSize', fields: ['fontSize'] },\n // `size` is the short name, so it wins over `fontSize`, as it does for a literal.\n { prop: 'size', fields: ['fontSize'] },\n { prop: 'lineHeight', fields: ['lineHeight'] },\n { prop: 'letterSpacing', fields: ['letterSpacing'] }\n )\n }\n return props\n}\n\n/** The paint props a COLOR variable binds: the first fill's colour, or the first stroke's. */\nexport function paintProps({ text }: Pick<BindingContext, 'text'>): BoundProp[] {\n const fill = ['fills/0/color']\n const stroke = ['strokes/0/color']\n return [\n { prop: 'bg', fields: fill },\n { prop: 'fill', fields: fill },\n { prop: 'background', fields: fill },\n { prop: 'backgroundColor', fields: fill },\n ...(text ? [{ prop: 'color', fields: fill }] : []),\n { prop: 'stroke', fields: stroke },\n { prop: 'border', fields: stroke },\n { prop: 'borderColor', fields: stroke }\n ]\n}\n","import { isEqual } from 'es-toolkit'\n\nimport type { SceneNode } from '@pairdraw/scene-graph'\n\nimport {\n PADDING_FIELDS,\n paintProps,\n scalarProps,\n type BindingContext,\n type BoundProp\n} from '../variables/props'\nimport type { JSXProp, JSXValue } from './value'\nimport type { VariableExport } from './variables'\n\n/** Sizes are not added when the export left them out, as a fixed size would replace Hug or Fill. */\nconst NOT_ADDED = new Set(['width', 'height'])\n/** The corner props, which make the corners independent wherever one of them is written. */\nconst CORNER_PROPS = ['roundedTL', 'roundedTR', 'roundedBR', 'roundedBL']\n\nfunction bindingContext(node: SceneNode): BindingContext {\n return {\n text: node.type === 'TEXT',\n grid: node.layoutMode === 'GRID',\n wrap: node.layoutWrap === 'WRAP'\n }\n}\n\n/**\n * The prop `field` is written through on `node`: one the export printed that sets that field\n * alone, or else the last number prop that does, as rendering reads it, or none, when only\n * `bind` can set it. A paint prop is printed only for a single solid paint, which a colour\n * variable can stand for; a number prop printed as a word, such as `w=\"fill\"`, keeps it.\n */\nfunction fieldProp(node: SceneNode, field: string, props: JSXProp[]) {\n const context = bindingContext(node)\n const sets = ({ fields }: BoundProp) => fields.length === 1 && fields[0] === field\n const scalar = scalarProps(context).filter(sets)\n const printedAs = (prop: string, numeric: boolean) =>\n props.some(([name, value]) => name === prop && (!numeric || typeof value === 'number'))\n const printed =\n scalar.find(({ prop }) => printedAs(prop, true)) ??\n paintProps(context)\n .filter(sets)\n .find(({ prop }) => printedAs(prop, false))\n if (printed) return { prop: printed.prop, add: false }\n const last = scalar.at(-1)\n return last && !NOT_ADDED.has(field) ? { prop: last.prop, add: true } : undefined\n}\n\nfunction setProp(props: JSXProp[], name: string, value: JSXValue, add: boolean): boolean {\n const index = props.findIndex(([prop]) => prop === name)\n if (index !== -1) props[index] = [name, value]\n else if (add) props.push([name, value])\n return index !== -1 || add\n}\n\n/**\n * Write the padding again when a side is bound, each bound side as its variable, grouped as\n * `p`, `py` and `px`, or one prop per side, as the export groups literal padding.\n */\nfunction writePadding(\n node: SceneNode,\n props: JSXProp[],\n remaining: Map<string, string>,\n variables: VariableExport,\n named: (variableId: string) => boolean\n): void {\n const sides = PADDING_FIELDS.map((field): JSXValue => {\n const variableId = remaining.get(field)\n return variableId && named(variableId)\n ? variables.variable(variableId)\n : node[field as 'paddingTop']\n })\n if (sides.every((side) => typeof side === 'number')) return\n const paddingProps = new Set(\n scalarProps(bindingContext(node))\n .filter(({ fields }) => fields.every((field) => PADDING_FIELDS.includes(field)))\n .map(({ prop }) => prop)\n )\n for (let index = props.length - 1; index >= 0; index--) {\n if (paddingProps.has(props[index][0])) props.splice(index, 1)\n }\n const [top, right, bottom, left] = sides\n if ([right, bottom, left].every((side) => isEqual(side, top))) props.push(['p', top])\n else if (isEqual(top, bottom) && isEqual(left, right)) props.push(['py', top], ['px', left])\n else {\n ;(['pt', 'pr', 'pb', 'pl'] as const).forEach((prop, index) => {\n if (sides[index] !== 0) props.push([prop, sides[index]])\n })\n }\n for (const field of PADDING_FIELDS) {\n const variableId = remaining.get(field)\n if (variableId && named(variableId)) remaining.delete(field)\n }\n}\n\n/**\n * Write corners printed together as `rounded` one by one when a corner is bound, since the\n * bound corner's own prop makes the corners independent and the others would then be 0.\n */\nfunction expandCorners(\n node: SceneNode,\n props: JSXProp[],\n remaining: Map<string, string>,\n named: (variableId: string) => boolean\n): void {\n const corners = new Set(\n scalarProps(bindingContext(node))\n .filter(({ prop }) => CORNER_PROPS.includes(prop))\n .flatMap(({ fields }) => fields)\n )\n const bound = [...remaining].some(([field, id]) => corners.has(field) && named(id))\n const index = props.findIndex(([prop]) => prop === 'rounded')\n if (!bound || index === -1) return\n const [, radius] = props[index]\n props.splice(index, 1, ...CORNER_PROPS.map((prop): JSXProp => [prop, radius]))\n}\n\n/**\n * Write the variables `node` binds through the props that set those fields, such as\n * `bg={theme.Surface}` and `p={density.Pad}`, and the rest in `bind`. Padding stays in `bind`\n * on a layer without auto layout, where a padding prop would turn it on.\n */\nexport function collectBindingProps(\n node: SceneNode,\n props: JSXProp[],\n variables: VariableExport\n): void {\n const remaining = new Map(Object.entries(node.boundVariables))\n // A variable only `bind` can name, by its ID, is not written in a prop, which reads a string.\n const named = (variableId: string) => typeof variables.variable(variableId) !== 'string'\n const laidOut = node.layoutMode !== 'NONE'\n if (laidOut) writePadding(node, props, remaining, variables, named)\n expandCorners(node, props, remaining, named)\n for (const [field, variableId] of remaining) {\n if (!named(variableId) || (!laidOut && PADDING_FIELDS.includes(field))) continue\n const target = fieldProp(node, field, props)\n if (target && setProp(props, target.prop, variables.variable(variableId), target.add))\n remaining.delete(field)\n }\n if (remaining.size === 0) return\n const bindings = [...remaining].toSorted(([a], [b]) => a.localeCompare(b))\n props.push([\n 'bind',\n Object.fromEntries(bindings.map(([field, id]) => [field, variables.variable(id)]))\n ])\n}\n\n/** The modes a layer pins; one is written without a list. */\nexport function collectModeProps(node: SceneNode, props: JSXProp[], variables: VariableExport) {\n const modes = Object.entries(node.variableModes).map(([collectionId, modeId]) =>\n variables.mode(collectionId, modeId)\n )\n if (modes.length > 0) props.push(['mode', modes.length === 1 ? modes[0] : modes])\n}\n"],"mappings":";;AAaA,MAAa,iBAAiB;CAAC;CAAc;CAAgB;CAAiB;AAAa;;;;;;AAO3F,SAAgB,YAAY,EAAE,MAAM,MAAM,QAAqC;CAC7E,MAAM,QAAqB;EACzB;GAAE,MAAM;GAAK,QAAQ,CAAC,OAAO;EAAE;EAC/B;GAAE,MAAM;GAAK,QAAQ,CAAC,QAAQ;EAAE;EAChC;GAAE,MAAM;GAAK,QAAQ;EAAe;EACpC;GAAE,MAAM;GAAM,QAAQ,CAAC,eAAe,cAAc;EAAE;EACtD;GAAE,MAAM;GAAM,QAAQ,CAAC,cAAc,eAAe;EAAE;EACtD;GAAE,MAAM;GAAM,QAAQ,CAAC,YAAY;EAAE;EACrC;GAAE,MAAM;GAAM,QAAQ,CAAC,cAAc;EAAE;EACvC;GAAE,MAAM;GAAM,QAAQ,CAAC,eAAe;EAAE;EACxC;GAAE,MAAM;GAAM,QAAQ,CAAC,aAAa;EAAE;EACtC;GAAE,MAAM;GAAW,QAAQ,CAAC,cAAc;EAAE;EAC5C;GAAE,MAAM;GAAa,QAAQ,CAAC,eAAe;EAAE;EAC/C;GAAE,MAAM;GAAa,QAAQ,CAAC,gBAAgB;EAAE;EAChD;GAAE,MAAM;GAAa,QAAQ,CAAC,kBAAkB;EAAE;EAClD;GAAE,MAAM;GAAa,QAAQ,CAAC,mBAAmB;EAAE;EACnD;GAAE,MAAM;GAAe,QAAQ,CAAC,cAAc;EAAE;EAChD;GAAE,MAAM;GAAW,QAAQ,CAA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I,MAAM,KAAK,KAAK,CAAC;AAClF"}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import { TEXT_DECORATION_STYLE, fillFromValue, isFillValue, parseScriptInput } from "../component-properties.js";
|
|
2
|
+
import { paintPropValue } from "../elements.js";
|
|
3
|
+
import * as v from "valibot";
|
|
4
|
+
import { uniqBy } from "es-toolkit";
|
|
5
|
+
import { percentLength, pixelLength } from "@pairdraw/scene-graph/text";
|
|
6
|
+
//#region src/overrides/text.ts
|
|
7
|
+
/** Lengths that follow the font unless set take `'auto'`, as in CSS. */
|
|
8
|
+
const AUTO = "auto";
|
|
9
|
+
/** The decoration colour that follows the text's, as in CSS. */
|
|
10
|
+
const CURRENT_COLOR = "currentColor";
|
|
11
|
+
/** A percent of the font size, such as `'150%'`, which follows the size as in Figma. */
|
|
12
|
+
const PERCENT_LENGTH = /^(-?\d+(?:\.\d+)?)%$/;
|
|
13
|
+
/** A line height or letter spacing a prop gives: pixels as a number, or a percent string. */
|
|
14
|
+
function textLengthProp(value) {
|
|
15
|
+
if (typeof value === "number" && Number.isFinite(value)) return pixelLength(value);
|
|
16
|
+
const match = typeof value === "string" ? PERCENT_LENGTH.exec(value.trim()) : null;
|
|
17
|
+
return match ? percentLength(Number(match[1])) : void 0;
|
|
18
|
+
}
|
|
19
|
+
/** A line height or letter spacing as a prop writes it. */
|
|
20
|
+
function textLengthJSX(length) {
|
|
21
|
+
return length.unit === "PIXELS" ? length.value : `${length.value}%`;
|
|
22
|
+
}
|
|
23
|
+
const lengthSchema = v.pipe(v.number(), v.finite());
|
|
24
|
+
const autoLengthSchema = v.union([lengthSchema, v.literal(AUTO)]);
|
|
25
|
+
/** An OpenType feature or axis tag: four printable ASCII characters, such as `tnum` or `wght`. */
|
|
26
|
+
const openTypeTagSchema = v.pipe(v.string(), v.regex(/^[\x20-\x7E]{4}$/, "Expected a four-character tag"));
|
|
27
|
+
const textPropsSchema = v.object({
|
|
28
|
+
textDecorationStyle: v.optional(v.string()),
|
|
29
|
+
textDecorationColor: v.optional(v.custom(isFillValue, "Expected a colour or a paint")),
|
|
30
|
+
textDecorationThickness: v.optional(autoLengthSchema),
|
|
31
|
+
textUnderlineOffset: v.optional(autoLengthSchema),
|
|
32
|
+
textDecorationSkipInk: v.optional(v.boolean()),
|
|
33
|
+
fontFeatures: v.optional(v.pipe(v.record(openTypeTagSchema, v.boolean()), v.check((features) => {
|
|
34
|
+
const tags = Object.keys(features);
|
|
35
|
+
return uniqBy(tags, (tag) => tag.toUpperCase()).length === tags.length;
|
|
36
|
+
}, "Expected each feature tag once, in any case"))),
|
|
37
|
+
fontVariations: v.optional(v.record(openTypeTagSchema, lengthSchema)),
|
|
38
|
+
lang: v.optional(v.nullable(v.pipe(v.string(), v.trim(), v.nonEmpty()))),
|
|
39
|
+
fontOpticalSizing: v.optional(v.picklist([AUTO, "none"])),
|
|
40
|
+
paragraphSpacing: v.optional(lengthSchema),
|
|
41
|
+
listSpacing: v.optional(lengthSchema),
|
|
42
|
+
paragraphIndent: v.optional(lengthSchema),
|
|
43
|
+
hangingList: v.optional(v.boolean())
|
|
44
|
+
});
|
|
45
|
+
function autoLength(value) {
|
|
46
|
+
return value === "auto" ? null : value;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* The decoration details, font settings, and text-wide paragraph spacing a `<Text>` or `<Span>`
|
|
50
|
+
* sets. Font settings replace the ones around them as a whole, as CSS's do.
|
|
51
|
+
*/
|
|
52
|
+
function applyTextDetailOverrides(props, o) {
|
|
53
|
+
const parsed = parseScriptInput("Invalid <Text> props", textPropsSchema, props);
|
|
54
|
+
const color = parsed.textDecorationColor;
|
|
55
|
+
const style = TEXT_DECORATION_STYLE.parse(parsed.textDecorationStyle);
|
|
56
|
+
if (style) o.textDecorationStyle = style;
|
|
57
|
+
if (color !== void 0) o.textDecorationFills = typeof color === "string" && color.toLowerCase() === "currentColor".toLowerCase() ? [] : [fillFromValue(color)];
|
|
58
|
+
if (parsed.textDecorationThickness !== void 0) o.textDecorationThickness = autoLength(parsed.textDecorationThickness);
|
|
59
|
+
if (parsed.textUnderlineOffset !== void 0) o.textUnderlineOffset = autoLength(parsed.textUnderlineOffset);
|
|
60
|
+
if (parsed.textDecorationSkipInk !== void 0) o.textDecorationSkipInk = parsed.textDecorationSkipInk;
|
|
61
|
+
if (parsed.fontFeatures) o.fontFeatures = Object.entries(parsed.fontFeatures).map(([tag, enabled]) => ({
|
|
62
|
+
tag: tag.toUpperCase(),
|
|
63
|
+
enabled
|
|
64
|
+
}));
|
|
65
|
+
if (parsed.fontVariations) o.fontVariations = Object.entries(parsed.fontVariations).map(([axis, value]) => ({
|
|
66
|
+
axis,
|
|
67
|
+
value
|
|
68
|
+
}));
|
|
69
|
+
if (parsed.lang !== void 0) o.textLanguage = parsed.lang;
|
|
70
|
+
if (parsed.fontOpticalSizing !== void 0) o.opticalSizeFromFontSize = parsed.fontOpticalSizing === AUTO;
|
|
71
|
+
if (parsed.paragraphSpacing !== void 0) o.paragraphSpacing = parsed.paragraphSpacing;
|
|
72
|
+
if (parsed.listSpacing !== void 0) o.listSpacing = parsed.listSpacing;
|
|
73
|
+
if (parsed.paragraphIndent !== void 0) o.paragraphIndent = parsed.paragraphIndent;
|
|
74
|
+
if (parsed.hangingList !== void 0) o.hangingList = parsed.hangingList;
|
|
75
|
+
}
|
|
76
|
+
//#endregion
|
|
77
|
+
//#region src/export/decoration.ts
|
|
78
|
+
/**
|
|
79
|
+
* The decoration details set in `style`, as `<Text>` and `<Span>` write them. A decoration
|
|
80
|
+
* painted with more than one paint keeps only its first, the one `textDecorationColor` holds.
|
|
81
|
+
*/
|
|
82
|
+
function collectDecorationProps(style, node, props) {
|
|
83
|
+
const { textDecorationFills: fills } = style;
|
|
84
|
+
if (style.textDecorationStyle !== void 0) props.push(["textDecorationStyle", TEXT_DECORATION_STYLE.print(style.textDecorationStyle)]);
|
|
85
|
+
if (fills) {
|
|
86
|
+
const fill = fills.at(0);
|
|
87
|
+
props.push(["textDecorationColor", fill ? paintPropValue(fill, node) : CURRENT_COLOR]);
|
|
88
|
+
}
|
|
89
|
+
if (style.textDecorationThickness !== void 0) props.push(["textDecorationThickness", style.textDecorationThickness ?? "auto"]);
|
|
90
|
+
if (style.textUnderlineOffset !== void 0) props.push(["textUnderlineOffset", style.textUnderlineOffset ?? "auto"]);
|
|
91
|
+
if (style.textDecorationSkipInk !== void 0) props.push(["textDecorationSkipInk", style.textDecorationSkipInk]);
|
|
92
|
+
}
|
|
93
|
+
//#endregion
|
|
94
|
+
export { AUTO, applyTextDetailOverrides, collectDecorationProps, textLengthJSX, textLengthProp };
|
|
95
|
+
|
|
96
|
+
//# sourceMappingURL=decoration.js.map
|