import { FLAGS, isFlag } from '#dom-css/behaviours/args' import { layerKind } from '#dom-css/behaviours/states/layers' import type { StateElement } from '#dom-css/behaviours/states/types' import type { DesignStyleDeclaration } from '#dom-css/types' import { isEmptyObject } from 'es-toolkit/predicate' import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph' import { behaviourOwner, findLayerByPath } from '@open-pencil/scene-graph/behaviours' import { findComponentPropertyTargets } from '@open-pencil/scene-graph/components' import { isIconModified, isNamedIcon, readIcon } from '@open-pencil/scene-graph/icons' import { instanceMainComponent } from '@open-pencil/scene-graph/instances' import { appendAll } from '@open-pencil/std/arrays' import { drawsAsMain } from './drawn' import type { ComponentModel } from './model' /** A prop a reference sets on the component it uses: a variant or text value, or a flag. */ export interface ReferenceProp { name: string value: string | boolean } /** * Another generated component used where the design places an instance of it, with the values * the instance shows. Its own layers are the component's, so they are not drawn here. */ export interface ComponentReference { type: 'reference' /** The layer it draws, which code links back to. */ layerId?: string /** The component's identifier and file name. */ component: string /** The class the parent's state styles place it by. */ className: string props: ReferenceProp[] /** The two-way value the instance is drawn with, when it is on. */ model: string | null } /** An icon from a set, drawn by the framework's Iconify component. */ export interface IconReference { type: 'icon' /** The layer it draws, which code links back to. */ layerId?: string /** `prefix:name`. */ icon: string className: string } /** * How a parent places a layer, as opposed to how the layer looks. A component used in place of * a layer keeps its own look and state styles; the parent only places it. */ const PLACEMENT = /^(position|inset|left|top|right|bottom|(min-|max-)?(width|height)|margin(-.+)?|flex(-(grow|shrink|basis))?|align-self|justify-self|order|grid-(area|column|row)(-.+)?|transform(-origin)?|rotate|translate|scale|z-index)$/ /** Whether a declaration places a layer rather than drawing it. */ export const isPlacement = (property: string) => PLACEMENT.test(property) /** Whether a declaration hides or shows a layer by state, which the parent decides too. */ const isVisibility = (property: string, value: string) => property === 'display' && (value === 'none' || value === 'revert') /** Keeps only where the parent places a layer, and whether a state shows it. */ export function placementOnly(element: StateElement): void { const placement = (style: DesignStyleDeclaration): DesignStyleDeclaration => Object.fromEntries( Object.entries(style).filter( ([property, value]) => isPlacement(property) || isVisibility(property, value) ) ) element.base = placement(element.base) element.rules = element.rules .map((rule) => ({ ...rule, style: placement(rule.style) })) .filter((rule) => !isEmptyObject(rule.style)) } /** Generated components by the id of the set they come from, which instances refer to. */ export type ComponentReferences = ReadonlyMap /** The set a component belongs to, or the component itself when it stands alone. */ function ownerId(graph: SceneGraph, component: SceneNode): string { const parent = component.parentId ? graph.getNode(component.parentId) : undefined return parent?.type === 'COMPONENT_SET' ? parent.id : component.id } /** * The words an instance shows for a text property: an assignment that overrides the default, * else what its bound text layer reads, which a direct edit changes, else the assignment. */ export function shownText( graph: SceneGraph, instance: SceneNode, propertyId: string ): string | undefined { const assigned = instance.componentPropertyAssignments[propertyId] const main = instanceMainComponent(graph, instance) const owner = main && behaviourOwner(graph, main) const definition = owner?.componentPropertyDefinitions.find((item) => item.id === propertyId) if (typeof assigned === 'string' && assigned !== definition?.defaultValue) return assigned const target = findComponentPropertyTargets(graph, instance, propertyId).find( (item) => item.field === 'TEXT' && item.node.type === 'TEXT' ) return target?.node.text ?? (typeof assigned === 'string' ? assigned : undefined) } /** `disabled` and `invalid`, set where the instance shows the state property's value for them. */ function drawnFlags(component: ComponentModel, values: Record): ReferenceProp[] { const states = component.args.states if (!states) return [] return FLAGS.filter((flag) => { const value = states[flag] return value !== undefined && values[states.property] === value }).map((flag) => ({ name: flag, value: true })) } /** * What `instance` sets on `component`: the values it is drawn with that differ from defaults, * and whether it is drawn on: its model, or for a group's item the value that marks it chosen. */ export function referenceValues( graph: SceneGraph, instance: SceneNode, component: ComponentModel ): Pick { const values = instanceMainComponent(graph, instance)?.componentPropertyValues ?? {} const props: ReferenceProp[] = [] let model: string | null = null for (const [property, arg] of component.args.booleans) { if (values[property] !== arg.on) continue const on = arg.name === component.model || (component.valueProp && !isFlag(arg.name)) if (on) model = arg.name else props.push({ name: arg.name, value: true }) } // A set may draw a flag both as a boolean and as a state value; the prop is set once. const flags = drawnFlags(component, values) appendAll( props, flags.filter((flag) => !props.some((prop) => prop.name === flag.name)) ) for (const prop of component.props) { const value = values[prop.property] if (Object.hasOwn(values, prop.property) && value !== prop.default) props.push({ name: prop.name, value }) } for (const text of component.texts) { const value = shownText(graph, instance, text.id) if (value !== undefined && value !== text.default) props.push({ name: text.name, value }) } for (const prop of component.booleans) { const assignments = instance.componentPropertyAssignments const value = Object.hasOwn(assignments, prop.id) ? assignments[prop.id] === 'true' : prop.default if (value !== prop.default) props.push({ name: prop.name, value }) } return { props, model } } /** A used layer, before the parent's class name for it is known. */ export type UsedLayer = Omit | Omit /** * What the layer at `element` uses in place of drawing itself, if anything, read from the first * variant that draws it as that element: the rest state, or the one that shows it, such as open * content. */ function usedLayer( graph: SceneGraph, variantIds: readonly string[], element: StateElement, references: ComponentReferences ): UsedLayer | null { const path = element.key.split('\0')[0] ?? '' // The variant's layer at that path drawn as this element is: a frame, or that instance or icon. const node = variantIds .map((id) => findLayerByPath(graph, id, path)) .find((found) => found !== undefined && layerKind(graph, found) === element.kind) if (!node) return null const main = node.type === 'INSTANCE' ? instanceMainComponent(graph, node) : undefined // An instance changed beyond its properties draws its own layers, which the component's // props could not reproduce. const component = main && drawsAsMain(graph, node, main) ? references.get(ownerId(graph, main)) : undefined if (component) return { type: 'reference', component: component.name, ...referenceValues(graph, node, component) } const icon = readIcon(node) return icon && isNamedIcon(icon) && !isIconModified(graph, node) ? { type: 'icon', icon: icon.name } : null } /** * The layers of a set's merged markup that are used rather than drawn: instances of other * generated components, and icons from a set, read from the variants in order, the rest state * first. Their own layers are dropped from the markup and the styles, which belong to the * component or the icon. */ export function referencedLayers( graph: SceneGraph, root: StateElement, variantIds: readonly string[], references: ComponentReferences, /** Layers already used otherwise, such as a group's items. */ taken: ReadonlyMap = new Map() ): Map { const used = new Map() const visit = (element: StateElement) => { for (const child of element.children) { if (child.type !== 'element' || taken.has(child)) continue const layer = usedLayer(graph, variantIds, child, references) if (!layer) { visit(child) continue } used.set(child, layer) child.children = [] if (layer.type === 'reference') placementOnly(child) } } visit(root) return used }