@petrarca/sonnet-schema-designer 0.6.0 → 0.8.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/README.md +97 -0
- package/dist/index.d.ts +20 -11
- package/dist/index.js +36 -7
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/model/paths.ts","../src/model/view.ts","../src/model/mutate.ts","../src/model/compatibleWidgets.ts","../src/model/embed.ts","../src/hooks/useDesignerState.ts","../src/capabilities.ts","../src/model/scoping.ts","../src/SchemaDesigner.tsx","../src/FormSettingsSheet.tsx","../src/inspector/layoutMetaSchemas.ts","../src/tree/PropertyTree.tsx","../src/preview/PreviewPane.tsx","../src/preview/TablePreview.tsx","../src/preview/sampleRows.ts","../src/designers/FormLayoutDesigner.tsx","../src/inspector/RuleFields.tsx","../src/model/conditions.ts","../src/inspector/OperatorValueInput.tsx","../src/inspector/ruleEffects.ts","../src/preview/CapabilitiesPanel.tsx","../src/preview/SchemaSourcePanel.tsx","../src/inspector/Inspector.tsx","../src/inspector/DataTab.tsx","../src/inspector/metaSchemas.ts","../src/inspector/UITab.tsx","../src/inspector/EnumEditor.tsx","../src/inspector/TableHintsTab.tsx","../src/inspector/ConditionEditor.tsx","../src/inspector/RuleEditor.tsx","../src/inspector/ReferenceTab.tsx"],"sourcesContent":["/**\n * Path navigation over a JsonSchema tree.\n *\n * A path is a list of typed segments from the root down to a property. Most\n * segments are property keys (`{kind:\"prop\"}`) -- object children nest through\n * `properties`, array-of-object children through `items.properties`, and the\n * navigator descends through `items` transparently so an array and its item\n * object share one editing surface.\n *\n * Logic constructs introduce non-property segments: `{kind:\"branch\"}` for a\n * `oneOf`/`allOf` element, and `{kind:\"slot\"}` for a fixed schema slot\n * (`then`/`else`/`items`). The discriminated union keeps the distinction\n * explicit and type-checked; a single codec (pathKey/parsePathKey) owns all\n * conversion to/from strings.\n */\n\nimport type {\n JsonSchema,\n JsonSchemaProperty,\n} from \"@petrarca/sonnet-core/schema\";\nimport {\n isOneOf,\n getDiscriminator,\n getBranchLabel,\n} from \"@petrarca/sonnet-core/schema\";\n\n/** A fixed schema slot that holds a single sub-schema. */\nexport type PathSlot = \"then\" | \"else\" | \"items\";\n\n/**\n * The array a conditional (if/then/else) member lives in. `allOf` = every\n * condition must hold (AND); `anyOf` = any condition suffices (OR). Maps to\n * FHIR `enableBehavior` \"all\" / \"any\".\n */\nexport type ConditionCombinator = \"allOf\" | \"anyOf\";\n\n/** One step in a property path. */\nexport type PathSegment =\n | { kind: \"prop\"; key: string }\n | { kind: \"branch\"; index: number }\n | { kind: \"condition\"; combinator: ConditionCombinator; index: number }\n | { kind: \"slot\"; slot: PathSlot }\n | { kind: \"def\"; name: string };\n\nexport type PropertyPath = PathSegment[];\n\n/**\n * Whether a property key is reserved by the path codec. Keys matching\n * `/^#(branch|condition|def|slot):/` would corrupt the pathKey/parsePathKey\n * round-trip. The designer guards against these at rename/add time.\n */\nexport function isReservedKey(key: string): boolean {\n return /^#(branch|condition|def|slot):/.test(key);\n}\n\n/** Construct a property-key segment. */\nexport function prop(key: string): PathSegment {\n return { kind: \"prop\", key };\n}\n\n/** Construct a branch (oneOf element) segment. */\nexport function branch(index: number): PathSegment {\n return { kind: \"branch\", index };\n}\n\n/** Construct a condition (if/then/else member) segment for a combinator array. */\nexport function condition(\n index: number,\n combinator: ConditionCombinator = \"allOf\",\n): PathSegment {\n return { kind: \"condition\", combinator, index };\n}\n\n/** Construct a fixed-slot segment. */\nexport function slot(name: PathSlot): PathSegment {\n return { kind: \"slot\", slot: name };\n}\n\n/** Construct a definition ($defs entry) segment. Root-only in practice. */\nexport function def(name: string): PathSegment {\n return { kind: \"def\", name };\n}\n\n// ---- Codec: the single segment <-> string boundary ------------------------\n\n// Non-prop segments use a reserved \"#\" prefix that cannot be a JSON Schema\n// property key produced by the designer. Prop keys are percent-ish escaped so\n// the \".\" join is reversible even for keys containing separators.\nconst SEP = \"/\";\n\n// Escape backslash first, then the separator, so parse is unambiguous.\nfunction escapeToken(raw: string): string {\n return raw.replace(/\\\\/g, \"\\\\\\\\\").replace(/\\//g, \"\\\\/\");\n}\n\nfunction unescapeToken(raw: string): string {\n return raw.replace(/\\\\\\//g, \"/\").replace(/\\\\\\\\/g, \"\\\\\");\n}\n\nfunction encodeSegment(seg: PathSegment): string {\n switch (seg.kind) {\n case \"prop\":\n return escapeToken(seg.key);\n case \"branch\":\n return `#branch:${seg.index}`;\n case \"condition\":\n return `#condition:${seg.combinator}:${seg.index}`;\n case \"slot\":\n return `#slot:${seg.slot}`;\n case \"def\":\n return `#def:${escapeToken(seg.name)}`;\n }\n}\n\nconst VALID_SLOTS: readonly PathSlot[] = [\"then\", \"else\", \"items\"];\n\n// Parse a non-negative integer, defaulting to 0 for tampered/invalid tokens.\nfunction safeIndex(raw: string): number {\n const n = Number(raw);\n return Number.isInteger(n) && n >= 0 ? n : 0;\n}\n\n// Decode \"#condition:<combinator>:<index>\" (legacy \"#condition:<index>\" -> allOf).\nfunction decodeCondition(rest: string): PathSegment {\n const sep = rest.indexOf(\":\");\n const combinatorRaw = sep >= 0 ? rest.slice(0, sep) : \"allOf\";\n const combinator: ConditionCombinator =\n combinatorRaw === \"anyOf\" ? \"anyOf\" : \"allOf\";\n const index = safeIndex(sep >= 0 ? rest.slice(sep + 1) : rest);\n return { kind: \"condition\", combinator, index };\n}\n\nfunction decodeSegment(token: string): PathSegment {\n if (token.startsWith(\"#branch:\")) {\n return { kind: \"branch\", index: safeIndex(token.slice(\"#branch:\".length)) };\n }\n if (token.startsWith(\"#condition:\")) {\n return decodeCondition(token.slice(\"#condition:\".length));\n }\n if (token.startsWith(\"#slot:\")) {\n const s = token.slice(\"#slot:\".length) as PathSlot;\n return { kind: \"slot\", slot: VALID_SLOTS.includes(s) ? s : \"items\" };\n }\n if (token.startsWith(\"#def:\")) {\n return { kind: \"def\", name: unescapeToken(token.slice(\"#def:\".length)) };\n }\n return { kind: \"prop\", key: unescapeToken(token) };\n}\n\n// Split on unescaped separators.\nfunction splitTokens(key: string): string[] {\n const tokens: string[] = [];\n let current = \"\";\n for (let i = 0; i < key.length; i++) {\n const ch = key[i];\n if (ch === \"\\\\\" && i + 1 < key.length) {\n current += ch + key[i + 1];\n i++;\n } else if (ch === SEP) {\n tokens.push(current);\n current = \"\";\n } else {\n current += ch;\n }\n }\n tokens.push(current);\n return tokens;\n}\n\n/** Serialize a path to a stable string (React key, selection id, scope value). */\nexport function pathKey(path: PropertyPath): string {\n return path.map(encodeSegment).join(SEP);\n}\n\n/** Parse a string produced by {@link pathKey} back into a path. */\nexport function parsePathKey(key: string): PropertyPath {\n if (key === \"\") return [];\n return splitTokens(key).map(decodeSegment);\n}\n\n// ---- Comparison -----------------------------------------------------------\n\n// A stable string identity for a segment's payload; two segments are equal iff\n// their kind and identity string match. Keeps sameSegment's complexity flat.\nfunction segmentIdentity(seg: PathSegment): string {\n switch (seg.kind) {\n case \"prop\":\n return `prop:${seg.key}`;\n case \"branch\":\n return `branch:${seg.index}`;\n case \"condition\":\n return `condition:${seg.combinator}:${seg.index}`;\n case \"slot\":\n return `slot:${seg.slot}`;\n case \"def\":\n return `def:${seg.name}`;\n }\n}\n\n/** Whether two path segments refer to the same position. */\nexport function sameSegment(a: PathSegment, b: PathSegment): boolean {\n return segmentIdentity(a) === segmentIdentity(b);\n}\n\n/** Whether two paths refer to the same node (structural comparison). */\nexport function samePath(\n a: PropertyPath | null,\n b: PropertyPath | null,\n): boolean {\n if (a === null || b === null) return a === b;\n return a.length === b.length && a.every((seg, i) => sameSegment(seg, b[i]));\n}\n\n// ---- Child slots (the container abstraction) ------------------------------\n\n/** How a child slot is presented and mutated. */\nexport type SlotKind = \"property\" | \"branch\" | \"conditional\" | \"definition\";\n\n/** A single editable child of a property (or the root). */\nexport interface ChildSlot {\n /** Segment appended to the parent path to reach this child. */\n segment: PathSegment;\n /** Display label for the tree row. */\n label: string;\n /** The child schema. */\n property: JsonSchemaProperty;\n kind: SlotKind;\n removable: boolean;\n reorderable: boolean;\n}\n\n/**\n * The properties map that holds a property's named children, or undefined when\n * it has none. Object children live in `properties`; array-of-object children\n * live in `items.properties`. (Logic constructs use branch/slot children and\n * are surfaced via {@link childSlots}, not here.)\n */\nexport function childContainer(\n prop: JsonSchemaProperty,\n): Record<string, JsonSchemaProperty> | undefined {\n // A oneOf branch is an object-shaped schema that may omit `type`; treat\n // properties-bearing schemas with type \"object\" or no type (branches) as\n // containers. Exclude typed scalars that happen to carry a `properties` key\n // (valid in some JSON Schema dialects as an annotation) and oneOf unions\n // (whose children are branches, not properties).\n const typeIsObjectLike = prop.type === \"object\" || prop.type === undefined;\n if (typeIsObjectLike && prop.properties && !prop.oneOf)\n return prop.properties;\n if (prop.type === \"array\" && prop.items?.type === \"object\") {\n return prop.items.properties;\n }\n return undefined;\n}\n\n/** Whether an allOf/anyOf member is a conditional (carries an `if`). */\nfunction isConditionalMember(member: JsonSchemaProperty): boolean {\n return !!member.if;\n}\n\ninterface ConditionalMember {\n member: JsonSchemaProperty;\n combinator: ConditionCombinator;\n index: number;\n}\n\n// The conditional members in one combinator array, with their positional index.\nfunction membersOfCombinator(\n property: JsonSchemaProperty,\n combinator: ConditionCombinator,\n): ConditionalMember[] {\n const arr = property[combinator];\n if (!Array.isArray(arr)) return [];\n return arr\n .map((member, index) => ({ member, combinator, index }))\n .filter(({ member }) => isConditionalMember(member));\n}\n\n/** The conditional members of a property across both allOf (AND) and anyOf (OR). */\nfunction conditionalMembers(property: JsonSchemaProperty): ConditionalMember[] {\n return [\n ...membersOfCombinator(property, \"allOf\"),\n ...membersOfCombinator(property, \"anyOf\"),\n ];\n}\n\n// A short label for a conditional derived from its `if` (e.g. \"if smoker\").\n// The field is in `if.properties` for value operators, or `if.required` for the\n// bare `exists` operator (which has no per-property constraint).\nfunction conditionLabel(member: JsonSchemaProperty): string {\n const field =\n Object.keys(member.if?.properties ?? {})[0] ?? member.if?.required?.[0];\n return field ? `if ${field}` : \"if ...\";\n}\n\n// The then/else slots of a conditional member (only present ones are shown).\nfunction conditionalSlots(member: JsonSchemaProperty): ChildSlot[] {\n const slots: ChildSlot[] = [];\n const add = (name: \"then\" | \"else\", sub: JsonSchemaProperty | undefined) => {\n if (sub) {\n slots.push({\n segment: slot(name),\n label: name,\n property: sub,\n kind: \"conditional\",\n removable: false,\n reorderable: false,\n });\n }\n };\n add(\"then\", member.then);\n add(\"else\", member.else);\n return slots;\n}\n\n/**\n * The reusable definitions map of a schema. Canonically 2020-12 `$defs`; also\n * reads Draft-7 `definitions` so both dialects surface as editable nodes. New\n * definitions are always authored into `$defs` (see mutate.addDefinition).\n */\nexport function definitionsOf(\n property: JsonSchemaProperty,\n): Record<string, JsonSchemaProperty> | undefined {\n return property.$defs ?? property.definitions;\n}\n\n// One definition slot per $defs (or Draft-7 definitions) entry.\nfunction definitionSlots(property: JsonSchemaProperty): ChildSlot[] {\n const defs = definitionsOf(property);\n if (!defs) return [];\n return Object.keys(defs).map((name) => ({\n segment: def(name),\n label: name,\n property: defs[name],\n kind: \"definition\" as const,\n removable: true,\n reorderable: false,\n }));\n}\n\n/**\n * The ordered child slots of a property (the single extension point for the\n * tree/inspector/mutations). Surfaces object/array property children, oneOf\n * branches, if/then/else conditionals (allOf/anyOf members), and $defs\n * definitions (root-only in practice).\n */\nexport function childSlots(property: JsonSchemaProperty): ChildSlot[] {\n // A conditional (allOf member with an `if`) exposes its then/else as slots.\n if (isConditionalMember(property)) return conditionalSlots(property);\n // oneOf: one branch slot per element.\n if (isOneOf(property)) {\n const discriminator = getDiscriminator(property);\n return (property.oneOf ?? []).map((b, index) => ({\n segment: branch(index),\n label: getBranchLabel(b, discriminator, index),\n property: b,\n kind: \"branch\" as const,\n removable: true,\n reorderable: true,\n }));\n }\n // object / array-of-object: property slots, then any conditional members.\n const container = childContainer(property);\n const propertySlots: ChildSlot[] = container\n ? Object.keys(container).map((key) => ({\n segment: prop(key),\n label: key,\n property: container[key],\n kind: \"property\" as const,\n removable: true,\n reorderable: true,\n }))\n : [];\n const conditionSlots: ChildSlot[] = conditionalMembers(property).map(\n ({ member, combinator, index }) => ({\n segment: condition(index, combinator),\n label: conditionLabel(member),\n property: member,\n kind: \"conditional\" as const,\n removable: true,\n reorderable: false,\n }),\n );\n return [...propertySlots, ...conditionSlots, ...definitionSlots(property)];\n}\n\n// ---- Navigation -----------------------------------------------------------\n\n// Resolve the immediate child of a property named by one segment.\nfunction stepInto(\n parent: JsonSchemaProperty,\n seg: PathSegment,\n): JsonSchemaProperty | undefined {\n if (seg.kind === \"prop\") return childContainer(parent)?.[seg.key];\n if (seg.kind === \"branch\") return parent.oneOf?.[seg.index];\n if (seg.kind === \"condition\") return parent[seg.combinator]?.[seg.index];\n if (seg.kind === \"def\") return definitionsOf(parent)?.[seg.name];\n if (seg.slot === \"items\") return parent.items;\n return parent[seg.slot];\n}\n\n/**\n * Wrap a JsonSchema root as an object-shaped JsonSchemaProperty so the path\n * navigation machinery can traverse it with the same stepInto logic as any\n * nested property. Pass the keys needed by the caller; unused fields default\n * to undefined.\n */\nexport function schemaAsRootProp(schema: JsonSchema): JsonSchemaProperty {\n return {\n type: \"object\",\n properties: schema.properties,\n required: schema.required,\n \"x-ui-order\": schema[\"x-ui-order\"],\n allOf: schema.allOf,\n anyOf: schema.anyOf,\n $defs: schema.$defs,\n definitions: schema.definitions,\n };\n}\n\n/** Resolve a path to its property definition, or undefined if not found. */\nexport function getProperty(\n schema: JsonSchema,\n path: PropertyPath,\n): JsonSchemaProperty | undefined {\n if (path.length === 0) return undefined;\n // Treat the schema root as an object-shaped property so root children --\n // named properties AND allOf conditionals -- are reached the same way as\n // nested ones (step by step through the segment machinery).\n const root = schemaAsRootProp(schema);\n let current: JsonSchemaProperty | undefined = root;\n for (const seg of path) {\n if (!current) return undefined;\n current = stepInto(current, seg);\n }\n return current;\n}\n\n/** Whether a property has (or can have) child slots (properties, branches, conditionals). */\nexport function isContainer(prop: JsonSchemaProperty): boolean {\n return childSlots(prop).length > 0 || childContainer(prop) !== undefined;\n}\n","/**\n * Read-shaping: turn a JsonSchema into a property tree for the designer UI.\n *\n * Pure, no React. Ordering follows the renderer's rule: an explicit x-ui-order\n * first, then remaining keys in declaration order.\n */\n\nimport type {\n JsonSchema,\n JsonSchemaProperty,\n RefResolver,\n} from \"@petrarca/sonnet-core/schema\";\nimport {\n childSlots,\n isContainer,\n schemaAsRootProp,\n type ChildSlot,\n type PropertyPath,\n type SlotKind,\n} from \"./paths\";\nimport { isOneOf } from \"@petrarca/sonnet-core/schema\";\n\nexport type PropertyKind =\n | \"scalar\"\n | \"enum\"\n | \"object\"\n | \"array\"\n | \"oneOf\"\n | \"conditional\"\n | \"reference\"\n | \"definition\";\n\nexport interface PropertyNode {\n path: PropertyPath;\n key: string;\n property: JsonSchemaProperty;\n kind: PropertyKind;\n /** How this node sits in its parent: a named property or a oneOf branch. */\n slotKind: SlotKind;\n required: boolean;\n /** Short type descriptor for the tree row, e.g. \"string\", \"object[]\". */\n typeLabel: string;\n /** Resolved widget override (x-ui-widget) if any. */\n widget?: string;\n /**\n * When this node is a `$ref`, the ref string it points at. Undefined for\n * non-ref nodes.\n */\n reference?: string;\n /**\n * True for nodes that live inside a resolved `$ref` (the ref's descendants).\n * These come from a shared definition and are not editable here -- the tree\n * and inspector use this to show read-only affordances. Computed once at\n * build time (no per-render schema walks). The ref node itself is NOT marked\n * (the usage can be renamed/deleted).\n */\n readOnly?: boolean;\n children: PropertyNode[];\n}\n\n/** Classify a property into a tree kind. */\nexport function propertyKind(prop: JsonSchemaProperty): PropertyKind {\n if (prop.if) return \"conditional\";\n if (isOneOf(prop)) return \"oneOf\";\n if (prop.type === \"object\" && prop.properties) return \"object\";\n if (prop.type === \"array\") return \"array\";\n if (Array.isArray(prop.enum) && prop.enum.length > 0) return \"enum\";\n return \"scalar\";\n}\n\n// Cardinality inside the brackets, standard multiplicity notation:\n// [] -- unconstrained\n// [3] -- exactly 3 (min == max)\n// [1..5] -- between 1 and 5\n// [1..] -- at least 1\n// [..5] -- at most 5\nfunction arrayCardinality(\n min: number | undefined,\n max: number | undefined,\n): string {\n if (min == null && max == null) return \"\";\n if (min != null && min === max) return `${min}`;\n return `${min ?? \"\"}..${max ?? \"\"}`;\n}\n\nfunction typeLabelOf(prop: JsonSchemaProperty): string {\n if (prop.if) return \"if/then/else\";\n if (isOneOf(prop)) return \"oneOf\";\n if (prop.type === \"array\") {\n const itemType = prop.items?.type ?? \"any\";\n // Compact array indicator (e.g. \"object[]\", \"object[1..5]\") so the type\n // descriptor stays short and does not crowd out the property name.\n return `${itemType}[${arrayCardinality(prop.minItems, prop.maxItems)}]`;\n }\n return prop.type ?? \"any\";\n}\n\n/** Order keys by explicit x-ui-order, then remaining declaration order. */\nexport function orderedKeys(\n properties: Record<string, JsonSchemaProperty>,\n order: string[] | undefined,\n): string[] {\n const keys = Object.keys(properties);\n if (!order || order.length === 0) return keys;\n const inOrder = order.filter((k) => k in properties);\n const rest = keys.filter((k) => !inOrder.includes(k));\n return [...inOrder, ...rest];\n}\n\n// The required-key list for a container property (object -> its required;\n// array-of-object -> items.required). Branches/oneOf have none.\nfunction requiredOf(prop: JsonSchemaProperty): string[] | undefined {\n if (prop.type === \"object\") return prop.required;\n if (prop.type === \"array\") return prop.items?.required;\n return undefined;\n}\n\n// The x-ui-order for a container property (object own, array via items).\nfunction orderOf(prop: JsonSchemaProperty): string[] | undefined {\n if (prop.type === \"array\") return prop.items?.[\"x-ui-order\"];\n return prop[\"x-ui-order\"];\n}\n\n// The tree kind of a node built from a slot. Branches and then/else slots are\n// anonymous object schemas (may omit `type`), shown as \"object\"; a conditional\n// member (the allOf if/then/else) is shown as \"conditional\".\nfunction nodeKind(slot: ChildSlot, prop: JsonSchemaProperty): PropertyKind {\n if (slot.kind === \"branch\") return \"object\";\n if (slot.segment.kind === \"def\") return \"definition\";\n if (slot.segment.kind === \"slot\") return \"object\"; // then / else / items\n return propertyKind(prop);\n}\n\n// The required-key list a container exposes to its property children. For a\n// then/else slot the required lives on the slot schema itself.\nfunction requiredForChildren(\n prop: JsonSchemaProperty,\n isSlot: boolean,\n): string[] | undefined {\n return isSlot ? prop.required : requiredOf(prop);\n}\n\n// Resolve a $ref node one level to its target for child display; undefined when\n// the node is not a ref or the ref cannot be resolved.\nfunction resolveRefTarget(\n prop: JsonSchemaProperty,\n resolve: RefResolver | undefined,\n): JsonSchemaProperty | undefined {\n if (!prop.$ref || !resolve) return undefined;\n const target = resolve(prop.$ref);\n if (!target) return undefined;\n // Merge node-level overrides (e.g. title) over the target, as the renderer does.\n const { $ref: _drop, ...overrides } = prop;\n return { ...target, ...overrides };\n}\n\n// How a node relates to a shared definition: a direct $ref, an array whose\n// items is a $ref, or neither. `container` is the schema whose child slots the\n// node exposes (the resolved target for refs, else the property itself).\ninterface RefShape {\n kind: PropertyKind;\n typeLabel: string;\n reference?: string;\n container: JsonSchemaProperty;\n // Whether this node's children come from a shared definition (read-only).\n childrenFromRef: boolean;\n}\n\n// Classify a property's relationship to a definition and derive its display.\nfunction refShapeOf(\n slot: ChildSlot,\n prop: JsonSchemaProperty,\n resolve: RefResolver | undefined,\n): RefShape {\n // A $ref node keeps its original property (with $ref) for identity/marker,\n // but its children come from the resolved target (read-only).\n const refTarget = resolveRefTarget(prop, resolve);\n if (refTarget) {\n return {\n kind: \"reference\",\n typeLabel: refLabel(prop.$ref!),\n reference: prop.$ref,\n container: refTarget,\n childrenFromRef: true,\n };\n }\n // An array-of-$ref surfaces the referenced element's fields as read-only\n // children while remaining an array node.\n if (prop.type === \"array\" && prop.items?.$ref) {\n const itemTarget = resolveRefTarget(prop.items, resolve);\n if (itemTarget) {\n return {\n kind: \"array\",\n typeLabel: arrayItemLabel(prop.items.$ref, prop),\n reference: prop.items.$ref,\n container: itemTarget,\n childrenFromRef: true,\n };\n }\n }\n return {\n kind: nodeKind(slot, prop),\n typeLabel: typeLabelOf(prop),\n container: prop,\n childrenFromRef: false,\n };\n}\n\nfunction buildNode(\n slot: ChildSlot,\n parentPath: PropertyPath,\n required: boolean,\n resolve: RefResolver | undefined,\n inRef: boolean,\n): PropertyNode {\n const path = [...parentPath, slot.segment];\n const prop = slot.property;\n const widget =\n typeof prop[\"x-ui-widget\"] === \"string\" ? prop[\"x-ui-widget\"] : undefined;\n const ref = refShapeOf(slot, prop, resolve);\n const node: PropertyNode = {\n path,\n key: slot.label,\n property: prop,\n kind: ref.kind,\n slotKind: slot.kind,\n required,\n typeLabel: ref.typeLabel,\n widget,\n reference: ref.reference,\n readOnly: inRef || undefined,\n children: [],\n };\n if (isContainer(ref.container)) {\n const isSlot = slot.segment.kind === \"slot\";\n const req = requiredForChildren(ref.container, isSlot);\n // Descendants of a $ref node (or of an already-read-only node) are read-only.\n const childrenInRef = inRef || ref.childrenFromRef;\n node.children = orderedSlots(ref.container).map((child) =>\n buildNode(\n child,\n path,\n child.kind === \"property\" ? !!req?.includes(child.label) : false,\n resolve,\n childrenInRef,\n ),\n );\n }\n return node;\n}\n\n// The definition name from a local $ref pointer (or the trailing URI segment).\nfunction refName(ref: string): string {\n const local = ref.match(/^#\\/(?:\\$defs|definitions)\\/(.+)$/);\n return local ? local[1] : ref.split(\"/\").pop() || ref;\n}\n\n// A compact label for a ref, e.g. \"#/$defs/Address\" -> \"-> Address\"; a registry\n// id or URI shows the trailing segment.\nfunction refLabel(ref: string): string {\n return `\\u2192 ${refName(ref)}`;\n}\n\n// A compact label for an array-of-$ref, e.g. \"Address[1..3]\".\nfunction arrayItemLabel(ref: string, prop: JsonSchemaProperty): string {\n return `${refName(ref)}[${arrayCardinality(prop.minItems, prop.maxItems)}]`;\n}\n\n// Child slots in display order. x-ui-order applies ONLY to property children\n// (keyed by property name); branch/conditional/definition slots keep their\n// positional order and follow the properties. Ordering is scoped to property\n// slots so a definition sharing a name with a property (both label \"vitals\")\n// cannot shadow the property (label is not a unique key across slot kinds).\nfunction orderedSlots(prop: JsonSchemaProperty): ChildSlot[] {\n const slots = childSlots(prop);\n const propertySlots = slots.filter((s) => s.kind === \"property\");\n const otherSlots = slots.filter((s) => s.kind !== \"property\");\n const order = orderOf(prop);\n if (propertySlots.length === 0 || !order || order.length === 0) return slots;\n const byLabel = new Map(propertySlots.map((s) => [s.label, s]));\n const inOrder = order\n .filter((k) => byLabel.has(k))\n .map((k) => byLabel.get(k)!);\n const rest = propertySlots.filter((s) => !order.includes(s.label));\n return [...inOrder, ...rest, ...otherSlots];\n}\n\n/**\n * Build the full property tree for a schema. Pass `resolve` to expand `$ref`\n * nodes (read-only) so referenced structure is legible; without it, ref nodes\n * show as leaves. `resolve` mirrors the renderer's RefResolver.\n */\nexport function buildPropertyTree(\n schema: JsonSchema,\n resolve?: RefResolver,\n): PropertyNode[] {\n // Default to an in-document $defs/definitions resolver so local refs expand\n // without the consumer wiring anything; an injected resolver (registry/URI)\n // is tried first and this is the fallback.\n const effective = withInDocumentFallback(schema, resolve);\n const rootProp = schemaAsRootProp(schema);\n return orderedSlots(rootProp).map((slot) =>\n buildNode(\n slot,\n [],\n !!schema.required?.includes(slot.label),\n effective,\n false,\n ),\n );\n}\n\n// Compose the injected resolver (if any) with an in-document $defs lookup.\nfunction withInDocumentFallback(\n schema: JsonSchema,\n resolve: RefResolver | undefined,\n): RefResolver | undefined {\n const defs = schema.$defs ?? schema.definitions;\n if (!defs) return resolve;\n const local: RefResolver = (ref) => {\n const m = ref.match(/^#\\/(?:\\$defs|definitions)\\/(.+)$/);\n return m ? defs[m[1]] : undefined;\n };\n return resolve ? (ref) => resolve(ref) ?? local(ref) : local;\n}\n\n/**\n * A layout scope: a container whose fields can be arranged into rows. Root is\n * the form itself (path []); nested scopes are object/array containers.\n */\nexport interface LayoutScope {\n /** Empty for root, otherwise the property path to the container. */\n path: PropertyPath;\n /** Human label, e.g. \"Form (root)\" or \"contact\" or \"addresses (items)\". */\n label: string;\n}\n\n/** Enumerate all layout scopes: the root form plus every object/array container. */\nexport function layoutScopes(schema: JsonSchema): LayoutScope[] {\n const scopes: LayoutScope[] = [{ path: [], label: \"Form (root)\" }];\n const walk = (nodes: PropertyNode[], labelPrefix: string[]) => {\n for (const node of nodes) {\n // Layout rows are keyed by property name within a property container.\n // Skip containers reached through a non-property segment (oneOf branch,\n // conditional member, then/else slot) -- their fields are not laid out\n // by the property-name-based row model.\n const allProps = node.path.every((s) => s.kind === \"prop\");\n if (allProps && (node.kind === \"object\" || node.kind === \"array\")) {\n const labels = [...labelPrefix, node.key];\n const suffix = node.kind === \"array\" ? \" (items)\" : \"\";\n scopes.push({\n path: node.path,\n label: labels.join(\" \\u203a \") + suffix,\n });\n walk(node.children, labels);\n }\n }\n };\n walk(buildPropertyTree(schema), []);\n return scopes;\n}\n","/**\n * Pure edit operations over { schema, uiSchema }.\n *\n * Every function returns a new pair; nothing mutates in place. Operations keep\n * the schema and uiSchema consistent -- renaming a property rewrites the property\n * key, the uiSchema entry, the required entry, and any x-ui-order reference at\n * the same level. Mirrors the graph-model/mutate.ts discipline.\n */\n\nimport type {\n JsonSchema,\n JsonSchemaProperty,\n UISchema,\n UILayoutConfig,\n UILayoutRowConfig,\n UILayoutGroupConfig,\n UISchemaOptions,\n} from \"@petrarca/sonnet-core/schema\";\nimport {\n getProperty,\n isReservedKey,\n prop as propSeg,\n branch as branchSeg,\n condition as condSeg,\n def as defSeg,\n type ConditionCombinator,\n type PathSegment,\n type PropertyPath,\n} from \"./paths\";\n\nexport type UiSchemaMap = Record<string, UISchema>;\n\n// The property key of a segment, or undefined for non-property segments.\n// Phase 1 mutations operate on property (prop-kind) children only.\nfunction segKey(seg: PathSegment | undefined): string | undefined {\n return seg && seg.kind === \"prop\" ? seg.key : undefined;\n}\n\n// The property keys along a path (prop segments only). Used to walk the\n// uiSchema x-ui-fields nesting, which is keyed by property name.\nfunction propKeys(path: PropertyPath): string[] {\n return path.flatMap((s) => (s.kind === \"prop\" ? [s.key] : []));\n}\n\nexport interface DesignerModel {\n schema: JsonSchema;\n uiSchema: UiSchemaMap;\n}\n\n// Deep clone via structuredClone (available in the runtime targets).\nfunction clone<T>(v: T): T {\n return structuredClone(v);\n}\n\n/** Kinds that can be created as a new property. */\nexport type NewPropertyKind = \"scalar\" | \"object\" | \"array\" | \"oneOf\";\n\n/** A default property for a newly created property of a given kind. */\nexport function newProperty(kind: NewPropertyKind): JsonSchemaProperty {\n switch (kind) {\n case \"object\":\n return { type: \"object\", properties: {} };\n case \"array\":\n return { type: \"array\", items: { type: \"object\", properties: {} } };\n case \"oneOf\":\n // Start with two empty branches, each tagged by a `kind` discriminator.\n return {\n type: \"object\",\n discriminator: { propertyName: \"kind\" },\n oneOf: [newBranch(\"option_1\"), newBranch(\"option_2\")],\n };\n default:\n return { type: \"string\" };\n }\n}\n\n/** A default oneOf branch: an object with a const-valued `kind` discriminator. */\nexport function newBranch(value: string): JsonSchemaProperty {\n return {\n title: value,\n properties: { kind: { const: value } },\n };\n}\n\n// Resolve the properties container + order-owner for a parent path. Root when\n// path is empty. Returns the mutable container inside a cloned schema.\nfunction resolveContainer(\n schema: JsonSchema,\n parentPath: PropertyPath,\n): {\n properties: Record<string, JsonSchemaProperty>;\n getOrder: () => string[] | undefined;\n setOrder: (order: string[] | undefined) => void;\n getRequired: () => string[] | undefined;\n setRequired: (req: string[] | undefined) => void;\n} | null {\n if (parentPath.length === 0) {\n return {\n properties: schema.properties,\n getOrder: () => schema[\"x-ui-order\"],\n setOrder: (o) => {\n if (o) schema[\"x-ui-order\"] = o;\n else delete schema[\"x-ui-order\"];\n },\n getRequired: () => schema.required,\n setRequired: (r) => {\n if (r && r.length) schema.required = r;\n else delete schema.required;\n },\n };\n }\n const owner = getProperty(schema, parentPath);\n if (!owner) return null;\n // For arrays, order/required/properties live on items; otherwise on the\n // owner (objects and oneOf branches). A branch may not yet have a\n // properties map -- create one so children can be added.\n if (owner.oneOf) return null; // cannot add a bare property to a oneOf itself\n const target = owner.type === \"array\" ? owner.items : owner;\n if (!target) return null; // malformed array (no items)\n if (!target.properties) target.properties = {};\n const properties = target.properties;\n return {\n properties,\n getOrder: () => target[\"x-ui-order\"],\n setOrder: (o) => {\n if (o) target[\"x-ui-order\"] = o;\n else delete target[\"x-ui-order\"];\n },\n getRequired: () => target.required,\n setRequired: (r) => {\n if (r && r.length) target.required = r;\n else delete target.required;\n },\n };\n}\n\n// Unique key like \"property\", \"property_2\" within a container.\nfunction uniqueKey(\n base: string,\n properties: Record<string, JsonSchemaProperty>,\n): string {\n if (!(base in properties)) return base;\n let i = 2;\n while (`${base}_${i}` in properties) i++;\n return `${base}_${i}`;\n}\n\n/** Add a property under a parent path (root when empty). Returns the new model. */\nexport function addProperty(\n model: DesignerModel,\n parentPath: PropertyPath,\n kind: NewPropertyKind,\n): { model: DesignerModel; path: PropertyPath } {\n const schema = clone(model.schema);\n const container = resolveContainer(schema, parentPath);\n if (!container) return { model, path: parentPath };\n const key = uniqueKey(\"property\", container.properties);\n container.properties[key] = newProperty(kind);\n const order = container.getOrder();\n if (order) container.setOrder([...order, key]);\n return {\n model: { schema, uiSchema: model.uiSchema },\n path: [...parentPath, propSeg(key)],\n };\n}\n\n// Derive a branch value that is unique among existing branch titles/consts so\n// that the discriminator remains unambiguous after any add/remove sequence.\nfunction uniqueBranchValue(oneOf: JsonSchemaProperty[]): string {\n const existing = new Set(oneOf.map((b) => b.title).filter(Boolean));\n let i = 1;\n while (existing.has(`option_${i}`)) i++;\n return `option_${i}`;\n}\n\n/** Add a branch to the oneOf property at `path`. Returns the new model + branch path. */\nexport function addBranch(\n model: DesignerModel,\n path: PropertyPath,\n): { model: DesignerModel; path: PropertyPath } {\n const schema = clone(model.schema);\n const owner = getProperty(schema, path);\n if (!owner || !owner.oneOf) return { model, path };\n const index = owner.oneOf.length;\n owner.oneOf.push(newBranch(uniqueBranchValue(owner.oneOf)));\n return {\n model: { schema, uiSchema: model.uiSchema },\n path: [...path, branchSeg(index)],\n };\n}\n\n/** Remove the branch at `path` (a branch segment). Returns the new model. */\nexport function removeBranch(\n model: DesignerModel,\n path: PropertyPath,\n): DesignerModel {\n const last = path[path.length - 1];\n if (!last || last.kind !== \"branch\") return model;\n const schema = clone(model.schema);\n const owner = getProperty(schema, path.slice(0, -1));\n if (!owner?.oneOf) return model;\n owner.oneOf.splice(last.index, 1);\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** Move the branch at `path` up (-1) or down (+1) among its siblings. */\nexport function moveBranch(\n model: DesignerModel,\n path: PropertyPath,\n direction: -1 | 1,\n): DesignerModel {\n const last = path[path.length - 1];\n if (!last || last.kind !== \"branch\") return model;\n const schema = clone(model.schema);\n const owner = getProperty(schema, path.slice(0, -1));\n if (!owner?.oneOf) return model;\n const from = last.index;\n const to = from + direction;\n if (to < 0 || to >= owner.oneOf.length) return model;\n const [moved] = owner.oneOf.splice(from, 1);\n owner.oneOf.splice(to, 0, moved);\n return { schema, uiSchema: model.uiSchema };\n}\n\n// ---- Conditionals (if/then/else authored as allOf members) ----------------\n\n/**\n * A seed conditional member: an empty `if` (no field yet) plus an empty `then`.\n * The condition is filled in by setCondition; `then` fields are added like any\n * object's properties.\n */\nexport function newCondition(): JsonSchemaProperty {\n return { if: { properties: {} }, then: { properties: {} } };\n}\n\n/**\n * Add a conditional (if/then/else) to the object at `objectPath` (root when\n * empty), appended to the given combinator array (`allOf` = AND, default;\n * `anyOf` = OR). Returns the new model + the condition path.\n */\nexport function addConditional(\n model: DesignerModel,\n objectPath: PropertyPath,\n combinator: ConditionCombinator = \"allOf\",\n): { model: DesignerModel; path: PropertyPath } {\n const schema = clone(model.schema);\n const owner = conditionalOwner(schema, objectPath);\n if (!owner) return { model, path: objectPath };\n if (!Array.isArray(owner[combinator])) owner[combinator] = [];\n const arr = owner[combinator]!;\n const index = arr.length;\n arr.push(newCondition());\n return {\n model: { schema, uiSchema: model.uiSchema },\n path: [...objectPath, condSeg(index, combinator)],\n };\n}\n\n// The schema object that owns an `allOf` for a given object path: the root\n// schema (path []) or an object property. Arrays/oneOf/scalars cannot host a\n// conditional directly.\nfunction conditionalOwner(\n schema: JsonSchema,\n objectPath: PropertyPath,\n): JsonSchema | JsonSchemaProperty | null {\n if (objectPath.length === 0) return schema;\n const owner = getProperty(schema, objectPath);\n if (!owner) return null;\n const objectLike = owner.type === \"object\" || owner.type === undefined;\n if (!objectLike || owner.oneOf) return null;\n return owner;\n}\n\n/** Remove the conditional at `path` (a condition segment). Returns the new model. */\nexport function removeConditional(\n model: DesignerModel,\n path: PropertyPath,\n): DesignerModel {\n const last = path[path.length - 1];\n if (!last || last.kind !== \"condition\") return model;\n const schema = clone(model.schema);\n const owner = conditionalOwner(schema, path.slice(0, -1));\n const arr = owner?.[last.combinator];\n if (!arr) return model;\n arr.splice(last.index, 1);\n if (arr.length === 0) delete owner![last.combinator];\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** Write the `if` of the conditional at `path` from a condition triple. */\nexport function setCondition(\n model: DesignerModel,\n path: PropertyPath,\n ifSchema: JsonSchemaProperty,\n): DesignerModel {\n const last = path[path.length - 1];\n if (!last || last.kind !== \"condition\") return model;\n const schema = clone(model.schema);\n const member = getProperty(schema, path);\n if (!member) return model;\n member.if = ifSchema;\n if (!member.then) member.then = { properties: {} };\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** Add an empty `else` branch to the conditional at `path`. */\nexport function addElse(\n model: DesignerModel,\n path: PropertyPath,\n): DesignerModel {\n const last = path[path.length - 1];\n if (!last || last.kind !== \"condition\") return model;\n const schema = clone(model.schema);\n const member = getProperty(schema, path);\n if (!member || member.else) return model;\n member.else = { properties: {} };\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** Remove the `else` branch from the conditional at `path`. */\nexport function removeElse(\n model: DesignerModel,\n path: PropertyPath,\n): DesignerModel {\n const last = path[path.length - 1];\n if (!last || last.kind !== \"condition\") return model;\n const schema = clone(model.schema);\n const member = getProperty(schema, path);\n if (!member || !member.else) return model;\n delete member.else;\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** The other combinator. */\nfunction otherCombinator(c: ConditionCombinator): ConditionCombinator {\n return c === \"allOf\" ? \"anyOf\" : \"allOf\";\n}\n\n/**\n * Switch the combinator (AND/OR) for the conditionals of the object at\n * `objectPath`. Migrates every conditional member from the current combinator\n * array to `next`. Non-conditional members (structural allOf/anyOf entries)\n * stay put. No-op when already using `next` or when there are no conditionals.\n */\nexport function setConditionalBehavior(\n model: DesignerModel,\n objectPath: PropertyPath,\n next: ConditionCombinator,\n): DesignerModel {\n const schema = clone(model.schema);\n const owner = conditionalOwner(schema, objectPath);\n if (!owner) return model;\n const from = otherCombinator(next);\n const source = owner[from];\n if (!Array.isArray(source)) return model;\n\n const conditionals = source.filter((m) => !!m.if);\n if (conditionals.length === 0) return model;\n const rest = source.filter((m) => !m.if);\n\n // Move conditionals into the target array; leave structural members behind.\n if (rest.length > 0) owner[from] = rest;\n else delete owner[from];\n owner[next] = [...(owner[next] ?? []), ...conditionals];\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** Delete the property at path. Returns the new model. */\nexport function deleteProperty(\n model: DesignerModel,\n path: PropertyPath,\n): DesignerModel {\n if (path.length === 0) return model;\n const schema = clone(model.schema);\n const parentPath = path.slice(0, -1);\n const key = segKey(path[path.length - 1]);\n if (key === undefined) return model;\n const container = resolveContainer(schema, parentPath);\n if (!container || !(key in container.properties)) return model;\n delete container.properties[key];\n const order = container.getOrder();\n if (order) container.setOrder(order.filter((k) => k !== key));\n const required = container.getRequired();\n if (required) container.setRequired(required.filter((k) => k !== key));\n\n // Drop the uiSchema entry only for top-level properties (uiSchema is keyed by\n // top-level property name; nested UI lives under x-ui-fields, handled elsewhere).\n let uiSchema = model.uiSchema;\n if (parentPath.length === 0 && key in uiSchema) {\n uiSchema = { ...uiSchema };\n delete uiSchema[key];\n }\n return { schema, uiSchema };\n}\n\n// Rewrite one key to another within a properties map, preserving position.\nfunction renameKeyInPlace(\n properties: Record<string, JsonSchemaProperty>,\n prevKey: string,\n nextKey: string,\n): void {\n const rebuilt: Record<string, JsonSchemaProperty> = {};\n for (const [k, v] of Object.entries(properties)) {\n rebuilt[k === prevKey ? nextKey : k] = v;\n }\n for (const k of Object.keys(properties)) delete properties[k];\n Object.assign(properties, rebuilt);\n}\n\n// Move a top-level uiSchema entry to a new key (returns a new map if changed).\nfunction renameUiEntry(\n uiSchema: UiSchemaMap,\n parentPath: PropertyPath,\n prevKey: string,\n nextKey: string,\n): UiSchemaMap {\n if (parentPath.length !== 0 || !(prevKey in uiSchema)) return uiSchema;\n const next = { ...uiSchema };\n next[nextKey] = next[prevKey];\n delete next[prevKey];\n return next;\n}\n\n// Update order and required arrays when a key is renamed in a container.\nfunction updateContainerRefs(\n container: ReturnType<typeof resolveContainer> & object,\n prevKey: string,\n nextKey: string,\n): void {\n const rename = (k: string) => (k === prevKey ? nextKey : k);\n const order = container.getOrder();\n if (order) container.setOrder(order.map(rename));\n const required = container.getRequired();\n if (required) container.setRequired(required.map(rename));\n}\n\n/** Rename the property at path. Rewrites key, order, required, and uiSchema. */\nexport function renameProperty(\n model: DesignerModel,\n path: PropertyPath,\n nextKey: string,\n): { model: DesignerModel; path: PropertyPath } {\n if (path.length === 0) return { model, path };\n const parentPath = path.slice(0, -1);\n const prevKey = segKey(path[path.length - 1]);\n if (prevKey === undefined) return { model, path };\n if (nextKey === prevKey || !nextKey || isReservedKey(nextKey))\n return { model, path };\n\n const schema = clone(model.schema);\n const container = resolveContainer(schema, parentPath);\n if (!container || !(prevKey in container.properties)) return { model, path };\n if (nextKey in container.properties) return { model, path }; // collision: no-op\n\n renameKeyInPlace(container.properties, prevKey, nextKey);\n updateContainerRefs(container, prevKey, nextKey);\n const uiSchema = renameUiEntry(model.uiSchema, parentPath, prevKey, nextKey);\n return {\n model: { schema, uiSchema },\n path: [...parentPath, propSeg(nextKey)],\n };\n}\n\n/** Move the property at path up (-1) or down (+1) among its siblings. */\nexport function moveProperty(\n model: DesignerModel,\n path: PropertyPath,\n direction: -1 | 1,\n): DesignerModel {\n if (path.length === 0) return model;\n const schema = clone(model.schema);\n const parentPath = path.slice(0, -1);\n const key = segKey(path[path.length - 1]);\n if (key === undefined) return model;\n const container = resolveContainer(schema, parentPath);\n if (!container) return model;\n\n const keys = Object.keys(container.properties);\n const order = container.getOrder() ?? keys;\n // Normalize order to include every key.\n const full = [...order.filter((k) => keys.includes(k))];\n for (const k of keys) if (!full.includes(k)) full.push(k);\n\n const idx = full.indexOf(key);\n const swap = idx + direction;\n if (idx < 0 || swap < 0 || swap >= full.length) return model;\n [full[idx], full[swap]] = [full[swap], full[idx]];\n container.setOrder(full);\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** Toggle whether the property at path is required among its siblings. */\nexport function setRequired(\n model: DesignerModel,\n path: PropertyPath,\n required: boolean,\n): DesignerModel {\n if (path.length === 0) return model;\n const schema = clone(model.schema);\n const parentPath = path.slice(0, -1);\n const key = segKey(path[path.length - 1]);\n if (key === undefined) return model;\n const container = resolveContainer(schema, parentPath);\n if (!container) return model;\n const current = new Set(container.getRequired() ?? []);\n if (required) current.add(key);\n else current.delete(key);\n container.setRequired([...current]);\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** Replace the property definition at path (merges the given partial). */\nexport function updateProperty(\n model: DesignerModel,\n path: PropertyPath,\n patch: Partial<JsonSchemaProperty>,\n): DesignerModel {\n if (path.length === 0) return model;\n const schema = clone(model.schema);\n const prop = getProperty(schema, path);\n if (!prop) return model;\n // Apply the patch: set defined values, delete keys whose patch value is\n // undefined so they don't persist as ghost own-keys on the schema object.\n for (const [k, v] of Object.entries(patch)) {\n if (v === undefined) delete (prop as Record<string, unknown>)[k];\n else (prop as Record<string, unknown>)[k] = v;\n }\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** The kind a property can be changed to: a JSON Schema type, or a \"oneOf\" union. */\nexport type PropertyTypeChoice =\n | NonNullable<JsonSchemaProperty[\"type\"]>\n | \"oneOf\";\n\n// The current kind choice of a property (for no-op detection).\nfunction currentTypeChoice(prop: JsonSchemaProperty): PropertyTypeChoice {\n return prop.oneOf ? \"oneOf\" : (prop.type ?? \"string\");\n}\n\n/**\n * Change the kind of the property at path, reshaping structural keys: object\n * adds an empty `properties`; array adds `items`; oneOf adds branches + a\n * discriminator; leaving a kind strips its keys. Type-specific validation keys\n * that no longer apply are dropped.\n */\nexport function changePropertyType(\n model: DesignerModel,\n path: PropertyPath,\n next: PropertyTypeChoice,\n): DesignerModel {\n if (path.length === 0 || !next) return model;\n const schema = clone(model.schema);\n const prop = getProperty(schema, path);\n // A $ref node has no concrete type; always allow retyping it (which clears\n // the $ref below). Otherwise skip when the choice is unchanged.\n if (!prop || (!prop.$ref && currentTypeChoice(prop) === next)) return model;\n\n // Strip all structural + type-specific + logic keys from the previous kind.\n delete prop.properties;\n delete prop.items;\n delete prop.enum;\n delete prop.oneOf;\n delete prop.discriminator;\n delete prop.const;\n // A concrete type replaces any $ref: the property is no longer a reference.\n delete prop.$ref;\n // Conditionals (allOf if/then/else) belong to an object; drop them when the\n // owning property is no longer an object.\n if (next !== \"object\") {\n delete prop.allOf;\n delete prop.anyOf;\n }\n delete prop.minLength;\n delete prop.maxLength;\n delete prop.pattern;\n delete prop.format;\n delete prop.minimum;\n delete prop.maximum;\n delete prop.minItems;\n delete prop.maxItems;\n\n if (next === \"oneOf\") {\n const seed = newProperty(\"oneOf\");\n prop.type = seed.type;\n prop.discriminator = seed.discriminator;\n prop.oneOf = seed.oneOf;\n } else {\n prop.type = next;\n if (next === \"object\") prop.properties = {};\n if (next === \"array\") prop.items = { type: \"string\" };\n }\n return { schema, uiSchema: model.uiSchema };\n}\n\n// The local $ref pointer for a definition name (2020-12 canonical form).\nfunction defPointer(name: string): string {\n return `#/$defs/${name}`;\n}\n\n/**\n * Point the property at path to a definition by name, writing a local `$ref`\n * (`#/$defs/<name>`) and stripping type-specific keys. Turns a plain property\n * into a reference usage. No-op for the root or an unknown target.\n */\nexport function setReference(\n model: DesignerModel,\n path: PropertyPath,\n name: string,\n): DesignerModel {\n if (path.length === 0 || !name) return model;\n const schema = clone(model.schema);\n const prop = getProperty(schema, path);\n if (!prop) return model;\n const defs = schema.$defs ?? schema.definitions;\n if (!defs || !(name in defs)) return model;\n // For an array, the reference applies to its items (\"array of <def>\"); the\n // array keeps its type and cardinality. Otherwise the property itself becomes\n // the reference.\n if (prop.type === \"array\") {\n prop.items = { $ref: defPointer(name) };\n return { schema, uiSchema: model.uiSchema };\n }\n makeReference(prop, name);\n return { schema, uiSchema: model.uiSchema };\n}\n\n// Turn a property into a $ref node: strip structural and type-specific keys,\n// keeping only annotation overrides (title/description/default) that are valid\n// 2020-12 $ref siblings at the referencing site.\nfunction makeReference(prop: JsonSchemaProperty, name: string): void {\n delete prop.properties;\n delete prop.items;\n delete prop.enum;\n delete prop.oneOf;\n delete prop.discriminator;\n delete prop.const;\n delete prop.allOf;\n delete prop.anyOf;\n delete prop.type;\n // Strip type-specific validation so it does not silently constrain the\n // referencing site independently of the definition's own constraints.\n delete prop.minLength;\n delete prop.maxLength;\n delete prop.pattern;\n delete prop.format;\n delete prop.minimum;\n delete prop.maximum;\n delete prop.minItems;\n delete prop.maxItems;\n prop.$ref = defPointer(name);\n}\n\n// Visit every object node in a schema tree, calling visitor on each.\n// The visitor receives the object and the key under which it was reached\n// (undefined for the root); returning true from the visitor skips recursing\n// into the object's children (used to skip already-matched nodes).\nfunction walkSchemaNodes(\n node: unknown,\n visitor: (obj: Record<string, unknown>, key: string | undefined) => void,\n parentKey?: string,\n): void {\n if (Array.isArray(node)) {\n for (const item of node) walkSchemaNodes(item, visitor, parentKey);\n return;\n }\n if (!node || typeof node !== \"object\") return;\n const obj = node as Record<string, unknown>;\n visitor(obj, parentKey);\n for (const key of Object.keys(obj)) {\n walkSchemaNodes(obj[key], visitor, key);\n }\n}\n\n/** Recursively rewrite every local `$ref` targeting `from` to point at `to`. */\nfunction rewriteRefs(node: unknown, from: string, to: string): void {\n walkSchemaNodes(node, (obj, key) => {\n // Only rewrite when reached via a non-$ref key, so we are visiting the\n // containing object (not a string value that happens to equal `from`).\n if (key !== \"$ref\" && obj.$ref === from) obj.$ref = to;\n });\n}\n\n// Count local $ref usages of a definition across the whole schema.\nfunction countRefUsages(schema: JsonSchema, name: string): number {\n let count = 0;\n const pointers = new Set([`#/$defs/${name}`, `#/definitions/${name}`]);\n walkSchemaNodes(schema, (obj) => {\n if (typeof obj.$ref === \"string\" && pointers.has(obj.$ref)) count++;\n });\n return count;\n}\n\n/**\n * Add a new empty object definition under `$defs`. Returns the new model and the\n * path to the created definition for selection.\n */\nexport function addDefinition(\n model: DesignerModel,\n name?: string,\n): { model: DesignerModel; path: PropertyPath } {\n const schema = clone(model.schema);\n if (!schema.$defs) schema.$defs = {};\n const key = uniqueKey(name ?? \"Definition\", schema.$defs);\n schema.$defs[key] = { type: \"object\", properties: {} };\n return {\n model: { schema, uiSchema: model.uiSchema },\n path: [defSeg(key)],\n };\n}\n\n/**\n * Rename a `$defs` entry, preserving order, and rewrite every local `$ref` that\n * targets it (both `#/$defs/` and `#/definitions/` forms) to the new pointer.\n * No-op on collision, reserved, or empty names.\n */\nexport function renameDefinition(\n model: DesignerModel,\n oldName: string,\n newName: string,\n): { model: DesignerModel; path: PropertyPath } {\n const path: PropertyPath = [defSeg(oldName)];\n if (!newName || newName === oldName || isReservedKey(newName))\n return { model, path };\n const schema = clone(model.schema);\n // Support both 2020-12 $defs and Draft-7 definitions; author to the map\n // that already contains the entry.\n const defs = schema.$defs ?? schema.definitions;\n if (!defs || !(oldName in defs) || newName in defs) return { model, path };\n\n renameKeyInPlace(defs, oldName, newName);\n rewriteRefs(schema, `#/$defs/${oldName}`, `#/$defs/${newName}`);\n rewriteRefs(schema, `#/definitions/${oldName}`, `#/$defs/${newName}`);\n return {\n model: { schema, uiSchema: model.uiSchema },\n path: [defSeg(newName)],\n };\n}\n\n/**\n * Remove a `$defs` entry. Blocked (no-op) while any local `$ref` still targets\n * it; the UI surfaces the usage count. Drops the `$defs` map when it empties.\n */\nexport function removeDefinition(\n model: DesignerModel,\n name: string,\n): DesignerModel {\n const schema = clone(model.schema);\n // Support both 2020-12 $defs and Draft-7 definitions.\n const inDefs = schema.$defs && name in schema.$defs;\n const inDefs7 = schema.definitions && name in schema.definitions;\n if (!inDefs && !inDefs7) return model;\n if (countRefUsages(schema, name) > 0) return model; // in use: keep it\n if (inDefs) {\n delete schema.$defs![name];\n if (Object.keys(schema.$defs!).length === 0) delete schema.$defs;\n } else {\n delete schema.definitions![name];\n if (Object.keys(schema.definitions!).length === 0)\n delete schema.definitions;\n }\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** Whether a definition is referenced anywhere (for UI delete-guard messaging). */\nexport function definitionUsageCount(schema: JsonSchema, name: string): number {\n return countRefUsages(schema, name);\n}\n\n/** One enum choice: a value and an optional display label. */\nexport interface EnumChoice {\n value: string;\n label?: string;\n}\n\n/**\n * Set the enum choices for the property at path. Values write to `property.enum`;\n * labels write to the property's `x-ui-options.enumNames` in the uiSchema (only\n * for top-level properties, where the uiSchema map is keyed). An empty list clears\n * both. Deduplicates and drops empty values.\n */\n// Normalize choices: trim, drop empties, dedupe by value (first wins).\nfunction normalizeChoices(choices: EnumChoice[]): EnumChoice[] {\n const seen = new Set<string>();\n const clean: EnumChoice[] = [];\n for (const c of choices) {\n const value = c.value.trim();\n if (!value || seen.has(value)) continue;\n seen.add(value);\n clean.push({ value, label: c.label?.trim() || undefined });\n }\n return clean;\n}\n\n// Update a UISchema entry's x-ui-options.enumNames from labelled choices,\n// returning the new entry (or undefined if empty).\nfunction withEnumNames(\n entry: UISchema | undefined,\n choices: EnumChoice[],\n): UISchema | undefined {\n const enumNames: Record<string, string> = {};\n for (const c of choices) if (c.label) enumNames[c.value] = c.label;\n\n const next: UISchema = { ...(entry ?? {}) };\n const options = {\n ...((next[\"x-ui-options\"] as Record<string, unknown>) ?? {}),\n };\n if (Object.keys(enumNames).length) options.enumNames = enumNames;\n else delete options.enumNames;\n if (Object.keys(options).length) next[\"x-ui-options\"] = options;\n else delete next[\"x-ui-options\"];\n\n return Object.keys(next).length ? next : undefined;\n}\n\nexport function setEnum(\n model: DesignerModel,\n path: PropertyPath,\n choices: EnumChoice[],\n): DesignerModel {\n if (path.length === 0) return model;\n const schema = clone(model.schema);\n const prop = getProperty(schema, path);\n if (!prop) return model;\n\n const clean = normalizeChoices(choices);\n if (clean.length === 0) delete prop.enum;\n else prop.enum = clean.map((c) => c.value);\n\n // enumNames lives in the property's uiSchema entry (at any nesting depth).\n const nextEntry = withEnumNames(\n getUiEntryAtPath(model.uiSchema, path),\n clean,\n );\n const uiSchema = setEntryIn(model.uiSchema, propKeys(path), nextEntry);\n\n return { schema, uiSchema };\n}\n\n/** Read the current enum choices for a property + its uiSchema entry. */\nexport function readEnumChoices(\n prop: JsonSchemaProperty,\n uiEntry: UISchema | undefined,\n): EnumChoice[] {\n if (!Array.isArray(prop.enum)) return [];\n const enumNames =\n (uiEntry?.[\"x-ui-options\"] as { enumNames?: Record<string, string> })\n ?.enumNames ?? {};\n return prop.enum.map((v) => {\n const value = String(v);\n return { value, label: enumNames[value] };\n });\n}\n\n/** Table presentation hints for a property (embedded in the schema). */\nexport interface TableHints {\n cell?: string;\n cellOptions?: Record<string, unknown>;\n column?: NonNullable<JsonSchemaProperty[\"x-ui-column\"]>;\n}\n\n/**\n * Set (or clear) a property's table hints: x-ui-cell, x-ui-cell-options, and\n * x-ui-column. These live embedded on the property (EntityTable reads them\n * there). Empty values clear the corresponding key.\n */\nexport function setTableHints(\n model: DesignerModel,\n path: PropertyPath,\n hints: TableHints,\n): DesignerModel {\n if (path.length === 0) return model;\n const schema = clone(model.schema);\n const prop = getProperty(schema, path);\n if (!prop) return model;\n\n if (hints.cell) prop[\"x-ui-cell\"] = hints.cell;\n else delete prop[\"x-ui-cell\"];\n\n if (hints.cellOptions && Object.keys(hints.cellOptions).length > 0) {\n prop[\"x-ui-cell-options\"] = hints.cellOptions;\n } else {\n delete prop[\"x-ui-cell-options\"];\n }\n\n if (hints.column && Object.keys(hints.column).length > 0) {\n prop[\"x-ui-column\"] = hints.column;\n } else {\n delete prop[\"x-ui-column\"];\n }\n\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** Read a property's current table hints. */\nexport function readTableHints(prop: JsonSchemaProperty): TableHints {\n return {\n cell: typeof prop[\"x-ui-cell\"] === \"string\" ? prop[\"x-ui-cell\"] : undefined,\n cellOptions: prop[\"x-ui-cell-options\"] as\n | Record<string, unknown>\n | undefined,\n column: prop[\"x-ui-column\"],\n };\n}\n\n/** Set (or clear) the top-level uiSchema entry for a property name. */\n// -- Path-aware uiSchema navigation --------------------------------------\n//\n// The uiSchema map is keyed by top-level property name. A nested property's\n// UISchema entry lives under its ancestor's `x-ui-fields` sub-map: the first\n// path segment indexes the top-level map, each subsequent segment indexes\n// through `x-ui-fields`. This mirrors how ObjectWidget/ArrayWidget read it.\n\ntype UiFieldsMap = Record<string, UISchema>;\n\n/** Read the UISchema entry for a property path, or undefined. */\nexport function getUiEntryAtPath(\n uiSchema: UiSchemaMap,\n path: PropertyPath,\n): UISchema | undefined {\n const keys = propKeys(path);\n if (keys.length === 0) return undefined;\n let entry: UISchema | undefined = uiSchema[keys[0]];\n for (let i = 1; i < keys.length && entry; i++) {\n const fields = entry[\"x-ui-fields\"] as UiFieldsMap | undefined;\n entry = fields?.[keys[i]];\n }\n return entry;\n}\n\n// Recursively set `entry` at `keys` within a fields map, pruning empties on the\n// way back up (empty entry -> removed; empty x-ui-fields -> removed).\nfunction setEntryIn(\n map: UiFieldsMap,\n keys: string[],\n entry: UISchema | undefined,\n): UiFieldsMap {\n const [head, ...rest] = keys;\n const next: UiFieldsMap = { ...map };\n\n if (rest.length === 0) {\n if (entry && Object.keys(entry).length > 0) next[head] = entry;\n else delete next[head];\n return next;\n }\n\n const current: UISchema = { ...(next[head] ?? {}) };\n const childFields = (current[\"x-ui-fields\"] as UiFieldsMap | undefined) ?? {};\n const updatedFields = setEntryIn(childFields, rest, entry);\n\n if (Object.keys(updatedFields).length > 0) {\n current[\"x-ui-fields\"] = updatedFields;\n } else {\n delete current[\"x-ui-fields\"];\n }\n\n if (Object.keys(current).length > 0) next[head] = current;\n else delete next[head];\n return next;\n}\n\n/** Set (or clear) the UISchema entry at a property path (any nesting depth). */\nexport function setUiEntry(\n model: DesignerModel,\n path: PropertyPath,\n entry: UISchema | undefined,\n): DesignerModel {\n if (path.length === 0) return model;\n const uiSchema = setEntryIn(model.uiSchema, propKeys(path), entry);\n return { schema: model.schema, uiSchema };\n}\n\n/**\n * Set (or clear) the x-ui-layout of an object/array property at path. Object\n * layout lives on the property; array layout lives on `items`.\n */\nexport function setPropertyLayout(\n model: DesignerModel,\n path: PropertyPath,\n layout: UILayoutConfig | undefined,\n): DesignerModel {\n if (path.length === 0) return model;\n const schema = clone(model.schema);\n const prop = getProperty(schema, path);\n if (!prop) return model;\n const target = prop.type === \"array\" ? prop.items : prop;\n if (!target) return model;\n if (layout) target[\"x-ui-layout\"] = layout;\n else delete target[\"x-ui-layout\"];\n return { schema, uiSchema: model.uiSchema };\n}\n\n// The uiSchema map is keyed by property name (UISchema values) but also carries\n// special top-level keys (x-ui-layout, x-ui-globalOptions) whose values are not\n// UISchema. Read/write them through this looser view.\ntype RootUiSchema = UiSchemaMap & {\n \"x-ui-layout\"?: UILayoutConfig;\n \"x-ui-globalOptions\"?: UISchemaOptions;\n};\n\n/** Set (or clear) the root form layout (uiSchema[\"x-ui-layout\"]). */\nexport function setRootLayout(\n model: DesignerModel,\n layout: UILayoutConfig | undefined,\n): DesignerModel {\n const uiSchema = { ...model.uiSchema } as RootUiSchema;\n if (layout) uiSchema[\"x-ui-layout\"] = layout;\n else delete uiSchema[\"x-ui-layout\"];\n return { schema: model.schema, uiSchema };\n}\n\n/**\n * Set (or clear) the root layout rows (uiSchema[\"x-ui-layout\"].rows),\n * preserving other x-ui-layout keys. Clearing rows to empty removes the key;\n * if x-ui-layout then has no keys, it is removed entirely.\n */\nexport function setRootLayoutRows(\n model: DesignerModel,\n rows: UILayoutConfig[\"rows\"],\n): DesignerModel {\n const uiSchema = { ...model.uiSchema } as RootUiSchema;\n const layout: UILayoutConfig = { ...(uiSchema[\"x-ui-layout\"] ?? {}) };\n if (rows && rows.length > 0) layout.rows = rows;\n else delete layout.rows;\n if (Object.keys(layout).length > 0) uiSchema[\"x-ui-layout\"] = layout;\n else delete uiSchema[\"x-ui-layout\"];\n return { schema: model.schema, uiSchema };\n}\n\n/**\n * Set the layout rows for a scope: the root form (path []) or an object/array\n * container (its property path). Root rows live in uiSchema[\"x-ui-layout\"];\n * a container's rows live on the property's x-ui-layout (array -> items).\n * Preserves other x-ui-layout keys.\n */\nexport function setScopedLayoutRows(\n model: DesignerModel,\n scopePath: PropertyPath,\n rows: UILayoutConfig[\"rows\"],\n): DesignerModel {\n if (scopePath.length === 0) return setRootLayoutRows(model, rows);\n\n const schema = clone(model.schema);\n const prop = getProperty(schema, scopePath);\n if (!prop) return model;\n const target = prop.type === \"array\" ? prop.items : prop;\n if (!target) return model;\n\n const layout: UILayoutConfig = { ...(target[\"x-ui-layout\"] ?? {}) };\n if (rows && rows.length > 0) layout.rows = rows;\n else delete layout.rows;\n if (Object.keys(layout).length > 0) target[\"x-ui-layout\"] = layout;\n else delete target[\"x-ui-layout\"];\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** Read the current x-ui-layout for a scope (root or a container property). */\nexport function getScopedLayout(\n schema: JsonSchema,\n uiSchema: UiSchemaMap,\n scopePath: PropertyPath,\n): UILayoutConfig | undefined {\n if (scopePath.length === 0) {\n return (uiSchema as RootUiSchema)[\"x-ui-layout\"];\n }\n const prop = getProperty(schema, scopePath);\n const target = prop?.type === \"array\" ? prop.items : prop;\n return target?.[\"x-ui-layout\"];\n}\n\n/**\n * Merge scalar layout options (direction/gap/labels/compact) into a scope's\n * x-ui-layout, preserving rows and other keys. Undefined values clear the key.\n */\nexport function setScopedLayoutOptions(\n model: DesignerModel,\n scopePath: PropertyPath,\n options: Pick<UILayoutConfig, \"direction\" | \"gap\" | \"labels\" | \"compact\">,\n): DesignerModel {\n const current =\n getScopedLayout(model.schema, model.uiSchema, scopePath) ?? {};\n const merged: UILayoutConfig = { ...current };\n for (const key of [\"direction\", \"gap\", \"labels\", \"compact\"] as const) {\n const v = options[key];\n if (v === undefined || (typeof v === \"number\" && Number.isNaN(v)))\n delete merged[key];\n else (merged as Record<string, unknown>)[key] = v;\n }\n const layout = Object.keys(merged).length > 0 ? merged : undefined;\n if (scopePath.length === 0) return setRootLayout(model, layout);\n return setPropertyLayout(model, scopePath, layout);\n}\n\n/**\n * Set the group definitions for a scope, preserving other x-ui-layout keys.\n * Passing an empty list (or undefined) clears groups, returning the scope to the\n * flat row layout. Root groups live in uiSchema[\"x-ui-layout\"]; a container's\n * live on the property's x-ui-layout (array -> items).\n *\n * Groups and flat rows are mutually exclusive (the renderer gives groups\n * precedence), so setting groups drops `rows` -- otherwise the orphaned list\n * would be invisible in both the form and the designer.\n */\nexport function setScopedLayoutGroups(\n model: DesignerModel,\n scopePath: PropertyPath,\n groups: UILayoutConfig[\"groups\"],\n): DesignerModel {\n const current =\n getScopedLayout(model.schema, model.uiSchema, scopePath) ?? {};\n const merged: UILayoutConfig = { ...current };\n if (groups && groups.length > 0) {\n merged.groups = groups;\n delete merged.rows;\n } else {\n delete merged.groups;\n }\n const layout = Object.keys(merged).length > 0 ? merged : undefined;\n if (scopePath.length === 0) return setRootLayout(model, layout);\n return setPropertyLayout(model, scopePath, layout);\n}\n\n/** The groups currently defined for a scope. */\nfunction groupsOf(\n model: DesignerModel,\n scopePath: PropertyPath,\n): UILayoutGroupConfig[] {\n return getScopedLayout(model.schema, model.uiSchema, scopePath)?.groups ?? [];\n}\n\n/** Append an empty group. The label defaults to the next ordinal (\"Group 3\"). */\nexport function addLayoutGroup(\n model: DesignerModel,\n scopePath: PropertyPath,\n label?: string,\n): DesignerModel {\n const groups = groupsOf(model, scopePath);\n const next = { label: label ?? `Group ${groups.length + 1}`, rows: [] };\n return setScopedLayoutGroups(model, scopePath, [...groups, next]);\n}\n\n/** Rename one group. No-op for an unknown index or a blank label. */\nexport function renameLayoutGroup(\n model: DesignerModel,\n scopePath: PropertyPath,\n groupIndex: number,\n label: string,\n): DesignerModel {\n const groups = groupsOf(model, scopePath);\n if (!groups[groupIndex] || !label.trim()) return model;\n return setScopedLayoutGroups(\n model,\n scopePath,\n groups.map((group, i) => (i === groupIndex ? { ...group, label } : group)),\n );\n}\n\n/**\n * Place a property into one group's row, removing it from wherever it currently\n * sits across *all* groups. Passing a null target returns it to the pool.\n *\n * Needed because each group owns its own rows: without a cross-group operation a\n * field could only be moved between groups by visiting its old group first.\n */\nexport function placeFieldInGroup(\n model: DesignerModel,\n scopePath: PropertyPath,\n key: string,\n target: { groupIndex: number; rowIndex: number } | null,\n): DesignerModel {\n const groups = groupsOf(model, scopePath);\n if (!key || groups.length === 0) return model;\n const stripped = groups.map((group) => ({\n ...group,\n rows: group.rows.map((row) => ({\n ...row,\n fields: row.fields.filter((f) => f !== key),\n })),\n }));\n if (!target) return setScopedLayoutGroups(model, scopePath, stripped);\n\n const { groupIndex, rowIndex } = target;\n const row = stripped[groupIndex]?.rows[rowIndex];\n if (!row) return setScopedLayoutGroups(model, scopePath, stripped);\n stripped[groupIndex].rows = stripped[groupIndex].rows.map((r, i) =>\n i === rowIndex ? { ...r, fields: [...r.fields, key] } : r,\n );\n return setScopedLayoutGroups(model, scopePath, stripped);\n}\n\n/** Move one group left (-1) or right (+1). No-op at the ends. */\nexport function moveLayoutGroup(\n model: DesignerModel,\n scopePath: PropertyPath,\n groupIndex: number,\n direction: -1 | 1,\n): DesignerModel {\n const groups = groupsOf(model, scopePath);\n const target = groupIndex + direction;\n if (!groups[groupIndex] || target < 0 || target >= groups.length)\n return model;\n const next = [...groups];\n [next[groupIndex], next[target]] = [next[target], next[groupIndex]];\n return setScopedLayoutGroups(model, scopePath, next);\n}\n\n/**\n * Set (or clear) a group's show/hide rule. Passing undefined makes the group\n * unconditional.\n */\nexport function setLayoutGroupRule(\n model: DesignerModel,\n scopePath: PropertyPath,\n groupIndex: number,\n rule: UILayoutGroupConfig[\"rule\"],\n): DesignerModel {\n const groups = groupsOf(model, scopePath);\n if (!groups[groupIndex]) return model;\n const next = groups.map((group, i) => {\n if (i !== groupIndex) return group;\n const { rule: _drop, ...rest } = group;\n return rule ? { ...rest, rule } : rest;\n });\n return setScopedLayoutGroups(model, scopePath, next);\n}\n\n/**\n * Set the group presentation for a scope (\"groups\", \"stepper\", or a custom\n * template name). Passing undefined restores the default group presentation.\n */\nexport function setScopedLayoutVariant(\n model: DesignerModel,\n scopePath: PropertyPath,\n variant: UILayoutConfig[\"variant\"],\n): DesignerModel {\n const current =\n getScopedLayout(model.schema, model.uiSchema, scopePath) ?? {};\n const merged: UILayoutConfig = { ...current };\n if (variant && variant !== \"groups\") merged.variant = variant;\n else delete merged.variant;\n const layout = Object.keys(merged).length > 0 ? merged : undefined;\n if (scopePath.length === 0) return setRootLayout(model, layout);\n return setPropertyLayout(model, scopePath, layout);\n}\n\n/**\n * Remove one group. Its rows are not discarded: removing the last remaining group\n * flattens them back into the scope's flat row layout, so a single click can\n * never destroy every field placement.\n */\nexport function removeLayoutGroup(\n model: DesignerModel,\n scopePath: PropertyPath,\n groupIndex: number,\n): DesignerModel {\n const groups = groupsOf(model, scopePath);\n if (!groups[groupIndex]) return model;\n const remaining = groups.filter((_, i) => i !== groupIndex);\n if (remaining.length > 0) {\n return setScopedLayoutGroups(model, scopePath, remaining);\n }\n const cleared = setScopedLayoutGroups(model, scopePath, []);\n return setScopedLayoutRows(cleared, scopePath, groups[groupIndex].rows);\n}\n\n/** Replace the rows of one group in a scope. No-op for an unknown group index. */\nexport function setScopedGroupRows(\n model: DesignerModel,\n scopePath: PropertyPath,\n groupIndex: number,\n rows: UILayoutRowConfig[],\n): DesignerModel {\n const groups = getScopedLayout(\n model.schema,\n model.uiSchema,\n scopePath,\n )?.groups;\n if (!groups?.[groupIndex]) return model;\n const next = groups.map((group, i) =>\n i === groupIndex ? { ...group, rows } : group,\n );\n return setScopedLayoutGroups(model, scopePath, next);\n}\n\n/**\n * Switch a scope between flat rows and groups, carrying the existing layout over\n * so no field placement is lost: rows become the first group's rows, and leaving\n * group mode flattens every group's rows back into one list.\n */\nexport function setScopedLayoutMode(\n model: DesignerModel,\n scopePath: PropertyPath,\n mode: \"rows\" | \"groups\",\n): DesignerModel {\n const layout = getScopedLayout(model.schema, model.uiSchema, scopePath) ?? {};\n const groups = layout.groups ?? [];\n const rows = layout.rows ?? [];\n if (mode === \"groups\") {\n if (groups.length > 0) return model; // already tabbed\n // setScopedLayoutGroups drops the flat rows, so seed the group with them first.\n return setScopedLayoutGroups(model, scopePath, [\n { label: \"Group 1\", rows },\n ]);\n }\n if (groups.length === 0) return model; // already flat\n // Keep any pre-existing flat rows ahead of the flattened group rows so nothing\n // is overwritten if both somehow coexist (hand-authored uiSchema).\n const flattened = [...rows, ...groups.flatMap((group) => group.rows)];\n const cleared = setScopedLayoutGroups(model, scopePath, []);\n return setScopedLayoutRows(cleared, scopePath, flattened);\n}\n\n/** Set (or clear) the root global options (uiSchema[\"x-ui-globalOptions\"]). */\nexport function setGlobalOptions(\n model: DesignerModel,\n options: UISchemaOptions | undefined,\n): DesignerModel {\n const uiSchema = { ...model.uiSchema } as RootUiSchema;\n if (options) uiSchema[\"x-ui-globalOptions\"] = options;\n else delete uiSchema[\"x-ui-globalOptions\"];\n return { schema: model.schema, uiSchema };\n}\n","/**\n * Type -> compatible form widgets for the inspector's widget dropdown.\n *\n * Mirrors the renderer's resolution vocabulary (sonnet-forms widgetResolver):\n * the dropdown offers widgets that make sense for a property's type, plus an\n * \"Auto\" choice (value null) that clears x-ui-widget and lets the renderer\n * resolve from structure/type. Keep aligned with DEFAULT_WIDGETS.\n */\n\nimport type { JsonSchemaProperty } from \"@petrarca/sonnet-core/schema\";\n\nexport interface WidgetChoice {\n /** x-ui-widget value (lowercase alias), or null for Auto (no override). */\n value: string | null;\n label: string;\n}\n\nconst AUTO: WidgetChoice = { value: null, label: \"Auto (resolve from schema)\" };\n\nconst STRING_WIDGETS: WidgetChoice[] = [\n { value: \"text\", label: \"Text input\" },\n { value: \"textarea\", label: \"Textarea\" },\n { value: \"select\", label: \"Select\" },\n { value: \"date\", label: \"Date\" },\n { value: \"date-time\", label: \"Date & time\" },\n { value: \"time\", label: \"Time\" },\n { value: \"tags\", label: \"Tags\" },\n { value: \"entity-select\", label: \"Entity select\" },\n { value: \"json-editor\", label: \"JSON editor\" },\n];\n\nconst NUMBER_WIDGETS: WidgetChoice[] = [\n { value: \"number\", label: \"Number\" },\n { value: \"select\", label: \"Select\" },\n { value: \"quantity\", label: \"Quantity\" },\n];\n\nconst BOOLEAN_WIDGETS: WidgetChoice[] = [\n { value: \"checkbox\", label: \"Checkbox\" },\n];\n\nconst OBJECT_WIDGETS: WidgetChoice[] = [\n { value: \"object\", label: \"Object (sub-form)\" },\n { value: \"json-editor\", label: \"JSON editor\" },\n];\n\nconst ARRAY_WIDGETS: WidgetChoice[] = [\n { value: \"array\", label: \"Array (repeatable)\" },\n { value: \"select\", label: \"Multi-select\" },\n { value: \"tags\", label: \"Tags\" },\n];\n\nconst NULL_WIDGETS: WidgetChoice[] = [{ value: \"display\", label: \"Display\" }];\n\nconst ONEOF_WIDGETS: WidgetChoice[] = [\n { value: \"one-of\", label: \"One of (variant)\" },\n];\n\n/** Widgets offered for a property, Auto first. */\nexport function compatibleWidgets(prop: JsonSchemaProperty): WidgetChoice[] {\n if (Array.isArray(prop.oneOf) && prop.oneOf.length > 0) {\n return [AUTO, ...ONEOF_WIDGETS];\n }\n switch (prop.type) {\n case \"string\":\n return [AUTO, ...STRING_WIDGETS];\n case \"number\":\n case \"integer\":\n return [AUTO, ...NUMBER_WIDGETS];\n case \"boolean\":\n return [AUTO, ...BOOLEAN_WIDGETS];\n case \"object\":\n return [AUTO, ...OBJECT_WIDGETS];\n case \"array\":\n return [AUTO, ...ARRAY_WIDGETS];\n case \"null\":\n return [AUTO, ...NULL_WIDGETS];\n default:\n return [AUTO];\n }\n}\n","/**\n * Output shaping: merge a separate uiSchema map's form hints into the JSON\n * schema as embedded x-ui-* keys, for consumers that want a single\n * self-contained schema.\n *\n * The designer edits the two artifacts separately (clean data/presentation\n * split); embedding is applied only at the emit boundary when outputMode is\n * \"embedded\". Only top-level form hints are embedded in v1 (x-ui-widget,\n * x-ui-options, x-ui-title, x-ui-placeholder, x-ui-description), matching what\n * uiSchema carries for top-level properties.\n */\n\nimport type {\n JsonSchema,\n JsonSchemaProperty,\n UISchema,\n} from \"@petrarca/sonnet-core/schema\";\n\nconst EMBEDDABLE_KEYS = [\n \"x-ui-widget\",\n \"x-ui-options\",\n \"x-ui-title\",\n \"x-ui-placeholder\",\n \"x-ui-description\",\n] as const;\n\n/**\n * Return a new schema with each top-level property's uiSchema form hints copied\n * onto the corresponding property as x-ui-* keys. The input schema/uiSchema are\n * not mutated. uiSchema hints win over any pre-existing embedded key.\n */\nexport function embedUiSchema(\n schema: JsonSchema,\n uiSchema: Record<string, UISchema>,\n): JsonSchema {\n const next = structuredClone(schema);\n for (const [fieldName, entry] of Object.entries(uiSchema)) {\n const prop: JsonSchemaProperty | undefined = next.properties[fieldName];\n if (!prop || !entry) continue;\n for (const key of EMBEDDABLE_KEYS) {\n if (entry[key] !== undefined) {\n (prop as Record<string, unknown>)[key] = entry[key];\n }\n }\n }\n return next;\n}\n","/**\n * useDesignerState -- owns the designer's { schema, uiSchema, selection } and\n * exposes bound mutation operations.\n *\n * Controlled: pass `schema` + `uiSchema` + `onChange`; the hook holds no schema\n * state and every op calls `onChange`. Uncontrolled: pass `initialSchema`\n * (+ optional `initialUiSchema`); the hook manages the schema internally.\n * Selection (the active property path) is always internal UI state.\n */\n\nimport { useCallback, useMemo, useRef, useState } from \"react\";\nimport type {\n JsonSchema,\n JsonSchemaProperty,\n UISchema,\n UILayoutConfig,\n UILayoutRowConfig,\n UILayoutGroupConfig,\n UISchemaOptions,\n RefResolver,\n} from \"@petrarca/sonnet-core/schema\";\nimport {\n addProperty,\n addBranch,\n removeBranch,\n moveBranch,\n addConditional,\n removeConditional,\n setCondition,\n setConditionalBehavior,\n addElse,\n removeElse,\n deleteProperty,\n moveProperty,\n renameProperty,\n setRequired,\n updateProperty,\n changePropertyType,\n setReference,\n addDefinition,\n renameDefinition,\n removeDefinition,\n type NewPropertyKind,\n type PropertyTypeChoice,\n setEnum,\n setUiEntry,\n setTableHints,\n type TableHints,\n setPropertyLayout,\n setRootLayout,\n setRootLayoutRows,\n setScopedLayoutRows,\n setScopedLayoutOptions,\n setScopedLayoutGroups,\n setScopedGroupRows,\n setScopedLayoutMode,\n addLayoutGroup,\n renameLayoutGroup,\n removeLayoutGroup,\n moveLayoutGroup,\n setLayoutGroupRule,\n setScopedLayoutVariant,\n placeFieldInGroup,\n setGlobalOptions,\n type DesignerModel,\n type UiSchemaMap,\n type EnumChoice,\n} from \"../model/mutate\";\nimport {\n samePath,\n sameSegment,\n slot as slotSeg,\n condition as condSeg,\n def as defSeg,\n getProperty,\n type ConditionCombinator,\n type PathSegment,\n type PropertyPath,\n} from \"../model/paths\";\nimport {\n resolveCapabilities,\n type SchemaDesignerCapabilities,\n type ResolvedCapabilities,\n} from \"../capabilities\";\nimport { isPropertyEditable, canAddChildTo } from \"../model/scoping\";\n\n// Whether path `p` is `prefix` or a descendant of it (segment-wise).\nfunction pathStartsWith(p: PropertyPath, prefix: PropertyPath): boolean {\n if (p.length < prefix.length) return false;\n return prefix.every((seg, i) => sameSegment(seg, p[i]));\n}\n\n// Whether path `p` runs through the same parent as `removed` (every segment\n// before the removed one matches). `removed` ends in an indexed segment.\nfunction sharesParentPrefix(p: PropertyPath, removed: PropertyPath): boolean {\n if (p.length < removed.length) return false;\n const parentLen = removed.length - 1;\n for (let i = 0; i < parentLen; i++) {\n if (!sameSegment(p[i], removed[i])) return false;\n }\n return true;\n}\n\n// When an indexed sibling (branch or condition) at `removed` is spliced out,\n// adjust a selection that pointed at it (clear) or at a higher-indexed sibling\n// (shift its index down by one) -- including selections nested inside such a\n// sibling. Selections elsewhere are returned unchanged.\n// Whether two indexed segments (branch/condition) index the same array -- i.e.\n// they are siblings whose positions shift together. For conditions this\n// requires the same combinator; branches share one array.\nfunction sameIndexedArray(a: PathSegment, b: PathSegment): boolean {\n if (a.kind !== b.kind) return false;\n if (a.kind === \"branch\" && b.kind === \"branch\") return true;\n if (a.kind === \"condition\" && b.kind === \"condition\")\n return a.combinator === b.combinator;\n return false;\n}\n\n// The selected segment sitting in the same indexed array as the removed one,\n// or null when the selection is unaffected by the removal.\nfunction affectedSibling(\n prev: PropertyPath,\n removed: PropertyPath,\n kind: \"branch\" | \"condition\",\n): { at: number; seg: Extract<PathSegment, { index: number }> } | null {\n const last = removed[removed.length - 1];\n if (!last || last.kind !== kind) return null;\n if (!sharesParentPrefix(prev, removed)) return null;\n const at = removed.length - 1;\n const seg = prev[at];\n if (!seg || !sameIndexedArray(seg, last) || !(\"index\" in seg)) return null;\n return { at, seg };\n}\n\nfunction adjustIndexedSelection(\n prev: PropertyPath | null,\n removed: PropertyPath,\n kind: \"branch\" | \"condition\",\n): PropertyPath | null {\n if (!prev) return null;\n const hit = affectedSibling(prev, removed, kind);\n if (!hit) return prev;\n const removedIndex = (removed[removed.length - 1] as { index: number }).index;\n if (hit.seg.index === removedIndex) return null; // selected the removed node\n if (hit.seg.index < removedIndex) return prev; // sits before -- unchanged\n // Sits after the removed one: shift its index down (spread keeps combinator).\n const shifted = { ...hit.seg, index: hit.seg.index - 1 };\n return [...prev.slice(0, hit.at), shifted, ...prev.slice(hit.at + 1)];\n}\n\nfunction adjustBranchSelection(\n prev: PropertyPath | null,\n removed: PropertyPath,\n): PropertyPath | null {\n return adjustIndexedSelection(prev, removed, \"branch\");\n}\n\n// The number of conditional members (with an `if`) in one combinator array.\nfunction countConditionals(arr: { if?: unknown }[] | undefined): number {\n return Array.isArray(arr) ? arr.filter((m) => !!m.if).length : 0;\n}\n\n// The selected condition segment at `objectPath` when it belongs to combinator\n// `from`, else null. Encapsulates the \"does this selection apply\" guards.\nfunction selectedConditionInCombinator(\n prev: PropertyPath | null,\n objectPath: PropertyPath,\n from: ConditionCombinator,\n): { at: number; index: number } | null {\n if (!prev) return null;\n const at = objectPath.length;\n const seg = prev[at];\n if (!seg || seg.kind !== \"condition\" || seg.combinator !== from) return null;\n if (!samePath(prev.slice(0, at), objectPath)) return null;\n return { at, index: seg.index };\n}\n\n/**\n * After a Match (AND/OR) switch on the object at `objectPath`, keep the\n * selection on the same conditional by remapping its segment to the target\n * combinator + new index. Uses the PRE-migration model to compute positions.\n * Returns `prev` unchanged when the selection is not a conditional here.\n */\nfunction remapConditionSelection(\n before: DesignerModel,\n prev: PropertyPath | null,\n objectPath: PropertyPath,\n next: ConditionCombinator,\n): PropertyPath | null {\n const from: ConditionCombinator = next === \"allOf\" ? \"anyOf\" : \"allOf\";\n const hit = selectedConditionInCombinator(prev, objectPath, from);\n if (!hit || !prev) return prev;\n\n const owner =\n objectPath.length === 0\n ? { allOf: before.schema.allOf, anyOf: before.schema.anyOf }\n : getProperty(before.schema, objectPath);\n const sourceArr = owner?.[from] as { if?: unknown }[] | undefined;\n if (!Array.isArray(sourceArr)) return prev;\n\n // Conditionals move to the end of the target's existing conditionals, keeping\n // relative order. New index = (target's prior conditionals) + (this member's\n // position among the source conditionals).\n const posAmongSource = countConditionals(sourceArr.slice(0, hit.index));\n const targetOffset = countConditionals(\n owner?.[next] as { if?: unknown }[] | undefined,\n );\n return [\n ...prev.slice(0, hit.at),\n condSeg(targetOffset + posAmongSource, next),\n ...prev.slice(hit.at + 1),\n ];\n}\n\nexport interface UseDesignerStateArgs {\n schema?: JsonSchema;\n uiSchema?: UiSchemaMap;\n initialSchema?: JsonSchema;\n initialUiSchema?: UiSchemaMap;\n onChange?: (schema: JsonSchema, uiSchema: UiSchemaMap) => void;\n readOnly?: boolean;\n capabilities?: SchemaDesignerCapabilities;\n /** Optional resolver for non-local `$ref`s (registry id / URI); local $defs\n * resolve automatically. Used to expand ref nodes (read-only) in the tree. */\n refResolver?: RefResolver;\n}\n\nexport interface DesignerState {\n schema: JsonSchema;\n uiSchema: UiSchemaMap;\n selection: PropertyPath | null;\n readOnly: boolean;\n /** Resolver for $ref expansion in the tree (undefined = local $defs only). */\n refResolver?: RefResolver;\n /** Resolved capability profile (readOnly + editablePaths applied). */\n capabilities: ResolvedCapabilities;\n /** Whether the property at path may be renamed / deleted / retyped / reordered. */\n canEditProperty: (path: PropertyPath) => boolean;\n /** Whether a child property may be added to the container at path (root = []). */\n canAddChild: (path: PropertyPath) => boolean;\n select: (path: PropertyPath | null) => void;\n addProperty: (parentPath: PropertyPath, kind: NewPropertyKind) => void;\n /** Add a branch to the oneOf property at path. */\n addBranch: (path: PropertyPath) => void;\n /** Remove the branch at path (a branch segment). */\n removeBranch: (path: PropertyPath) => void;\n /** Move the branch at path up (-1) or down (+1). */\n moveBranch: (path: PropertyPath, direction: -1 | 1) => void;\n /** Add an if/then/else conditional to the object at path (root when empty). */\n addConditional: (\n objectPath: PropertyPath,\n combinator?: ConditionCombinator,\n ) => void;\n /** Switch the AND/OR combinator for the conditionals of the object at path. */\n setConditionalBehavior: (\n objectPath: PropertyPath,\n combinator: ConditionCombinator,\n ) => void;\n /** Remove the conditional at path (a condition segment). */\n removeConditional: (path: PropertyPath) => void;\n /** Write the `if` schema of the conditional at path. */\n setCondition: (path: PropertyPath, ifSchema: JsonSchemaProperty) => void;\n /** Add an empty `else` branch to the conditional at path. */\n addElse: (path: PropertyPath) => void;\n /** Remove the `else` branch from the conditional at path. */\n removeElse: (path: PropertyPath) => void;\n deleteProperty: (path: PropertyPath) => void;\n renameProperty: (path: PropertyPath, nextKey: string) => void;\n moveProperty: (path: PropertyPath, direction: -1 | 1) => void;\n setRequired: (path: PropertyPath, required: boolean) => void;\n updateProperty: (\n path: PropertyPath,\n patch: Partial<JsonSchemaProperty>,\n ) => void;\n changePropertyType: (path: PropertyPath, next: PropertyTypeChoice) => void;\n /** Point the property at path at a definition (writes a local `$ref`). */\n setReference: (path: PropertyPath, name: string) => void;\n /** Add a new empty object definition to `$defs`. Selects the new node. */\n addDefinition: (name?: string) => void;\n /** Rename a `$defs` entry; rewrites every local `$ref` that targets it. */\n renameDefinition: (oldName: string, newName: string) => void;\n /** Remove an unused `$defs` entry (blocked while any `$ref` targets it). */\n removeDefinition: (name: string) => void;\n /** Replace the whole JSON Schema (from the editable JSON Schema source tab). */\n replaceSchema: (schema: JsonSchema) => void;\n /** Replace the whole UI Schema map (from the editable UI Schema source tab). */\n replaceUiSchema: (uiSchema: UiSchemaMap) => void;\n setEnum: (path: PropertyPath, choices: EnumChoice[]) => void;\n setUiEntry: (path: PropertyPath, entry: UISchema | undefined) => void;\n setTableHints: (path: PropertyPath, hints: TableHints) => void;\n setPropertyLayout: (\n path: PropertyPath,\n layout: UILayoutConfig | undefined,\n ) => void;\n setRootLayout: (layout: UILayoutConfig | undefined) => void;\n setRootLayoutRows: (rows: UILayoutConfig[\"rows\"]) => void;\n setScopedLayoutRows: (\n scopePath: PropertyPath,\n rows: UILayoutConfig[\"rows\"],\n ) => void;\n setScopedLayoutOptions: (\n scopePath: PropertyPath,\n options: Pick<UILayoutConfig, \"direction\" | \"gap\" | \"labels\" | \"compact\">,\n ) => void;\n /** Replace a scope's group definitions (empty clears groups -> flat rows). */\n setScopedLayoutGroups: (\n scopePath: PropertyPath,\n groups: UILayoutConfig[\"groups\"],\n ) => void;\n /** Replace the rows of one group within a scope. */\n setScopedGroupRows: (\n scopePath: PropertyPath,\n groupIndex: number,\n rows: UILayoutRowConfig[],\n ) => void;\n /** Switch a scope between flat rows and groups, carrying placements over. */\n setScopedLayoutMode: (\n scopePath: PropertyPath,\n mode: \"rows\" | \"groups\",\n ) => void;\n /** Append an empty group to a scope. */\n addLayoutGroup: (scopePath: PropertyPath, label?: string) => void;\n /** Rename one group of a scope. */\n renameLayoutGroup: (\n scopePath: PropertyPath,\n groupIndex: number,\n label: string,\n ) => void;\n /** Remove one group; removing the last flattens its rows back to flat rows. */\n removeLayoutGroup: (scopePath: PropertyPath, groupIndex: number) => void;\n /** Move one group left (-1) or right (+1). */\n moveLayoutGroup: (\n scopePath: PropertyPath,\n groupIndex: number,\n direction: -1 | 1,\n ) => void;\n /** Set (or clear) a group's show/hide rule. */\n setLayoutGroupRule: (\n scopePath: PropertyPath,\n groupIndex: number,\n rule: UILayoutGroupConfig[\"rule\"],\n ) => void;\n /** Choose the group presentation (\"tabs\", \"stepper\", \"sections\", ...). */\n setScopedLayoutVariant: (\n scopePath: PropertyPath,\n variant: UILayoutConfig[\"variant\"],\n ) => void;\n /** Place a property into a group's row, or back in the pool (null target). */\n placeFieldInGroup: (\n scopePath: PropertyPath,\n key: string,\n target: { groupIndex: number; rowIndex: number } | null,\n ) => void;\n setGlobalOptions: (options: UISchemaOptions | undefined) => void;\n}\n\nconst EMPTY_SCHEMA: JsonSchema = {\n title: \"\",\n type: \"object\",\n properties: {},\n};\n\nexport function useDesignerState(args: UseDesignerStateArgs): DesignerState {\n const { onChange, readOnly = false } = args;\n const controlled = args.schema !== undefined;\n\n const [internal, setInternal] = useState<DesignerModel>(() => ({\n schema: args.initialSchema ?? EMPTY_SCHEMA,\n uiSchema: args.initialUiSchema ?? {},\n }));\n const [selection, setSelection] = useState<PropertyPath | null>(null);\n\n // The live model: controlled props win; otherwise internal state.\n const model: DesignerModel = controlled\n ? { schema: args.schema!, uiSchema: args.uiSchema ?? {} }\n : internal;\n\n // Keep a ref so the mutation callbacks are stable but read the latest model.\n const modelRef = useRef(model);\n modelRef.current = model;\n\n const commit = useCallback(\n (next: DesignerModel) => {\n if (!controlled) setInternal(next);\n onChange?.(next.schema, next.uiSchema);\n },\n [controlled, onChange],\n );\n\n const select = useCallback((path: PropertyPath | null) => {\n setSelection((prev) => (samePath(prev, path) ? prev : path));\n }, []);\n\n const capabilities = useMemo(\n () => resolveCapabilities(args.capabilities, readOnly),\n [args.capabilities, readOnly],\n );\n\n // Structural gating: readOnly locks everything; scoped restricts edits to the\n // children of editablePaths. Read the latest model via the ref so callbacks\n // stay stable.\n const canEditProperty = useCallback(\n (path: PropertyPath) => {\n if (capabilities.locked) return false;\n return isPropertyEditable(\n modelRef.current.schema,\n path,\n capabilities.editablePaths,\n );\n },\n [capabilities.locked, capabilities.editablePaths],\n );\n const canAddChild = useCallback(\n (path: PropertyPath) => {\n if (capabilities.locked) return false;\n return canAddChildTo(\n modelRef.current.schema,\n path,\n capabilities.editablePaths,\n );\n },\n [capabilities.locked, capabilities.editablePaths],\n );\n\n const ops = useMemo(\n () => ({\n addProperty(parentPath: PropertyPath, kind: NewPropertyKind) {\n if (!canAddChild(parentPath)) return;\n const res = addProperty(modelRef.current, parentPath, kind);\n commit(res.model);\n setSelection(res.path);\n },\n addBranch(path: PropertyPath) {\n if (!canEditProperty(path)) return;\n const res = addBranch(modelRef.current, path);\n commit(res.model);\n setSelection(res.path);\n },\n removeBranch(path: PropertyPath) {\n if (!canEditProperty(path)) return;\n commit(removeBranch(modelRef.current, path));\n setSelection((prev) => adjustBranchSelection(prev, path));\n },\n moveBranch(path: PropertyPath, direction: -1 | 1) {\n if (!canEditProperty(path)) return;\n commit(moveBranch(modelRef.current, path, direction));\n },\n addConditional(\n objectPath: PropertyPath,\n combinator: ConditionCombinator = \"allOf\",\n ) {\n // Adding a conditional augments the object -- gate like adding a child.\n if (!canAddChild(objectPath)) return;\n const res = addConditional(modelRef.current, objectPath, combinator);\n commit(res.model);\n setSelection(res.path);\n },\n setConditionalBehavior(\n objectPath: PropertyPath,\n combinator: ConditionCombinator,\n ) {\n if (!canAddChild(objectPath)) return;\n const before = modelRef.current;\n commit(setConditionalBehavior(before, objectPath, combinator));\n // Keep the selection pointing at the same conditional after migration:\n // remap its combinator + index to the target array.\n setSelection((prev) =>\n remapConditionSelection(before, prev, objectPath, combinator),\n );\n },\n removeConditional(path: PropertyPath) {\n // Editing a conditional is scoped to its owning object.\n if (!canAddChild(path.slice(0, -1))) return;\n commit(removeConditional(modelRef.current, path));\n // Splicing the allOf member shifts higher-indexed siblings down.\n setSelection((prev) => adjustIndexedSelection(prev, path, \"condition\"));\n },\n setCondition(path: PropertyPath, ifSchema: JsonSchemaProperty) {\n if (!canAddChild(path.slice(0, -1))) return;\n commit(setCondition(modelRef.current, path, ifSchema));\n },\n addElse(path: PropertyPath) {\n if (!canAddChild(path.slice(0, -1))) return;\n commit(addElse(modelRef.current, path));\n },\n removeElse(path: PropertyPath) {\n if (!canAddChild(path.slice(0, -1))) return;\n commit(removeElse(modelRef.current, path));\n // Clear a selection that was on the removed else slot (or nested under it).\n const elsePath = [...path, slotSeg(\"else\")];\n setSelection((prev) =>\n prev && pathStartsWith(prev, elsePath) ? null : prev,\n );\n },\n deleteProperty(path: PropertyPath) {\n if (!canEditProperty(path)) return;\n commit(deleteProperty(modelRef.current, path));\n setSelection((prev) => (samePath(prev, path) ? null : prev));\n },\n renameProperty(path: PropertyPath, nextKey: string) {\n if (!canEditProperty(path)) return;\n const res = renameProperty(modelRef.current, path, nextKey);\n commit(res.model);\n setSelection(res.path);\n },\n moveProperty(path: PropertyPath, direction: -1 | 1) {\n if (!canEditProperty(path)) return;\n commit(moveProperty(modelRef.current, path, direction));\n },\n setRequired(path: PropertyPath, required: boolean) {\n if (!canEditProperty(path)) return;\n commit(setRequired(modelRef.current, path, required));\n },\n updateProperty(path: PropertyPath, patch: Partial<JsonSchemaProperty>) {\n if (!canEditProperty(path)) return;\n commit(updateProperty(modelRef.current, path, patch));\n },\n changePropertyType(path: PropertyPath, next: PropertyTypeChoice) {\n if (!canEditProperty(path)) return;\n commit(changePropertyType(modelRef.current, path, next));\n },\n setReference(path: PropertyPath, name: string) {\n if (!canEditProperty(path)) return;\n commit(setReference(modelRef.current, path, name));\n },\n // Definitions are document-level, not path-scoped: gate on lock only.\n addDefinition(name?: string) {\n if (capabilities.locked) return;\n const res = addDefinition(modelRef.current, name);\n commit(res.model);\n setSelection(res.path);\n },\n renameDefinition(oldName: string, newName: string) {\n if (capabilities.locked) return;\n const res = renameDefinition(modelRef.current, oldName, newName);\n commit(res.model);\n // Keep the selection on the renamed definition.\n setSelection((prev) =>\n prev && samePath(prev, [defSeg(oldName)]) ? res.path : prev,\n );\n },\n removeDefinition(name: string) {\n if (capabilities.locked) return;\n commit(removeDefinition(modelRef.current, name));\n // Clear a selection sitting on (or inside) the removed definition.\n setSelection((prev) =>\n prev && pathStartsWith(prev, [defSeg(name)]) ? null : prev,\n );\n },\n // Replace the whole JSON Schema (from the editable JSON Schema tab).\n // The uiSchema is preserved. Gated by capabilities.locked only -- a\n // wholesale replace is not subject to per-path scoping.\n replaceSchema(schema: JsonSchema) {\n if (capabilities.locked) return;\n commit({ schema, uiSchema: modelRef.current.uiSchema });\n setSelection(null);\n },\n // Replace the whole UI Schema map (from the editable UI Schema tab).\n replaceUiSchema(uiSchema: UiSchemaMap) {\n if (readOnly) return;\n commit({ schema: modelRef.current.schema, uiSchema });\n },\n setEnum(path: PropertyPath, choices: EnumChoice[]) {\n if (!canEditProperty(path)) return;\n commit(setEnum(modelRef.current, path, choices));\n },\n // UI-schema / presentation ops use `readOnly` (not `capabilities.locked`)\n // because they are not subject to scoped-path gating: presentation hints\n // are always either fully editable or fully locked.\n setUiEntry(path: PropertyPath, entry: UISchema | undefined) {\n if (readOnly) return;\n commit(setUiEntry(modelRef.current, path, entry));\n },\n setTableHints(path: PropertyPath, hints: TableHints) {\n if (readOnly) return;\n commit(setTableHints(modelRef.current, path, hints));\n },\n setPropertyLayout(\n path: PropertyPath,\n layout: UILayoutConfig | undefined,\n ) {\n if (readOnly) return;\n commit(setPropertyLayout(modelRef.current, path, layout));\n },\n setRootLayout(layout: UILayoutConfig | undefined) {\n if (readOnly) return;\n commit(setRootLayout(modelRef.current, layout));\n },\n setRootLayoutRows(rows: UILayoutConfig[\"rows\"]) {\n if (readOnly) return;\n commit(setRootLayoutRows(modelRef.current, rows));\n },\n setScopedLayoutRows(\n scopePath: PropertyPath,\n rows: UILayoutConfig[\"rows\"],\n ) {\n if (readOnly) return;\n commit(setScopedLayoutRows(modelRef.current, scopePath, rows));\n },\n setScopedLayoutOptions(\n scopePath: PropertyPath,\n options: Pick<\n UILayoutConfig,\n \"direction\" | \"gap\" | \"labels\" | \"compact\"\n >,\n ) {\n if (readOnly) return;\n commit(setScopedLayoutOptions(modelRef.current, scopePath, options));\n },\n setScopedLayoutGroups(\n scopePath: PropertyPath,\n groups: UILayoutConfig[\"groups\"],\n ) {\n if (readOnly) return;\n commit(setScopedLayoutGroups(modelRef.current, scopePath, groups));\n },\n setScopedGroupRows(\n scopePath: PropertyPath,\n groupIndex: number,\n rows: UILayoutRowConfig[],\n ) {\n if (readOnly) return;\n commit(\n setScopedGroupRows(modelRef.current, scopePath, groupIndex, rows),\n );\n },\n setScopedLayoutMode(scopePath: PropertyPath, mode: \"rows\" | \"groups\") {\n if (readOnly) return;\n commit(setScopedLayoutMode(modelRef.current, scopePath, mode));\n },\n addLayoutGroup(scopePath: PropertyPath, label?: string) {\n if (readOnly) return;\n commit(addLayoutGroup(modelRef.current, scopePath, label));\n },\n renameLayoutGroup(\n scopePath: PropertyPath,\n groupIndex: number,\n label: string,\n ) {\n if (readOnly) return;\n commit(\n renameLayoutGroup(modelRef.current, scopePath, groupIndex, label),\n );\n },\n removeLayoutGroup(scopePath: PropertyPath, groupIndex: number) {\n if (readOnly) return;\n commit(removeLayoutGroup(modelRef.current, scopePath, groupIndex));\n },\n moveLayoutGroup(\n scopePath: PropertyPath,\n groupIndex: number,\n direction: -1 | 1,\n ) {\n if (readOnly) return;\n commit(\n moveLayoutGroup(modelRef.current, scopePath, groupIndex, direction),\n );\n },\n setLayoutGroupRule(\n scopePath: PropertyPath,\n groupIndex: number,\n rule: UILayoutGroupConfig[\"rule\"],\n ) {\n if (readOnly) return;\n commit(\n setLayoutGroupRule(modelRef.current, scopePath, groupIndex, rule),\n );\n },\n setScopedLayoutVariant(\n scopePath: PropertyPath,\n variant: UILayoutConfig[\"variant\"],\n ) {\n if (readOnly) return;\n commit(setScopedLayoutVariant(modelRef.current, scopePath, variant));\n },\n placeFieldInGroup(\n scopePath: PropertyPath,\n key: string,\n target: { groupIndex: number; rowIndex: number } | null,\n ) {\n if (readOnly) return;\n commit(placeFieldInGroup(modelRef.current, scopePath, key, target));\n },\n setGlobalOptions(options: UISchemaOptions | undefined) {\n if (readOnly) return;\n commit(setGlobalOptions(modelRef.current, options));\n },\n }),\n [commit, readOnly, capabilities.locked, canEditProperty, canAddChild],\n );\n\n return {\n schema: model.schema,\n uiSchema: model.uiSchema,\n selection,\n readOnly,\n refResolver: args.refResolver,\n capabilities,\n canEditProperty,\n canAddChild,\n select,\n ...ops,\n };\n}\n","/**\n * SchemaDesigner capabilities -- a small profile that gates what a consumer can\n * author. Mirrors the discipline of GraphModelEditor's capabilities: the Zod\n * schema below is the single source of truth, the TypeScript types are inferred\n * from it, and `resolveCapabilities` applies defaults (with `readOnly` as a\n * fully-locked shorthand). Every field is optional and defaults to the most\n * permissive value, so adding a capability never tightens an existing profile.\n *\n * Design: docs/design/schema-designer.md, section \"Capability gating\".\n */\n\nimport { z } from \"zod\";\nimport { warnLog } from \"@petrarca/sonnet-core\";\n\n/**\n * A tab the center pane can offer. \"form\" / \"table\" / \"json\" preview the\n * schema; \"capabilities\" is a meta-editor for the profile itself (a dev /\n * power-user affordance), not a preview -- it is opt-in and never in a default.\n */\nexport type PreviewKind = \"form\" | \"table\" | \"json\" | \"capabilities\";\n\n/**\n * The capabilities schema. Small by design -- it covers the real consumer needs\n * (sestina's audit-event and terminology schema editors) without a per-area\n * matrix we do not use yet.\n */\nexport const capabilitiesSchema = z\n .object({\n mode: z.enum([\"data\", \"full\"]).default(\"full\").meta({\n description:\n \"What the designer authors. 'full' (default): JSON Schema + uiSchema (form presentation hints). 'data': JSON Schema only -- the UI Schema tab, Combined tab, and the inspector's per-field UI tab are hidden (pure data schemas: audit events, terminology).\",\n }),\n previews: z\n .array(z.enum([\"form\", \"table\", \"json\", \"capabilities\"]))\n .optional()\n .meta({\n description:\n \"Which tabs the center pane offers, in order. 'form'/'table'/'json' preview the schema; 'capabilities' is a JSON editor for this profile (opt-in, never in a default). When omitted, defaults to ['form','table','json'] in 'full' mode and ['json'] in 'data' mode. An empty list hides the center pane entirely.\",\n }),\n editablePaths: z.array(z.string()).optional().meta({\n description:\n \"Scoped editing. When set, the passed-in schema is fixed EVERYWHERE except the children of these JSON Pointer (RFC 6901) paths, which the user may add / delete / edit. Absent = fully editable. readOnly overrides this to fully locked.\",\n }),\n })\n .meta({\n id: \"SchemaDesignerCapabilities\",\n title: \"SchemaDesignerCapabilities\",\n description:\n \"Capability profile for SchemaDesigner. Gates what a consumer can author. Every field is optional and defaults to the most permissive value (forward-compatible). Passing readOnly to the designer overrides this object to a fully-locked profile.\",\n });\n\n/**\n * The capabilities a consumer may pass. Inferred from the schema, with all\n * fields optional on input (defaults are applied by resolveCapabilities).\n */\nexport type SchemaDesignerCapabilities = z.input<typeof capabilitiesSchema>;\n\n/** The fully-resolved capabilities, plus the derived flags used for gating. */\nexport interface ResolvedCapabilities {\n mode: \"data\" | \"full\";\n /** Effective preview list (defaulted by mode when not provided). */\n previews: PreviewKind[];\n /** JSON Pointer paths whose children are editable; empty = no scoping. */\n editablePaths: string[];\n /** No structural edits at all (readOnly shorthand). */\n locked: boolean;\n /** editablePaths is non-empty -- only designated subtrees are editable. */\n scoped: boolean;\n /** The Capabilities editor tab is listed in previews. */\n showCapabilities: boolean;\n /** Whether the center pane renders at all (previews non-empty). */\n showPreview: boolean;\n}\n\n/** Default preview lists per mode. */\nfunction defaultPreviews(mode: \"data\" | \"full\"): PreviewKind[] {\n return mode === \"data\" ? [\"json\"] : [\"form\", \"table\", \"json\"];\n}\n\n/**\n * Resolve the effective capabilities: readOnly wins (fully locked), otherwise\n * parse the provided capabilities (applying per-field defaults). Invalid input\n * falls back to permissive defaults rather than throwing.\n */\nexport function resolveCapabilities(\n capabilities: SchemaDesignerCapabilities | undefined,\n readOnly: boolean | undefined,\n): ResolvedCapabilities {\n const parsed = capabilitiesSchema.safeParse(capabilities ?? {});\n const value = parsed.success ? parsed.data : capabilitiesSchema.parse({});\n if (!parsed.success) {\n warnLog(\n \"[SchemaDesigner] Invalid capabilities — falling back to defaults.\",\n parsed.error.issues,\n );\n }\n const mode = value.mode;\n const previews = value.previews ?? defaultPreviews(mode);\n const editablePaths = value.editablePaths ?? [];\n return {\n mode,\n previews,\n editablePaths,\n locked: !!readOnly,\n scoped: !readOnly && editablePaths.length > 0,\n showCapabilities: previews.includes(\"capabilities\"),\n showPreview: previews.length > 0,\n };\n}\n\n/** Result of validating an untrusted capabilities object. */\nexport type CapabilitiesValidation =\n | { ok: true; value: SchemaDesignerCapabilities }\n | { ok: false; errors: string[] };\n\n/**\n * Validate a hand-authored / external capabilities object. Returns the parsed\n * value or a list of readable error messages. Does not throw.\n */\nexport function validateCapabilities(input: unknown): CapabilitiesValidation {\n const parsed = capabilitiesSchema.safeParse(input);\n if (parsed.success) return { ok: true, value: parsed.data };\n const errors = parsed.error.issues.map((i) => {\n const path = i.path.length ? i.path.join(\".\") : \"(root)\";\n return `${path}: ${i.message}`;\n });\n return { ok: false, errors };\n}\n","/**\n * Scoped-editing helpers. When capabilities carry `editablePaths` (JSON Pointer,\n * RFC 6901), the schema is fixed everywhere except the *children* of those\n * paths. This module maps the designer's key-array PropertyPath to the JSON\n * Pointer of the container that holds a property, and decides whether a given\n * property (or the root) is editable.\n *\n * A property's own pointer is built by walking the schema from the root:\n * each segment contributes `/properties/<key>`, and an array crossing inserts\n * `/items` before descending (mirroring childContainer navigation). The\n * *parent container* pointer is the property pointer with the trailing\n * `/<key>` removed -- this is what `editablePaths` names (e.g.\n * `/properties/metadata/properties`).\n */\n\nimport type {\n JsonSchema,\n JsonSchemaProperty,\n} from \"@petrarca/sonnet-core/schema\";\nimport { childContainer } from \"./paths\";\nimport type { PropertyPath } from \"./paths\";\n\ntype PropMap = Record<string, JsonSchemaProperty>;\n\n/** RFC 6901 escape for a single reference token. */\nfunction escapeToken(token: string): string {\n return token.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n}\n\n/**\n * The JSON Pointer of the container object that holds the property at `path`\n * (i.e. the `...properties` pointer the property lives under). Returns\n * `/properties` for a top-level property. Returns undefined if the path does\n * not resolve.\n */\nexport function parentContainerPointer(\n schema: JsonSchema,\n path: PropertyPath,\n): string | undefined {\n if (path.length === 0) return undefined;\n let container: PropMap | undefined = schema.properties;\n let pointer = \"/properties\";\n for (let i = 0; i < path.length; i++) {\n if (!container) return undefined;\n const segment = path[i];\n // Scoping applies to property containers only; a non-property segment\n // (branch/slot) has no `.../properties` pointer.\n if (segment.kind !== \"prop\") return undefined;\n const key = segment.key;\n const prop = container[key];\n if (!prop) return undefined;\n // The container holding this segment is `pointer`. For the last segment we\n // are done -- that pointer is the parent container.\n if (i === path.length - 1) return pointer;\n // Descend: cross `/items` for array-of-object, then into `/properties`.\n const next = childContainer(prop);\n if (!next) return undefined;\n pointer =\n prop.type === \"array\"\n ? `${pointer}/${escapeToken(key)}/items/properties`\n : `${pointer}/${escapeToken(key)}/properties`;\n container = next;\n }\n return pointer;\n}\n\n/**\n * Whether the property at `path` is editable (rename / delete / retype /\n * reorder). In scoped mode a property is editable only when its parent\n * container is one of the editablePaths (i.e. it is a user-added member of a\n * designated area). Without editablePaths, everything is editable.\n */\nexport function isPropertyEditable(\n schema: JsonSchema,\n path: PropertyPath,\n editablePaths: string[],\n): boolean {\n if (editablePaths.length === 0) return true;\n // For paths that cross a branch/slot segment (e.g. into a oneOf branch),\n // walk up to the nearest all-prop prefix and evaluate editability there.\n // Editing inside a branch is permitted whenever the oneOf property itself\n // is editable.\n const allPropPrefix = path.slice(\n 0,\n path.findIndex((s) => s.kind !== \"prop\") + 1 || path.length,\n );\n const effectivePath =\n allPropPrefix.length < path.length ? allPropPrefix : path;\n const parent = parentContainerPointer(schema, effectivePath);\n if (parent === undefined) return false;\n return editablePaths.includes(parent);\n}\n\n/**\n * Whether children may be added to the container at `path` (or the root when\n * path is empty). Adding is allowed when the container's own children pointer\n * is a designated editable path. Without editablePaths, always true.\n */\nexport function canAddChildTo(\n schema: JsonSchema,\n path: PropertyPath,\n editablePaths: string[],\n): boolean {\n if (editablePaths.length === 0) return true;\n if (path.length === 0) return editablePaths.includes(\"/properties\");\n const own = ownChildContainerPointer(schema, path);\n return own !== undefined && editablePaths.includes(own);\n}\n\n/** The `.../properties` pointer of a container property (array-aware). */\nexport function ownChildContainerPointer(\n schema: JsonSchema,\n path: PropertyPath,\n): string | undefined {\n const parent = parentContainerPointer(schema, path);\n if (parent === undefined) return undefined;\n // Resolve the property to know if it is an array (crosses /items).\n let container: PropMap | undefined = schema.properties;\n for (let i = 0; i < path.length; i++) {\n const segment = path[i];\n if (segment.kind !== \"prop\") return undefined;\n const prop = container?.[segment.key];\n if (!prop) return undefined;\n if (i === path.length - 1) {\n const seg = escapeToken(segment.key);\n return prop.type === \"array\"\n ? `${parent}/${seg}/items/properties`\n : `${parent}/${seg}/properties`;\n }\n container = childContainer(prop);\n }\n return undefined;\n}\n","/**\n * SchemaDesigner -- visual, controlled designer for a JsonSchema (+ uiSchema).\n *\n * Layout: Tree | Preview | Inspector. The preview (the live form) is the hero\n * and takes the flexible center, matching visual-builder convention; the\n * inspector is the resizable/collapsible right pane. Controlled via `schema` +\n * `uiSchema` + `onChange`, or uncontrolled via `initialSchema`. Read-only is a\n * mode of the same component.\n *\n * This is the assembly shell; the tree, preview, and inspector are built up\n * incrementally.\n */\n\nimport React, { useEffect, useState } from \"react\";\nimport { ResizeHandle, IconButton } from \"@petrarca/sonnet-ui\";\nimport { useResizablePanel } from \"@petrarca/sonnet-core/hooks\";\nimport {\n Settings,\n PanelRightClose,\n PanelRightOpen,\n PanelLeftOpen,\n} from \"lucide-react\";\nimport type {\n JsonSchema,\n UISchema,\n RefResolver,\n} from \"@petrarca/sonnet-core/schema\";\nimport type { WidgetOptionDef } from \"@petrarca/sonnet-forms/widget-options\";\nimport { useDesignerState } from \"./hooks/useDesignerState\";\nimport type { SchemaDesignerCapabilities } from \"./capabilities\";\nimport { FormSettingsSheet } from \"./FormSettingsSheet\";\nimport { PropertyTree } from \"./tree/PropertyTree\";\nimport { PreviewPane } from \"./preview/PreviewPane\";\nimport { Inspector } from \"./inspector/Inspector\";\n\nexport interface SchemaDesignerProps {\n /** Controlled schema. Provide with onChange. */\n schema?: JsonSchema;\n /** Controlled uiSchema map (form presentation hints). */\n uiSchema?: Record<string, UISchema>;\n /** Uncontrolled seed schema (used when `schema` is omitted). */\n initialSchema?: JsonSchema;\n /** Uncontrolled seed uiSchema. */\n initialUiSchema?: Record<string, UISchema>;\n /**\n * Called on every edit with the new schema + uiSchema (always the separate\n * form: schema is the data model, form hints live in uiSchema). Use the\n * exported `embedUiSchema` helper if a single self-contained schema is wanted.\n */\n onChange?: (schema: JsonSchema, uiSchema: Record<string, UISchema>) => void;\n /** View-only: no edit affordances, onChange never fires. Shorthand for a fully-locked profile. */\n readOnly?: boolean;\n /** Capability profile: gates data/full mode, preview renderers, and scoped editing. */\n capabilities?: SchemaDesignerCapabilities;\n /** Option descriptors for custom widgets, keyed by widget name (merged over built-ins). */\n widgetOptions?: Record<string, WidgetOptionDef[]>;\n /**\n * Optional resolver for non-local `$ref`s (schema-registry id / canonical\n * URI). Local `#/$defs` refs resolve automatically. When provided, ref nodes\n * are expanded read-only in the tree. Synchronous -- pre-load referenced\n * schemas and pass a lookup.\n */\n refResolver?: RefResolver;\n}\n\nexport function SchemaDesigner(props: SchemaDesignerProps): React.ReactElement {\n // Editable capabilities: seeded from the prop, live-editable via the\n // Capabilities tab (when previews include \"capabilities\"). Re-seeds via\n // useEffect when the prop identity changes (avoids a render-phase update).\n const [capabilities, setCapabilities] = useState<\n SchemaDesignerCapabilities | undefined\n >(props.capabilities);\n useEffect(() => {\n setCapabilities(props.capabilities);\n }, [props.capabilities]);\n\n const state = useDesignerState({ ...props, capabilities });\n\n const {\n panelWidth: inspectorWidth,\n handlePointerDown: startInspectorResize,\n handleDoubleClick: resetInspectorWidth,\n separatorProps: inspectorSepProps,\n } = useResizablePanel({\n defaultWidth: 360,\n minWidth: 300,\n maxWidth: 640,\n direction: \"left-edge\",\n });\n\n const {\n panelWidth: treeWidth,\n handlePointerDown: startTreeResize,\n handleDoubleClick: resetTreeWidth,\n separatorProps: treeSepProps,\n } = useResizablePanel({\n defaultWidth: 288,\n minWidth: 220,\n maxWidth: 520,\n direction: \"right-edge\",\n });\n\n const [inspectorCollapsed, setInspectorCollapsed] = useState(false);\n const [treeCollapsed, setTreeCollapsed] = useState(false);\n const [settingsOpen, setSettingsOpen] = useState(false);\n\n return (\n <div className=\"flex w-full h-full overflow-hidden border rounded-lg bg-background\">\n {/* Left: property tree (resizable/collapsible). Grows to fill when the\n center preview pane is hidden (tree + inspector only). */}\n {!treeCollapsed && (\n <>\n <div\n style={\n state.capabilities.showPreview ? { width: treeWidth } : undefined\n }\n className={\n state.capabilities.showPreview\n ? \"shrink-0 overflow-hidden p-3 flex flex-col min-h-0\"\n : \"flex-1 min-w-0 overflow-hidden p-3 flex flex-col min-h-0\"\n }\n >\n <PropertyTree\n state={state}\n onCollapse={() => setTreeCollapsed(true)}\n />\n </div>\n {state.capabilities.showPreview && (\n <ResizeHandle\n orientation=\"vertical\"\n {...treeSepProps}\n onPointerDown={startTreeResize}\n onDoubleClick={resetTreeWidth}\n />\n )}\n </>\n )}\n {treeCollapsed && (\n <div className=\"shrink-0 border-r flex flex-col items-center gap-1 p-1\">\n <IconButton\n label=\"Expand properties\"\n onClick={() => setTreeCollapsed(false)}\n >\n <PanelLeftOpen />\n </IconButton>\n </div>\n )}\n\n {/* Center: preview (the hero -- live form + JSON). Hidden when the\n capability profile lists no previews (structure-editing only). */}\n {state.capabilities.showPreview && (\n <div className=\"flex-1 min-w-0 overflow-hidden p-4 flex flex-col min-h-0\">\n <PreviewPane\n state={state}\n capabilities={capabilities}\n onCapabilitiesChange={setCapabilities}\n />\n </div>\n )}\n\n {/* Right: inspector (resizable/collapsible) */}\n {!inspectorCollapsed && (\n <>\n <ResizeHandle\n orientation=\"vertical\"\n {...inspectorSepProps}\n onPointerDown={startInspectorResize}\n onDoubleClick={resetInspectorWidth}\n />\n <div\n style={{ width: inspectorWidth }}\n className=\"shrink-0 border-l overflow-auto p-4 bg-card\"\n >\n <div className=\"flex items-center gap-1 mb-2\">\n <p className=\"heading-meta\">Inspector</p>\n <span className=\"ml-auto flex gap-0.5\">\n <IconButton\n label=\"Form settings\"\n onClick={() => setSettingsOpen(true)}\n >\n <Settings />\n </IconButton>\n <IconButton\n label=\"Collapse inspector\"\n onClick={() => setInspectorCollapsed(true)}\n >\n <PanelRightClose />\n </IconButton>\n </span>\n </div>\n <Inspector state={state} widgetOptions={props.widgetOptions} />\n </div>\n </>\n )}\n {inspectorCollapsed && (\n <div className=\"shrink-0 border-l flex flex-col items-center gap-1 p-1\">\n <IconButton\n label=\"Expand inspector\"\n onClick={() => setInspectorCollapsed(false)}\n >\n <PanelRightOpen />\n </IconButton>\n <IconButton\n label=\"Form settings\"\n onClick={() => setSettingsOpen(true)}\n >\n <Settings />\n </IconButton>\n </div>\n )}\n\n <FormSettingsSheet\n open={settingsOpen}\n onOpenChange={setSettingsOpen}\n state={state}\n />\n </div>\n );\n}\n\nexport default SchemaDesigner;\n","/**\n * FormSettingsSheet -- form-level (root) settings in a right-side Sheet, opened\n * from a gear button. Holds settings that are not tied to a single property:\n * the root form layout (x-ui-layout) and global options (x-ui-globalOptions).\n *\n * Uses the house-standard Sheet pattern (as in graph-model's PropertyFormSheet).\n * Kept out of the inspector's per-property tabs, which do not scale to\n * form-wide concerns.\n */\n\nimport React from \"react\";\nimport {\n Sheet,\n SheetContent,\n SheetHeader,\n SheetBody,\n SheetTitle,\n SheetDescription,\n} from \"@petrarca/sonnet-ui\";\nimport { JsonSchemaFormRenderer, FormSelect } from \"@petrarca/sonnet-forms\";\nimport type {\n UISchemaOptions,\n UILayoutConfig,\n} from \"@petrarca/sonnet-core/schema\";\nimport type { DesignerState } from \"./hooks/useDesignerState\";\nimport {\n buildGlobalOptionsMetaSchema,\n globalOptionsToValues,\n valuesToGlobalOptions,\n type GlobalOptionsFormValues,\n} from \"./inspector/layoutMetaSchemas\";\n\nexport interface FormSettingsSheetProps {\n open: boolean;\n onOpenChange: (open: boolean) => void;\n state: DesignerState;\n}\n\nexport function FormSettingsSheet({\n open,\n onOpenChange,\n state,\n}: FormSettingsSheetProps): React.ReactElement {\n const globalOptions = state.uiSchema[\"x-ui-globalOptions\"] as\n | UISchemaOptions\n | undefined;\n\n const optionValues = globalOptionsToValues(globalOptions);\n\n const rootLayout = state.uiSchema[\"x-ui-layout\"] as\n | UILayoutConfig\n | undefined;\n const labelPlacement = rootLayout?.labelPlacement ?? \"top\";\n\n // \"top\" is the default -- omit it (and prune an emptied layout) so the\n // uiSchema stays clean.\n const setLabelPlacement = (value: \"top\" | \"start\") => {\n const next: UILayoutConfig = { ...(rootLayout ?? {}) };\n if (value === \"start\") next.labelPlacement = \"start\";\n else delete next.labelPlacement;\n state.setRootLayout(Object.keys(next).length ? next : undefined);\n };\n\n return (\n <Sheet open={open} onOpenChange={onOpenChange}>\n <SheetContent>\n <SheetHeader>\n <SheetTitle>Form settings</SheetTitle>\n <SheetDescription>\n Options applied to every field in the form.\n </SheetDescription>\n </SheetHeader>\n <SheetBody className=\"space-y-6\">\n <section className=\"space-y-2\">\n <p className=\"heading-meta\">Layout</p>\n <FormSelect\n id=\"root-labelPlacement\"\n name=\"labelPlacement\"\n label=\"Label placement\"\n value={labelPlacement}\n options={[\n { value: \"top\", label: \"Above\" },\n { value: \"start\", label: \"Inline (start)\" },\n ]}\n onChange={(v) =>\n setLabelPlacement(v === \"start\" ? \"start\" : \"top\")\n }\n disabled={state.readOnly}\n clearable={false}\n />\n </section>\n <section className=\"space-y-2\">\n <p className=\"heading-meta\">Global options</p>\n <JsonSchemaFormRenderer\n schema={buildGlobalOptionsMetaSchema()}\n data={optionValues as unknown as Record<string, unknown>}\n onChange={(data) =>\n state.setGlobalOptions(\n valuesToGlobalOptions(data as GlobalOptionsFormValues),\n )\n }\n showActions={false}\n showExtraProperties={false}\n readOnly={state.readOnly}\n />\n </section>\n </SheetBody>\n </SheetContent>\n </Sheet>\n );\n}\n","/**\n * Meta-schemas for layout (x-ui-layout) and global options (x-ui-globalOptions),\n * rendered by JsonSchemaFormRenderer. Covers the scalar array-item layout\n * options (direction / gap / labels / compact); the visual row builder lives in\n * FormLayoutDesigner.\n */\n\nimport type {\n JsonSchema,\n UILayoutConfig,\n UISchemaOptions,\n} from \"@petrarca/sonnet-core/schema\";\n\n/** Tier-1 layout meta-schema (no row builder). */\nexport function buildLayoutMetaSchema(): JsonSchema {\n return {\n title: \"\",\n type: \"object\",\n properties: {\n direction: {\n type: \"string\",\n title: \"Direction\",\n enum: [\"vertical\", \"horizontal\"],\n description: \"Stack fields vertically or lay them out horizontally.\",\n },\n gap: {\n type: \"integer\",\n title: \"Gap (px)\",\n minimum: 0,\n description: \"Space between fields.\",\n },\n labels: {\n type: \"boolean\",\n title: \"Show labels\",\n },\n compact: {\n type: \"boolean\",\n title: \"Compact\",\n description: \"Smaller control sizing.\",\n },\n },\n };\n}\n\n/** Flat form values for the layout meta-schema. */\nexport interface LayoutFormValues {\n direction?: string;\n gap?: number;\n labels?: boolean;\n compact?: boolean;\n}\n\n/** Read tier-1 layout values from a UILayoutConfig. */\nexport function layoutToValues(\n layout: UILayoutConfig | undefined,\n): LayoutFormValues {\n return {\n direction: layout?.direction,\n gap: layout?.gap,\n labels: layout?.labels,\n compact: layout?.compact,\n };\n}\n\n/**\n * Merge tier-1 form values back into an existing layout, preserving keys the\n * tier-1 form does not manage (e.g. rows, columns). Empty/undefined clears the\n * managed key. Returns undefined when the result is empty.\n */\nexport function valuesToLayout(\n values: LayoutFormValues,\n existing: UILayoutConfig | undefined,\n): UILayoutConfig | undefined {\n const next: UILayoutConfig = { ...(existing ?? {}) };\n\n if (values.direction === \"vertical\" || values.direction === \"horizontal\") {\n next.direction = values.direction;\n } else {\n delete next.direction;\n }\n if (typeof values.gap === \"number\" && !Number.isNaN(values.gap)) {\n next.gap = values.gap;\n } else {\n delete next.gap;\n }\n if (typeof values.labels === \"boolean\") next.labels = values.labels;\n else delete next.labels;\n if (typeof values.compact === \"boolean\") next.compact = values.compact;\n else delete next.compact;\n\n return Object.keys(next).length > 0 ? next : undefined;\n}\n\n/** Global options meta-schema (x-ui-globalOptions -- applies to all fields). */\nexport function buildGlobalOptionsMetaSchema(): JsonSchema {\n return {\n title: \"\",\n type: \"object\",\n properties: {\n disabled: { type: \"boolean\", title: \"Disable all fields\" },\n readonly: { type: \"boolean\", title: \"Read-only all fields\" },\n hideLabels: {\n type: \"boolean\",\n title: \"Hide all labels\",\n description: \"Sets label: false on every field.\",\n },\n compact: { type: \"boolean\", title: \"Compact all fields\" },\n },\n };\n}\n\n/** Flat form values for the global-options meta-schema. */\nexport interface GlobalOptionsFormValues {\n disabled?: boolean;\n readonly?: boolean;\n hideLabels?: boolean;\n compact?: boolean;\n}\n\n/** Read global-options form values from a UISchemaOptions object. */\nexport function globalOptionsToValues(\n options: UISchemaOptions | undefined,\n): GlobalOptionsFormValues {\n return {\n disabled: options?.disabled,\n readonly: options?.readonly,\n hideLabels: options?.label === false,\n compact: options?.compact,\n };\n}\n\n/** Merge global-options form values into a UISchemaOptions; undefined if empty. */\nexport function valuesToGlobalOptions(\n values: GlobalOptionsFormValues,\n): UISchemaOptions | undefined {\n const next: UISchemaOptions = {};\n if (values.disabled) next.disabled = true;\n if (values.readonly) next.readonly = true;\n if (values.hideLabels) next.label = false;\n if (values.compact) next.compact = true;\n return Object.keys(next).length > 0 ? next : undefined;\n}\n","/**\n * PropertyTree -- the left pane. Renders the schema's properties as a\n * hierarchical list with select / add / delete / reorder. Row idiom matches\n * graph-model/TypeDetailPanel for cross-editor consistency.\n */\n\nimport React, { useEffect, useMemo, useRef, useState } from \"react\";\nimport { cn } from \"@petrarca/sonnet-core\";\nimport { IconButton, Input } from \"@petrarca/sonnet-ui\";\nimport {\n Plus,\n Trash2,\n ChevronUp,\n ChevronDown,\n PanelLeftClose,\n Lock,\n GitBranch,\n SplitSquareHorizontal,\n Eye,\n Braces,\n Brackets,\n GitFork,\n CornerDownRight,\n Type,\n List,\n ToggleLeft,\n Hash,\n Link2,\n Puzzle,\n ChevronRight,\n type LucideIcon,\n} from \"lucide-react\";\nimport type { UIRule } from \"@petrarca/sonnet-core/schema\";\nimport type { DesignerState } from \"../hooks/useDesignerState\";\nimport { buildPropertyTree, type PropertyNode } from \"../model/view\";\nimport { pathKey, samePath } from \"../model/paths\";\nimport { definitionUsageCount } from \"../model/mutate\";\n\n// Build a memoized set of definition names that have at least one $ref,\n// computed once per schema change at the DefinitionsRegion level so row\n// renders do not each trigger a full schema walk.\nfunction buildInUseDefs(\n schema: DesignerState[\"schema\"],\n names: string[],\n): Set<string> {\n return new Set(names.filter((n) => definitionUsageCount(schema, n) > 0));\n}\n\nexport interface PropertyTreeProps {\n state: DesignerState;\n /** When provided, renders a collapse button in the header. */\n onCollapse?: () => void;\n}\n\nexport function PropertyTree({\n state,\n onCollapse,\n}: PropertyTreeProps): React.ReactElement {\n const nodes = useMemo(\n () => buildPropertyTree(state.schema, state.refResolver),\n [state.schema, state.refResolver],\n );\n // Definitions ($defs) render in their own region, separate from properties.\n const propertyNodes = useMemo(\n () => nodes.filter((n) => n.kind !== \"definition\"),\n [nodes],\n );\n const definitionNodes = useMemo(\n () => nodes.filter((n) => n.kind === \"definition\"),\n [nodes],\n );\n const canEditDefs = !state.capabilities.locked;\n const [propsOpen, setPropsOpen] = useState(true);\n\n return (\n <div className=\"flex h-full flex-col min-h-0\">\n <div className=\"mb-2 flex items-center gap-2 shrink-0\">\n <button\n type=\"button\"\n className=\"flex items-center gap-1 heading-meta\"\n onClick={() => setPropsOpen((v) => !v)}\n >\n {propsOpen ? (\n <ChevronDown className=\"h-3 w-3\" />\n ) : (\n <ChevronRight className=\"h-3 w-3\" />\n )}\n Properties\n {propertyNodes.length > 0 && (\n <span className=\"text-muted-foreground/60\">\n ({propertyNodes.length})\n </span>\n )}\n </button>\n <span className=\"ml-auto flex gap-1\">\n {state.canAddChild([]) && (\n <IconButton\n label=\"Add property\"\n onClick={() => {\n setPropsOpen(true);\n state.addProperty([], \"scalar\");\n }}\n >\n <Plus />\n </IconButton>\n )}\n {state.canAddChild([]) && (\n <IconButton\n label=\"Add condition\"\n onClick={() => {\n setPropsOpen(true);\n state.addConditional([]);\n }}\n >\n <GitBranch />\n </IconButton>\n )}\n {onCollapse && (\n <IconButton label=\"Collapse properties\" onClick={onCollapse}>\n <PanelLeftClose />\n </IconButton>\n )}\n </span>\n </div>\n\n {propsOpen &&\n (propertyNodes.length === 0 ? (\n <p className=\"text-xs text-muted-foreground\">No properties yet.</p>\n ) : (\n <div className=\"flex-1 min-h-0 overflow-auto rounded-lg border divide-y\">\n {propertyNodes.map((node) => (\n <PropertyRow\n key={pathKey(node.path)}\n node={node}\n state={state}\n depth={0}\n />\n ))}\n </div>\n ))}\n\n <DefinitionsRegion\n nodes={definitionNodes}\n state={state}\n canEdit={canEditDefs}\n />\n </div>\n );\n}\n\n// The DEFINITIONS region: a collapsible section listing $defs entries as\n// editable nodes. Collapsed by default so data-only schemas stay uncluttered.\nfunction DefinitionsRegion({\n nodes,\n state,\n canEdit,\n}: {\n nodes: PropertyNode[];\n state: DesignerState;\n canEdit: boolean;\n}): React.ReactElement | null {\n const [open, setOpen] = useState(false);\n // Compute usage counts once per schema change -- not per row render.\n const inUseDefs = useMemo(\n () =>\n buildInUseDefs(\n state.schema,\n nodes.map((n) => n.key),\n ),\n [state.schema, nodes],\n );\n // Nothing to show and nothing to add: hide the region entirely.\n if (nodes.length === 0 && !canEdit) return null;\n return (\n <div className=\"mt-3 shrink-0\">\n <div className=\"mb-2 flex items-center gap-2\">\n <button\n type=\"button\"\n className=\"flex items-center gap-1 heading-meta\"\n onClick={() => setOpen((v) => !v)}\n >\n {open ? (\n <ChevronDown className=\"h-3 w-3\" />\n ) : (\n <ChevronRight className=\"h-3 w-3\" />\n )}\n Definitions\n {nodes.length > 0 && (\n <span className=\"text-muted-foreground/60\">({nodes.length})</span>\n )}\n </button>\n {canEdit && (\n <span className=\"ml-auto flex gap-1\">\n <IconButton\n label=\"Add definition\"\n onClick={() => {\n setOpen(true);\n state.addDefinition();\n }}\n >\n <Plus />\n </IconButton>\n </span>\n )}\n </div>\n {open &&\n (nodes.length === 0 ? (\n <p className=\"text-xs text-muted-foreground\">No definitions yet.</p>\n ) : (\n <div className=\"max-h-64 overflow-auto rounded-lg border divide-y\">\n {nodes.map((node) => (\n <PropertyRow\n key={pathKey(node.path)}\n node={node}\n state={state}\n depth={0}\n inUseDefs={inUseDefs}\n />\n ))}\n </div>\n ))}\n </div>\n );\n}\n\n// Inline key editor: an input seeded with the current key, committing on Enter\n// or blur and cancelling on Escape.\nfunction NameEditor({\n initial,\n onCommit,\n onCancel,\n}: {\n initial: string;\n onCommit: (next: string) => void;\n onCancel: () => void;\n}): React.ReactElement {\n const [value, setValue] = useState(initial);\n const ref = useRef<HTMLInputElement>(null);\n useEffect(() => {\n ref.current?.focus();\n ref.current?.select();\n }, []);\n const commit = () => {\n const trimmed = value.trim();\n if (trimmed && trimmed !== initial) onCommit(trimmed);\n else onCancel();\n };\n return (\n <Input\n ref={ref}\n value={value}\n onChange={(e) => setValue(e.target.value)}\n onClick={(e) => e.stopPropagation()}\n onBlur={commit}\n onKeyDown={(e) => {\n if (e.key === \"Enter\") {\n e.preventDefault();\n commit();\n } else if (e.key === \"Escape\") {\n e.preventDefault();\n onCancel();\n }\n }}\n className=\"h-6 text-sm py-0\"\n />\n );\n}\n\n// Icon + label per property kind (scalar is resolved by primitive type below).\nconst KIND_ICONS: Partial<\n Record<PropertyNode[\"kind\"], { Icon: LucideIcon; label: string }>\n> = {\n reference: { Icon: Link2, label: \"reference\" },\n definition: { Icon: Puzzle, label: \"definition\" },\n conditional: { Icon: GitBranch, label: \"condition\" },\n object: { Icon: Braces, label: \"object\" },\n array: { Icon: Brackets, label: \"array\" },\n oneOf: { Icon: GitFork, label: \"one of\" },\n enum: { Icon: List, label: \"choice\" },\n};\n\n// The leading icon for a node, chosen by its class (kind + slot). Disambiguates\n// data vs. structure vs. logic at a glance (VS Code / Figma-layer idiom).\nfunction kindIconFor(node: PropertyNode): { Icon: LucideIcon; label: string } {\n const last = node.path[node.path.length - 1];\n if (last?.kind === \"slot\") return { Icon: CornerDownRight, label: \"branch\" };\n if (node.slotKind === \"branch\") return { Icon: GitFork, label: \"variant\" };\n return KIND_ICONS[node.kind] ?? scalarIcon(node.property.type);\n}\n\n// Scalar sub-icon by primitive type.\nfunction scalarIcon(type: string | undefined): {\n Icon: LucideIcon;\n label: string;\n} {\n if (type === \"number\" || type === \"integer\")\n return { Icon: Hash, label: \"number\" };\n if (type === \"boolean\") return { Icon: ToggleLeft, label: \"boolean\" };\n return { Icon: Type, label: \"text\" };\n}\n\nfunction KindIcon({ node }: { node: PropertyNode }): React.ReactElement {\n const { Icon, label } = kindIconFor(node);\n return (\n <Icon\n className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground/60\"\n aria-label={label}\n />\n );\n}\n\n// Markers slot: icon badges for field metadata (required, visibility rule).\n// Icons (not color alone) carry meaning; hidden on hover like the type label.\nfunction Markers({ node }: { node: PropertyNode }): React.ReactElement | null {\n const rule = node.property[\"x-ui-rule\"] as UIRule | undefined;\n if (!node.required && !rule) return null;\n const scopeField = rule?.condition.scope.replace(/^\\//, \"\");\n const ruleTip = rule\n ? `${rule.effect} when ${scopeField || rule.condition.scope}`\n : \"\";\n return (\n <span className=\"shrink-0 flex items-center gap-1 group-hover/row:hidden\">\n {node.required && (\n <span\n className=\"text-destructive text-xs leading-none\"\n title=\"required\"\n aria-label=\"required\"\n >\n *\n </span>\n )}\n {rule && (\n <span title={ruleTip} aria-label={ruleTip} className=\"flex\">\n <Eye className=\"h-3 w-3 text-primary\" />\n </span>\n )}\n </span>\n );\n}\n\n// Whether a child may be added at this node. oneOf branches and then/else\n// slots are reached through non-property segments (which the JSON Pointer\n// scoping in canAddChild cannot represent), so they gate on canEditProperty\n// (the owning construct being editable) instead.\nfunction canAddChildHere(\n node: PropertyNode,\n state: DesignerState,\n isConditional: boolean,\n): boolean {\n if (!acceptsChildren(node)) return false;\n return node.kind === \"oneOf\" || isConditional\n ? state.canEditProperty(node.path)\n : state.canAddChild(node.path);\n}\n\n// A conditional's label reads as a rule (\"IF smoker\"), not a property name.\nfunction isRuleStyled(node: PropertyNode): boolean {\n const last = node.path[node.path.length - 1];\n return node.kind === \"conditional\" || last?.kind === \"slot\";\n}\n\n// The kind icon + name (rule-styled for logic nodes) + markers + type label.\nfunction RowLabel({\n node,\n editable,\n onStartRename,\n}: {\n node: PropertyNode;\n editable: boolean;\n onStartRename: (e: React.MouseEvent) => void;\n}): React.ReactElement {\n const title = editable\n ? `${node.key}${node.required ? \" (required)\" : \"\"} -- double-click to rename`\n : `${node.key} -- fixed (not editable)`;\n const ruleStyled = isRuleStyled(node);\n return (\n <>\n <KindIcon node={node} />\n <span\n className={cn(\n \"flex-1 min-w-0 truncate text-sm\",\n ruleStyled\n ? \"font-mono text-xs uppercase tracking-wide text-muted-foreground\"\n : \"font-medium\",\n )}\n onDoubleClick={onStartRename}\n title={title}\n >\n {node.key}\n </span>\n {!editable && (\n <Lock\n className=\"h-3 w-3 shrink-0 text-muted-foreground/50\"\n aria-label=\"fixed\"\n />\n )}\n <Markers node={node} />\n <span\n className=\"shrink-0 max-w-[40%] truncate font-mono text-[11px] text-muted-foreground/70 group-hover/row:hidden\"\n title={node.typeLabel}\n >\n {node.typeLabel}\n </span>\n </>\n );\n}\n\n// A conditional member (the allOf if/then/else node) -- distinct from a\n// then/else slot, which is an object-shaped container.\nfunction isConditionalMember(node: PropertyNode): boolean {\n return node.kind === \"conditional\";\n}\n\n// A then/else slot node: an object container reached through a slot segment.\nfunction isConditionalSlot(node: PropertyNode): boolean {\n const last = node.path[node.path.length - 1];\n return node.slotKind === \"conditional\" && last?.kind === \"slot\";\n}\n\n// Whether a node can hold property children (object/array, a oneOf branch, or a\n// then/else slot). oneOf holds branches; a conditional member holds then/else.\nfunction acceptsChildren(node: PropertyNode): boolean {\n return (\n node.kind === \"object\" ||\n node.kind === \"array\" ||\n node.kind === \"oneOf\" ||\n node.kind === \"definition\" ||\n node.slotKind === \"branch\" ||\n isConditionalSlot(node)\n );\n}\n\n// Whether \"Add condition\" applies: object/array containers and the root can host\n// an if/then/else (a then/else slot is itself object-like, so also qualifies).\nfunction acceptsConditions(node: PropertyNode): boolean {\n return node.kind === \"object\" || isConditionalSlot(node);\n}\n\n// A hover-revealed icon button that stops row-click propagation.\nfunction ActionButton({\n label,\n tone,\n disabled,\n onAct,\n children,\n}: {\n label: string;\n tone?: \"destructive\";\n disabled?: boolean;\n onAct: () => void;\n children: React.ReactNode;\n}): React.ReactElement {\n return (\n <IconButton\n label={label}\n tone={tone}\n disabled={disabled}\n revealOnHover\n onClick={(e) => {\n e.stopPropagation();\n onAct();\n }}\n >\n {children}\n </IconButton>\n );\n}\n\n// Move up/down buttons for a reorderable node.\nfunction MoveActions({\n node,\n state,\n}: {\n node: PropertyNode;\n state: DesignerState;\n}): React.ReactElement {\n const isBranch = node.slotKind === \"branch\";\n const move = (dir: -1 | 1) =>\n isBranch\n ? state.moveBranch(node.path, dir)\n : state.moveProperty(node.path, dir);\n return (\n <>\n <ActionButton label=\"Move up\" onAct={() => move(-1)}>\n <ChevronUp />\n </ActionButton>\n <ActionButton label=\"Move down\" onAct={() => move(1)}>\n <ChevronDown />\n </ActionButton>\n </>\n );\n}\n\n// The additive actions (add child / add condition / add else) for a row.\nfunction AddActions({\n node,\n state,\n editable,\n canAddHere,\n}: {\n node: PropertyNode;\n state: DesignerState;\n editable: boolean;\n canAddHere: boolean;\n}): React.ReactElement {\n const isOneOf = node.kind === \"oneOf\";\n const addChild = () =>\n isOneOf\n ? state.addBranch(node.path)\n : state.addProperty(node.path, \"scalar\");\n const condMember = isConditionalMember(node) && editable;\n const hasElse = !!node.property.else;\n return (\n <>\n {canAddHere && (\n <ActionButton\n label={isOneOf ? \"Add branch\" : \"Add child property\"}\n onAct={addChild}\n >\n <Plus />\n </ActionButton>\n )}\n {editable && acceptsConditions(node) && (\n <ActionButton\n label=\"Add condition\"\n onAct={() => state.addConditional(node.path)}\n >\n <GitBranch />\n </ActionButton>\n )}\n {/* Add else on the conditional; removing else is done from the else row. */}\n {condMember && !hasElse && (\n <ActionButton label=\"Add else\" onAct={() => state.addElse(node.path)}>\n <SplitSquareHorizontal />\n </ActionButton>\n )}\n </>\n );\n}\n\n// The last path segment, or undefined for the root.\nfunction lastSegment(node: PropertyNode) {\n return node.path[node.path.length - 1];\n}\n\ninterface RemoveDescriptor {\n label: string;\n disabled: boolean;\n remove: () => void;\n}\n\n// The removal label + action for a row, or null when the row is not removable\n// (the `then` slot is permanent -- a conditional always needs a then).\nfunction removeDescriptor(\n node: PropertyNode,\n state: DesignerState,\n inUseDefs: Set<string>,\n): RemoveDescriptor | null {\n const last = lastSegment(node);\n const slotName = last?.kind === \"slot\" ? last.slot : undefined;\n if (slotName === \"then\") return null; // then is not removable\n if (node.slotKind === \"branch\") {\n return simpleRemove(\"Remove branch\", () => state.removeBranch(node.path));\n }\n if (isConditionalMember(node)) {\n return simpleRemove(\"Remove condition\", () =>\n state.removeConditional(node.path),\n );\n }\n if (node.kind === \"definition\") {\n const inUse = inUseDefs.has(node.key);\n return {\n label: inUse ? \"In use -- remove references first\" : \"Delete definition\",\n disabled: inUse,\n remove: () => state.removeDefinition(node.key),\n };\n }\n if (slotName === \"else\") {\n return simpleRemove(\"Remove else\", () =>\n state.removeElse(node.path.slice(0, -1)),\n );\n }\n return simpleRemove(\"Delete property\", () => state.deleteProperty(node.path));\n}\n\n// An always-enabled remove descriptor (the common case).\nfunction simpleRemove(label: string, remove: () => void): RemoveDescriptor {\n return { label, disabled: false, remove };\n}\n\n// The destructive action for a row.\nfunction RemoveAction({\n node,\n state,\n inUseDefs,\n}: {\n node: PropertyNode;\n state: DesignerState;\n inUseDefs: Set<string>;\n}): React.ReactElement | null {\n const desc = removeDescriptor(node, state, inUseDefs);\n if (!desc) return null;\n return (\n <ActionButton\n label={desc.label}\n tone=\"destructive\"\n disabled={desc.disabled}\n onAct={desc.remove}\n >\n <Trash2 />\n </ActionButton>\n );\n}\n\n// Hover-revealed row actions (move / add / delete), gated by editability.\n// Reorder is suppressed for conditionals and then/else slots (positional).\nconst EMPTY_SET: Set<string> = new Set();\n\nfunction RowActions({\n node,\n state,\n editable,\n canAddHere,\n inUseDefs = EMPTY_SET,\n}: {\n node: PropertyNode;\n state: DesignerState;\n editable: boolean;\n canAddHere: boolean;\n inUseDefs?: Set<string>;\n}): React.ReactElement {\n const reorderable =\n editable &&\n node.slotKind !== \"conditional\" &&\n node.slotKind !== \"definition\";\n return (\n <>\n {reorderable && <MoveActions node={node} state={state} />}\n <AddActions\n node={node}\n state={state}\n editable={editable}\n canAddHere={canAddHere}\n />\n {editable && (\n <RemoveAction node={node} state={state} inUseDefs={inUseDefs} />\n )}\n </>\n );\n}\n\nfunction PropertyRow({\n node,\n state,\n depth,\n inUseDefs = EMPTY_SET,\n}: {\n node: PropertyNode;\n state: DesignerState;\n depth: number;\n inUseDefs?: Set<string>;\n}): React.ReactElement {\n const selected = samePath(state.selection, node.path);\n const [editing, setEditing] = useState(false);\n\n // Scoped/readOnly gating: a fixed property shows no edit affordances (and a\n // lock indicator); \"add child\" follows canAddChild for containers. Fields\n // inside a $ref (node.readOnly) are never editable -- flagged at build time,\n // so no per-row schema walk.\n const editable = !node.readOnly && state.canEditProperty(node.path);\n // Branches and oneOf unions accept children too: a oneOf takes branches,\n // a branch takes properties, object/array take properties.\n const isBranch = node.slotKind === \"branch\";\n const isConditional = node.slotKind === \"conditional\";\n const isDefinition = node.kind === \"definition\";\n // Definitions are document-level: editability is the lock, not path scoping.\n const editableName = isDefinition ? !state.capabilities.locked : editable;\n const canAddHere = canAddChildHere(node, state, isConditional);\n const showActions = editableName || canAddHere;\n\n const startRename = (e: React.MouseEvent) => {\n e.stopPropagation();\n // Branches and conditionals have no key to rename -- a branch's label is its\n // title (inspector); a conditional's label is derived from its `if`.\n if (editableName && !isBranch && !isConditional) setEditing(true);\n };\n\n const commitRename = (next: string) => {\n setEditing(false);\n if (isDefinition) state.renameDefinition(node.key, next);\n else state.renameProperty(node.path, next);\n };\n\n return (\n <>\n <div\n className={cn(\n \"group/row relative flex items-center gap-2 px-3 py-2 cursor-pointer\",\n selected && \"bg-accent\",\n )}\n style={{ paddingLeft: 12 + depth * 16 }}\n onClick={() => state.select(node.path)}\n >\n {editing ? (\n <NameEditor\n initial={node.key}\n onCommit={commitRename}\n onCancel={() => setEditing(false)}\n />\n ) : (\n <RowLabel\n node={node}\n editable={editableName}\n onStartRename={startRename}\n />\n )}\n {showActions && !editing && (\n // Absolutely positioned so the buttons do not reserve row width at\n // rest -- the name/type use the full row. The actions overlay the\n // right edge; each button reveals on hover via revealOnHover. The\n // background is applied only on hover so it does not cover the type\n // label at rest (accent for the selected row, background otherwise).\n <span\n className={cn(\n \"absolute right-2 flex gap-0.5 rounded-md pl-2\",\n selected\n ? \"group-hover/row:bg-accent\"\n : \"group-hover/row:bg-background\",\n )}\n >\n <RowActions\n node={node}\n state={state}\n editable={editableName}\n canAddHere={canAddHere}\n inUseDefs={inUseDefs}\n />\n </span>\n )}\n </div>\n {node.children.map((child) => (\n <PropertyRow\n key={pathKey(child.path)}\n node={child}\n state={state}\n depth={depth + 1}\n inUseDefs={inUseDefs}\n />\n ))}\n </>\n );\n}\n","/**\n * PreviewPane -- the center pane. Tabs: Form (live rendered form), JSON Schema\n * (the data model), and UI Schema (the presentation map). The form is the\n * universal sanity check; the two JSON views are read-only.\n *\n * Additional renderers (table, tree, detail) plug in as more tabs without\n * touching this contract -- each takes the same schema + uiSchema + data.\n */\n\nimport React, { useMemo, useState } from \"react\";\nimport {\n Tabs,\n TabsList,\n TabsTrigger,\n TabsContent,\n TabsSeparator,\n} from \"@petrarca/sonnet-ui\";\nimport { JsonSchemaFormRenderer } from \"@petrarca/sonnet-forms\";\nimport {\n extractSchemaDefaults,\n type JsonSchema,\n} from \"@petrarca/sonnet-core/schema\";\nimport { embedUiSchema } from \"../model/embed\";\nimport type { DesignerState } from \"../hooks/useDesignerState\";\nimport type { UiSchemaMap } from \"../model/mutate\";\nimport { TablePreview } from \"./TablePreview\";\nimport { FormLayoutDesigner } from \"../designers/FormLayoutDesigner\";\nimport { CapabilitiesPanel } from \"./CapabilitiesPanel\";\nimport { SchemaSourcePanel } from \"./SchemaSourcePanel\";\nimport type { SchemaDesignerCapabilities } from \"../capabilities\";\n\n// Validate a parsed value is a usable root JSON Schema.\nfunction validateRootSchema(parsed: unknown): string | null {\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n return \"Schema must be a JSON object.\";\n }\n const s = parsed as Record<string, unknown>;\n if (s.type !== \"object\") return 'Root schema must have type: \"object\".';\n if (typeof s.properties !== \"object\" || s.properties === null) {\n return \"Root schema must have a properties object.\";\n }\n return null;\n}\n\n// Validate a parsed value is a usable UI Schema map (object of entries).\nfunction validateUiSchema(parsed: unknown): string | null {\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n return \"UI Schema must be a JSON object.\";\n }\n return null;\n}\n\nexport interface PreviewPaneProps {\n state: DesignerState;\n /** The current (editable) capabilities profile. */\n capabilities?: SchemaDesignerCapabilities;\n /** Apply an edited profile (from the Capabilities tab). */\n onCapabilitiesChange?: (next: SchemaDesignerCapabilities) => void;\n}\n\ninterface TabFlags {\n isFull: boolean;\n showForm: boolean;\n showTable: boolean;\n showJson: boolean;\n showCapabilities: boolean;\n}\n\nfunction PreviewTabList({ flags }: { flags: TabFlags }): React.ReactElement {\n return (\n <TabsList className=\"mb-3\">\n {flags.showForm && <TabsTrigger value=\"form\">Form</TabsTrigger>}\n {flags.isFull && flags.showForm && (\n <TabsTrigger value=\"layout\">Form Layout</TabsTrigger>\n )}\n {flags.showTable && <TabsTrigger value=\"table\">Table</TabsTrigger>}\n <TabsSeparator />\n {flags.showJson && <TabsTrigger value=\"schema\">JSON Schema</TabsTrigger>}\n {flags.isFull && <TabsTrigger value=\"ui\">UI Schema</TabsTrigger>}\n {flags.isFull && <TabsTrigger value=\"combined\">Combined</TabsTrigger>}\n {flags.showCapabilities && (\n <>\n <TabsSeparator />\n <TabsTrigger value=\"capabilities\">Capabilities</TabsTrigger>\n </>\n )}\n </TabsList>\n );\n}\n\nexport function PreviewPane({\n state,\n capabilities,\n onCapabilitiesChange,\n}: PreviewPaneProps): React.ReactElement {\n const { schema, uiSchema } = state;\n const caps = state.capabilities;\n const flags: TabFlags = {\n isFull: caps.mode === \"full\",\n showForm: caps.previews.includes(\"form\"),\n showTable: caps.previews.includes(\"table\"),\n showJson: caps.previews.includes(\"json\"),\n showCapabilities: caps.showCapabilities,\n };\n\n const [data, setData] = useState<Record<string, unknown>>(() =>\n extractSchemaDefaults(schema),\n );\n\n const schemaText = useMemo(() => JSON.stringify(schema, null, 2), [schema]);\n const uiSchemaText = useMemo(\n () => JSON.stringify(uiSchema ?? {}, null, 2),\n [uiSchema],\n );\n const embeddedText = useMemo(\n () => JSON.stringify(embedUiSchema(schema, uiSchema ?? {}), null, 2),\n [schema, uiSchema],\n );\n\n // Default to the first available tab so it always resolves to something shown.\n const defaultTab = flags.showForm\n ? \"form\"\n : flags.showTable\n ? \"table\"\n : \"schema\";\n\n return (\n <Tabs defaultValue={defaultTab} className=\"flex flex-col h-full min-h-0\">\n <PreviewTabList flags={flags} />\n {flags.showForm && (\n <TabsContent value=\"form\" className=\"flex-1 min-h-0 overflow-auto\">\n <JsonSchemaFormRenderer\n schema={schema}\n data={data}\n uiSchema={uiSchema}\n onChange={setData}\n showActions={false}\n showExtraProperties={false}\n />\n </TabsContent>\n )}\n {flags.isFull && flags.showForm && (\n <TabsContent value=\"layout\" className=\"flex-1 min-h-0 overflow-hidden\">\n <FormLayoutDesigner state={state} />\n </TabsContent>\n )}\n {flags.showTable && (\n <TabsContent value=\"table\" className=\"flex-1 min-h-0 overflow-auto\">\n <TablePreview schema={schema} />\n </TabsContent>\n )}\n <SourceTabPanels\n state={state}\n flags={flags}\n schemaText={schemaText}\n uiSchemaText={uiSchemaText}\n embeddedText={embeddedText}\n capabilities={capabilities}\n onCapabilitiesChange={onCapabilitiesChange}\n />\n </Tabs>\n );\n}\n\n// The source-artifact panels (JSON Schema / UI Schema / Combined) plus the\n// optional Capabilities editor. Split out to keep PreviewPane's complexity low.\nfunction SourceTabPanels({\n state,\n flags,\n schemaText,\n uiSchemaText,\n embeddedText,\n capabilities,\n onCapabilitiesChange,\n}: {\n state: DesignerState;\n flags: TabFlags;\n schemaText: string;\n uiSchemaText: string;\n embeddedText: string;\n capabilities?: SchemaDesignerCapabilities;\n onCapabilitiesChange?: (next: SchemaDesignerCapabilities) => void;\n}): React.ReactElement {\n // Wholesale source replacement bypasses per-path scoping, so it is allowed\n // only when the profile is fully editable (neither locked nor scoped).\n const canEditSource =\n !state.capabilities.locked && !state.capabilities.scoped;\n\n return (\n <>\n {flags.showJson && (\n <TabsContent value=\"schema\" className=\"flex-1 min-h-0 relative\">\n <SchemaSourcePanel\n value={schemaText}\n editable={canEditSource}\n validate={validateRootSchema}\n onApply={(parsed) => state.replaceSchema(parsed as JsonSchema)}\n />\n </TabsContent>\n )}\n {flags.isFull && (\n <TabsContent value=\"ui\" className=\"flex-1 min-h-0 relative\">\n <SchemaSourcePanel\n value={uiSchemaText}\n editable={canEditSource}\n validate={validateUiSchema}\n onApply={(parsed) => state.replaceUiSchema(parsed as UiSchemaMap)}\n />\n </TabsContent>\n )}\n {flags.isFull && (\n <TabsContent value=\"combined\" className=\"flex-1 min-h-0 relative\">\n <SchemaSourcePanel\n value={embeddedText}\n editable={false}\n onApply={() => {}}\n />\n </TabsContent>\n )}\n {flags.showCapabilities && (\n <TabsContent value=\"capabilities\" className=\"flex-1 min-h-0 relative\">\n <CapabilitiesPanel\n capabilities={capabilities}\n onApply={onCapabilitiesChange}\n />\n </TabsContent>\n )}\n </>\n );\n}\n","/**\n * TablePreview -- renders the schema as an EntityTable using auto-generated\n * sample rows. Columns and cells come from the resolver's defaults plus any\n * x-ui-column / x-ui-cell hints embedded in the schema.\n */\n\nimport React, { useMemo } from \"react\";\nimport { EntityTable, type TableUiSchema } from \"@petrarca/sonnet-ui\";\nimport { toPageResult } from \"@petrarca/sonnet-core\";\nimport type { JsonSchema } from \"@petrarca/sonnet-core/schema\";\nimport { sampleRows } from \"./sampleRows\";\n\nexport interface TablePreviewProps {\n schema: JsonSchema;\n uiSchema?: TableUiSchema;\n}\n\nexport function TablePreview({\n schema,\n uiSchema,\n}: TablePreviewProps): React.ReactElement {\n const data = useMemo(() => toPageResult(sampleRows(schema)), [schema]);\n\n return (\n <EntityTable\n schema={schema}\n uiSchema={uiSchema}\n data={data}\n isLoading={false}\n isError={false}\n entityLabel=\"rows\"\n />\n );\n}\n","/**\n * Generate plausible sample rows from a JsonSchema, for the table preview.\n *\n * Pure. Produces a few rows with a value per top-level property, chosen by\n * type / format / enum so the table shows realistic content. Nested objects and\n * arrays get simple placeholders (tables typically show scalar columns; the\n * cell renderer decides how to display the rest).\n */\n\nimport type {\n JsonSchema,\n JsonSchemaProperty,\n} from \"@petrarca/sonnet-core/schema\";\n\ntype Row = Record<string, unknown>;\n\nfunction sampleString(\n prop: JsonSchemaProperty,\n key: string,\n i: number,\n): string {\n switch (prop.format) {\n case \"email\":\n return `user${i + 1}@example.com`;\n case \"date\":\n return `2024-0${(i % 9) + 1}-15`;\n case \"date-time\":\n return `2024-0${(i % 9) + 1}-15T09:30:00Z`;\n case \"uri\":\n case \"url\":\n return `https://example.com/${key}/${i + 1}`;\n case \"uuid\":\n return `00000000-0000-4000-8000-00000000000${i + 1}`;\n default:\n return `${titleCase(key)} ${i + 1}`;\n }\n}\n\nfunction titleCase(key: string): string {\n const s = key.replace(/[_-]+/g, \" \").trim();\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n\nfunction sampleValue(\n prop: JsonSchemaProperty,\n key: string,\n i: number,\n): unknown {\n if (Array.isArray(prop.enum) && prop.enum.length > 0) {\n return prop.enum[i % prop.enum.length];\n }\n switch (prop.type) {\n case \"string\":\n return sampleString(prop, key, i);\n case \"number\":\n return Math.round((i + 1) * 1.5 * 100) / 100;\n case \"integer\":\n return i + 1;\n case \"boolean\":\n return i % 2 === 0;\n case \"array\":\n return [];\n case \"object\":\n return {};\n default:\n return null;\n }\n}\n\n/** Build `count` sample rows for a schema's top-level properties. */\nexport function sampleRows(schema: JsonSchema, count = 3): Row[] {\n const entries = Object.entries(schema.properties);\n return Array.from({ length: count }, (_, i) => {\n const row: Row = {};\n for (const [key, prop] of entries) {\n row[key] = sampleValue(prop, key, i);\n }\n return row;\n });\n}\n","/**\n * FormLayoutDesigner -- visual editor for the form's row layout\n * (x-ui-layout.rows). Two columns: an \"Available\" pool of unassigned top-level\n * properties (left) and the row designer (right). Properties are dragged\n * (native HTML5 DnD) between the pool and rows; rows can be added, removed,\n * reordered, and given a CSS grid-template-columns value.\n *\n * This is a bespoke visual designer (not a meta-schema form) -- the first of a\n * planned family of \"*Designer\" surfaces for spatial authoring tasks.\n */\n\nimport React, { useMemo, useState } from \"react\";\nimport { cn } from \"@petrarca/sonnet-core\";\nimport { Input, IconButton, Button } from \"@petrarca/sonnet-ui\";\nimport { FormSelect, JsonSchemaFormRenderer } from \"@petrarca/sonnet-forms\";\nimport {\n Plus,\n Trash2,\n ChevronUp,\n ChevronDown,\n ChevronLeft,\n ChevronRight,\n GripVertical,\n} from \"lucide-react\";\nimport {\n buildLayoutMetaSchema,\n layoutToValues,\n valuesToLayout,\n type LayoutFormValues,\n} from \"../inspector/layoutMetaSchemas\";\nimport type {\n JsonSchema,\n JsonSchemaProperty,\n UILayoutConfig,\n UILayoutRowConfig,\n UILayoutGroupConfig,\n WidthToken,\n} from \"@petrarca/sonnet-core/schema\";\nimport type { DesignerState } from \"../hooks/useDesignerState\";\nimport { layoutScopes, type LayoutScope } from \"../model/view\";\nimport { RuleFields, type ScopeOption } from \"../inspector/RuleFields\";\nimport { VISIBILITY_EFFECT_OPTIONS } from \"../inspector/ruleEffects\";\nimport {\n getProperty,\n pathKey,\n parsePathKey,\n type PropertyPath,\n} from \"../model/paths\";\n\nexport interface FormLayoutDesignerProps {\n state: DesignerState;\n}\n\nconst DRAG_MIME = \"application/x-sonnet-property\";\n\n// Ordered keys of a properties map, honoring x-ui-order.\nfunction orderedKeysOf(\n properties: Record<string, JsonSchemaProperty>,\n order: string[] | undefined,\n): string[] {\n const keys = Object.keys(properties);\n if (!order || order.length === 0) return keys;\n const inOrder = order.filter((k) => k in properties);\n return [...inOrder, ...keys.filter((k) => !inOrder.includes(k))];\n}\n\n// Resolve a scope path to its editable keys + current rows. Root (path []) uses\n// the schema + uiSchema[\"x-ui-layout\"]; a property scope uses the object (or\n// array items) property and its x-ui-layout.\n// The container property for a scope path: the object, or an array's items.\nfunction scopeTarget(\n schema: JsonSchema,\n scopePath: PropertyPath,\n): JsonSchemaProperty | undefined {\n const prop = getProperty(schema, scopePath);\n if (!prop) return undefined;\n return prop.type === \"array\" ? prop.items : prop;\n}\n\ninterface ResolvedScope {\n keys: string[];\n /** The scope's properties, for the types a condition scope needs. */\n props: Record<string, JsonSchemaProperty>;\n rows: UILayoutRowConfig[];\n groups: UILayoutGroupConfig[];\n layout: UILayoutConfig | undefined;\n /** True when the scope is an array property (scalar options apply). */\n isArray: boolean;\n}\n\n// The container schema for a scope and the layout config attached to it.\n// Root reads the uiSchema; a nested scope reads the property (array -> items).\nfunction scopeContainer(\n schema: JsonSchema,\n uiSchema: DesignerState[\"uiSchema\"],\n scopePath: PropertyPath,\n): {\n container: JsonSchema | JsonSchemaProperty | undefined;\n layout: UILayoutConfig | undefined;\n} {\n if (scopePath.length === 0) {\n return {\n container: schema,\n layout: uiSchema[\"x-ui-layout\"] as UILayoutConfig | undefined,\n };\n }\n const container = scopeTarget(schema, scopePath);\n return {\n container,\n layout: container?.[\"x-ui-layout\"] as UILayoutConfig | undefined,\n };\n}\n\nfunction resolveScope(\n schema: JsonSchema,\n uiSchema: DesignerState[\"uiSchema\"],\n scopePath: PropertyPath,\n): ResolvedScope {\n const { container, layout } = scopeContainer(schema, uiSchema, scopePath);\n const props = container?.properties ?? {};\n return {\n keys: orderedKeysOf(props, container?.[\"x-ui-order\"]),\n props,\n rows: layout?.rows ?? [],\n groups: layout?.groups ?? [],\n layout,\n isArray: scopeIsArray(schema, scopePath),\n };\n}\n\n// The rows the designer is editing, plus every field already claimed by the\n// layout. `assigned` spans all groups so the Available pool stays correct no\n// matter which group is active.\n// Whether any of these rows already claims the property.\nfunction ownsField(rows: UILayoutRowConfig[], key: string): boolean {\n return rows.some((r) => r.fields.includes(key));\n}\n\nfunction rowTarget(\n grouped: boolean,\n groups: UILayoutGroupConfig[],\n groupIndex: number,\n flatRows: UILayoutRowConfig[],\n): { rows: UILayoutRowConfig[]; assigned: Set<string> } {\n const rows = grouped ? (groups[groupIndex]?.rows ?? []) : flatRows;\n const all = grouped ? groups.flatMap((t) => t.rows) : flatRows;\n return { rows, assigned: new Set(all.flatMap((r) => r.fields)) };\n}\n\n// Whether the scope path points at an array property.\nfunction scopeIsArray(schema: JsonSchema, scopePath: PropertyPath): boolean {\n if (scopePath.length === 0) return false;\n return getProperty(schema, scopePath)?.type === \"array\";\n}\n\n// Array item layout options (direction/gap/labels/compact), laid out on one\n// row via the renderer's own x-ui-layout so it matches form styling.\nconst SCALAR_META_SCHEMA = buildLayoutMetaSchema();\nconst SCALAR_UI_SCHEMA = {\n \"x-ui-layout\": {\n labelPlacement: \"start\" as const,\n // Flow row: controls sit left-to-right at their natural width (label hugs\n // control via horizontal labelPlacement), wrapping as needed.\n rows: [\n {\n fields: [\"direction\", \"gap\", \"labels\", \"compact\"],\n arrange: \"flow\" as const,\n gap: 16,\n },\n ],\n compact: true,\n },\n // Per-field widths for the toolbar. Top-level fields take their per-field\n // uiSchema directly under the field name. Direction (a select) gets more\n // room; the numeric Gap input stays narrow.\n direction: { \"x-ui-width\": \"lg\" as const },\n gap: { \"x-ui-width\": \"sm\" as const },\n};\n\nfunction scalarsFrom(\n values: LayoutFormValues,\n): Pick<UILayoutConfig, \"direction\" | \"gap\" | \"labels\" | \"compact\"> {\n const full = valuesToLayout(values, undefined) ?? {};\n return {\n direction: full.direction,\n gap: full.gap,\n labels: full.labels,\n compact: full.compact,\n };\n}\n\n// The array item layout options bar -- a horizontally-laid-out rendered form.\nfunction ArrayItemLayoutBar({\n layout,\n readOnly,\n onChange,\n}: {\n layout: UILayoutConfig | undefined;\n readOnly: boolean;\n onChange: (\n opts: Pick<UILayoutConfig, \"direction\" | \"gap\" | \"labels\" | \"compact\">,\n ) => void;\n}): React.ReactElement {\n return (\n <div className=\"shrink-0 rounded-lg border p-3\">\n <p className=\"heading-meta mb-2\">Array item layout</p>\n <JsonSchemaFormRenderer\n schema={SCALAR_META_SCHEMA}\n uiSchema={SCALAR_UI_SCHEMA}\n data={layoutToValues(layout) as unknown as Record<string, unknown>}\n onChange={(data) => onChange(scalarsFrom(data as LayoutFormValues))}\n showActions={false}\n showExtraProperties={false}\n readOnly={readOnly}\n />\n </div>\n );\n}\n\nexport function FormLayoutDesigner({\n state,\n}: FormLayoutDesignerProps): React.ReactElement {\n const scopes = useMemo(() => layoutScopes(state.schema), [state.schema]);\n const [scopePath, setScopePath] = useState<PropertyPath>([]);\n\n // Fall back to root if the selected scope no longer exists.\n const scopeKey = pathKey(scopePath);\n const activeScope =\n scopes.find((s) => pathKey(s.path) === scopeKey) ?? scopes[0];\n const effectivePath = activeScope.path;\n\n const {\n keys: allKeys,\n props: scopeProps,\n rows: flatRows,\n groups,\n layout,\n isArray,\n } = resolveScope(state.schema, state.uiSchema, effectivePath);\n\n // Groups mode is implied by the presence of group definitions.\n const grouped = groups.length > 0;\n const [activeGroup, setActiveGroup] = useState(0);\n // Clamp when groups shrink (or the scope changes) so the index stays valid.\n const groupIndex = grouped ? Math.min(activeGroup, groups.length - 1) : 0;\n\n // Every handler below works on this single array, in either mode.\n const { rows, assigned } = rowTarget(grouped, groups, groupIndex, flatRows);\n const available = allKeys.filter((k) => !assigned.has(k));\n // Properties held by a group other than the active one. They are offered in the\n // pool (marked) so a property can be moved between groups without first\n // navigating to the group that currently holds it.\n const inOtherGroups = grouped\n ? allKeys.filter((k) => assigned.has(k) && !ownsField(rows, k))\n : [];\n\n const [dragKey, setDragKey] = useState<string | null>(null);\n\n const commit = makeCommitRows(state, effectivePath, grouped, groupIndex);\n\n // Move a property into row `rowIndex` (or to the pool when rowIndex is null),\n // removing it from wherever it currently is. Empty rows are kept (they are\n // valid drop targets; the user removes rows explicitly).\n const place = (key: string, rowIndex: number | null) => {\n if (!key) return;\n // In groups mode a property may currently sit in a *different* group, so the\n // model op strips it across all groups before placing it here.\n if (grouped) {\n state.placeFieldInGroup(\n effectivePath,\n key,\n rowIndex === null ? null : { groupIndex, rowIndex },\n );\n return;\n }\n const next = rows.map((r) => ({\n ...r,\n fields: r.fields.filter((f) => f !== key),\n }));\n if (rowIndex !== null && next[rowIndex]) {\n next[rowIndex] = {\n ...next[rowIndex],\n fields: [...next[rowIndex].fields, key],\n };\n }\n commit(next);\n };\n\n const addRow = () => commit([...rows, { fields: [] }]);\n const removeRow = (i: number) => commit(rows.filter((_, idx) => idx !== i));\n const moveRow = (i: number, dir: -1 | 1) => {\n const j = i + dir;\n if (j < 0 || j >= rows.length) return;\n const next = [...rows];\n [next[i], next[j]] = [next[j], next[i]];\n commit(next);\n };\n const setColumns = (i: number, columns: string) => {\n const next = rows.map((r, idx) =>\n idx === i ? { ...r, columns: columns.trim() ? columns : undefined } : r,\n );\n commit(next);\n };\n const setGroup = (i: number, group: string) => {\n const next = rows.map((r, idx) =>\n idx === i ? { ...r, group: group.trim() ? group : undefined } : r,\n );\n commit(next);\n };\n const setArrange = (i: number, arrange: \"grid\" | \"flow\") => {\n const next: UILayoutRowConfig[] = rows.map((r, idx) =>\n // \"grid\" is the default -- omit it to keep the config clean.\n idx === i\n ? { ...r, arrange: arrange === \"flow\" ? (\"flow\" as const) : undefined }\n : r,\n );\n commit(next);\n };\n const setWidth = (i: number, cell: number, width: WidthToken) => {\n const next = rows.map((r, idx) => {\n if (idx !== i) return r;\n const widths = [...(r.widths ?? [])];\n while (widths.length < r.fields.length) widths.push(\"full\");\n widths[cell] = width;\n // Drop the array entirely when every cell is the default \"full\".\n const allFull = widths.every((w) => w === \"full\");\n return { ...r, widths: allFull ? undefined : widths };\n });\n commit(next);\n };\n\n // Condition scopes for a group rule: every property of this scope, with its\n // type so the comparand is written correctly (a boolean needs true, not \"true\").\n const scopeOptions = allKeys.map((k) => ({\n pointer: `/${k}`,\n type: scopeProps[k]?.type,\n }));\n\n const groupOps = makeGroupOps(\n state,\n effectivePath,\n groups.length,\n groupIndex,\n setActiveGroup,\n );\n const readOnly = state.readOnly;\n\n return (\n <div className=\"flex flex-col gap-3 h-full min-h-0\">\n <LayoutToolbar\n scopes={scopes}\n scopePath={effectivePath}\n onScope={setScopePath}\n grouped={grouped}\n variant={layout?.variant}\n readOnly={readOnly}\n onMode={groupOps.setMode}\n onVariant={(v) => state.setScopedLayoutVariant(effectivePath, v)}\n />\n\n {grouped && (\n <>\n <GroupBar\n groups={groups}\n activeIndex={groupIndex}\n readOnly={readOnly}\n onSelect={setActiveGroup}\n onAdd={groupOps.add}\n onRename={groupOps.rename}\n onRemove={groupOps.remove}\n onMove={groupOps.move}\n />\n <GroupSettings\n group={groups[groupIndex]}\n scopes={scopeOptions}\n readOnly={readOnly}\n onRule={(rule) =>\n state.setLayoutGroupRule(effectivePath, groupIndex, rule)\n }\n />\n </>\n )}\n\n {/* Array-only layout options in a single compact row. The renderer honors\n these only for array-of-object layout, so they show only when the\n scope is an array. */}\n {isArray && (\n <ArrayItemLayoutBar\n layout={layout}\n readOnly={readOnly}\n onChange={(opts) => state.setScopedLayoutOptions(effectivePath, opts)}\n />\n )}\n\n <div className=\"flex gap-4 flex-1 min-h-0\">\n <AvailablePool\n available={available}\n inOtherGroups={inOtherGroups}\n grouped={grouped}\n readOnly={readOnly}\n dragActive={!!dragKey}\n onDropToPool={(key) => place(key, null)}\n onDragStartKey={setDragKey}\n onDragEndKey={() => setDragKey(null)}\n />\n\n {/* Row designer */}\n <div className=\"flex-1 min-w-0 flex flex-col min-h-0\">\n <div className=\"mb-2 flex items-center gap-2\">\n <p className=\"heading-meta\">\n {rowsHeading(grouped, groups, groupIndex)}\n </p>\n {!readOnly && (\n <span className=\"ml-auto\">\n <Button\n size=\"sm\"\n variant=\"outline\"\n className=\"gap-1.5\"\n onClick={addRow}\n >\n <Plus className=\"h-4 w-4\" />\n Add row\n </Button>\n </span>\n )}\n </div>\n <div className=\"flex-1 min-h-0 overflow-auto space-y-3\">\n {rows.length === 0 ? (\n <p className=\"text-sm text-muted-foreground\">\n No rows yet. Add a row, then drag properties into it.\n </p>\n ) : (\n rows.map((row, i) => (\n <RowCard\n key={i}\n row={row}\n index={i}\n total={rows.length}\n readOnly={readOnly}\n dragActive={!!dragKey}\n onDropKey={(key) => place(key ?? dragKey ?? \"\", i)}\n onRemoveKey={(key) => place(key, null)}\n onDragStartKey={(key) => setDragKey(key)}\n onDragEndKey={() => setDragKey(null)}\n onMoveUp={() => moveRow(i, -1)}\n onMoveDown={() => moveRow(i, 1)}\n onDelete={() => removeRow(i)}\n onColumns={(v) => setColumns(i, v)}\n onGroup={(v) => setGroup(i, v)}\n onWidth={(cell, w) => setWidth(i, cell, w)}\n onArrange={(a) => setArrange(i, a)}\n />\n ))\n )}\n </div>\n </div>\n </div>\n </div>\n );\n}\n\n// Row writes go to the active group in groups mode, or the scope's flat list.\nfunction makeCommitRows(\n state: DesignerState,\n scopePath: PropertyPath,\n grouped: boolean,\n groupIndex: number,\n): (rows: UILayoutRowConfig[]) => void {\n if (grouped) {\n return (rows) => state.setScopedGroupRows(scopePath, groupIndex, rows);\n }\n return (rows) => state.setScopedLayoutRows(scopePath, rows);\n}\n\n// Heading for the row editor, naming the group being edited in groups mode.\nfunction rowsHeading(\n grouped: boolean,\n groups: UILayoutGroupConfig[],\n groupIndex: number,\n): string {\n if (!grouped) return \"Rows\";\n return `Rows in ${groups[groupIndex]?.label ?? \"\"}`;\n}\n\n// The group presentations offered by the designer. The renderer resolves any\n// variant to a template, so a consumer's custom presentation is authored in\n// the UI Schema source tab rather than listed here.\nconst VARIANT_OPTIONS = [\n { value: \"tabs\", label: \"Tabs\" },\n { value: \"stepper\", label: \"Stepper\" },\n { value: \"sections\", label: \"Sections\" },\n];\n\ninterface GroupOps {\n add: () => void;\n rename: (index: number, label: string) => void;\n remove: (index: number) => void;\n move: (index: number, direction: -1 | 1) => void;\n setMode: (mode: \"rows\" | \"groups\") => void;\n}\n\n// Tab-level operations: the model owns the semantics (see mutate.ts); this only\n// keeps the active index pointing somewhere sensible afterwards.\nfunction makeGroupOps(\n state: DesignerState,\n scopePath: PropertyPath,\n groupCount: number,\n activeIndex: number,\n setActiveGroup: React.Dispatch<React.SetStateAction<number>>,\n): GroupOps {\n return {\n add: () => {\n state.addLayoutGroup(scopePath);\n setActiveGroup(groupCount);\n },\n rename: (index, label) => state.renameLayoutGroup(scopePath, index, label),\n move: (index, direction) => {\n state.moveLayoutGroup(scopePath, index, direction);\n // Follow the group that moved, so the row editor keeps showing it.\n if (index === activeIndex) setActiveGroup(activeIndex + direction);\n },\n remove: (index) => {\n state.removeLayoutGroup(scopePath, index);\n // Clamp from the effective index, not raw state, so a stale-high value\n // (after a scope switch) cannot land on the wrong group.\n if (index <= activeIndex && activeIndex > 0)\n setActiveGroup(activeIndex - 1);\n },\n setMode: (mode) => {\n state.setScopedLayoutMode(scopePath, mode);\n setActiveGroup(0);\n },\n };\n}\n\n// The pool of properties not placed in the active rows. In groups mode it also\n// lists properties held by other groups, so one can be moved across without\n// first navigating to the group that owns it.\nfunction AvailablePool({\n available,\n inOtherGroups,\n grouped,\n readOnly,\n dragActive,\n onDropToPool,\n onDragStartKey,\n onDragEndKey,\n}: {\n available: string[];\n inOtherGroups: string[];\n grouped: boolean;\n readOnly: boolean;\n dragActive: boolean;\n onDropToPool: (key: string) => void;\n onDragStartKey: (key: string) => void;\n onDragEndKey: () => void;\n}): React.ReactElement {\n const empty = available.length === 0 && inOtherGroups.length === 0;\n return (\n <div className=\"w-56 shrink-0 flex flex-col min-h-0\">\n <p className=\"heading-meta mb-2\">Available</p>\n <div\n className=\"flex-1 min-h-0 overflow-auto rounded-lg border p-2 space-y-1 bg-muted/20\"\n onDragOver={(e) => {\n if (dragActive) e.preventDefault();\n }}\n onDrop={(e) => {\n const key = e.dataTransfer.getData(DRAG_MIME);\n if (key) onDropToPool(key);\n }}\n >\n {empty ? (\n <p className=\"text-xs text-muted-foreground p-1\">\n {grouped\n ? \"All properties are placed in groups.\"\n : \"All properties are placed in rows.\"}\n </p>\n ) : (\n available.map((key) => (\n <Chip\n key={key}\n label={key}\n readOnly={readOnly}\n onDragStart={() => onDragStartKey(key)}\n onDragEnd={onDragEndKey}\n />\n ))\n )}\n {inOtherGroups.length > 0 && (\n <>\n <p className=\"pt-2 pb-1 text-[11px] uppercase tracking-wide text-muted-foreground/70\">\n In other groups\n </p>\n {inOtherGroups.map((key) => (\n <Chip\n key={key}\n label={key}\n readOnly={readOnly}\n muted\n onDragStart={() => onDragStartKey(key)}\n onDragEnd={onDragEndKey}\n />\n ))}\n </>\n )}\n </div>\n <p className=\"text-xs text-muted-foreground mt-2\">\n {grouped\n ? \"Drag from \\u201cIn other groups\\u201d to move a property here. Unplaced properties render below the groups.\"\n : \"Unplaced properties render stacked below the rows.\"}\n </p>\n </div>\n );\n}\n\n// Scope selector plus the grouping controls (rows/groups and, when grouped, the\n// presentation variant).\nfunction LayoutToolbar({\n scopes,\n scopePath,\n onScope,\n grouped,\n variant,\n readOnly,\n onMode,\n onVariant,\n}: {\n scopes: LayoutScope[];\n scopePath: PropertyPath;\n onScope: (path: PropertyPath) => void;\n grouped: boolean;\n variant: UILayoutConfig[\"variant\"];\n readOnly: boolean;\n onMode: (mode: \"rows\" | \"groups\") => void;\n onVariant: (variant: UILayoutConfig[\"variant\"]) => void;\n}): React.ReactElement {\n return (\n <div className=\"flex items-center gap-2 shrink-0\">\n <label className=\"heading-meta\">Scope</label>\n <div className=\"w-64\">\n <FormSelect\n id=\"layout-scope\"\n name=\"scope\"\n value={pathKey(scopePath)}\n options={scopes.map((s) => ({\n value: pathKey(s.path),\n label: s.label,\n }))}\n onChange={(v: string | null) => onScope(v ? parsePathKey(v) : [])}\n clearable={false}\n />\n </div>\n <label className=\"heading-meta ml-4\">Group by</label>\n <ModeToggle\n mode={grouped ? \"groups\" : \"rows\"}\n readOnly={readOnly}\n onChange={onMode}\n />\n {grouped && (\n <>\n <label className=\"heading-meta ml-4\">Show as</label>\n <div className=\"w-36\">\n <FormSelect\n id=\"layout-variant\"\n name=\"variant\"\n value={variant ?? \"tabs\"}\n options={VARIANT_OPTIONS}\n onChange={(v) =>\n onVariant((v as UILayoutConfig[\"variant\"]) ?? \"tabs\")\n }\n clearable={false}\n disabled={readOnly}\n />\n </div>\n </>\n )}\n </div>\n );\n}\n\n// Rows / Tabs switch. Tabs group rows under labels; the data stays flat.\nfunction ModeToggle({\n mode,\n readOnly,\n onChange,\n}: {\n mode: \"rows\" | \"groups\";\n readOnly: boolean;\n onChange: (mode: \"rows\" | \"groups\") => void;\n}): React.ReactElement {\n return (\n <div className=\"inline-flex rounded-md border p-0.5\" aria-label=\"Group by\">\n {([\"rows\", \"groups\"] as const).map((m) => (\n <button\n key={m}\n type=\"button\"\n disabled={readOnly}\n // aria-pressed carries the active state; the visual highlight alone\n // would not reach assistive tech.\n aria-pressed={mode === m}\n onClick={() => onChange(m)}\n className={cn(\n \"rounded px-2 py-0.5 text-xs capitalize disabled:opacity-50\",\n mode === m\n ? \"bg-accent text-accent-foreground font-medium\"\n : \"text-muted-foreground hover:text-foreground\",\n )}\n >\n {m}\n </button>\n ))}\n </div>\n );\n}\n\n/**\n * Per-group settings for the active group. Currently its show/hide rule, which\n * makes a whole group conditional on another field's value -- the same\n * declarative mechanism as a field's x-ui-rule, so it reuses that editor.\n */\nfunction GroupSettings({\n group,\n scopes,\n readOnly,\n onRule,\n}: {\n group: UILayoutGroupConfig | undefined;\n scopes: ScopeOption[];\n readOnly: boolean;\n onRule: (rule: UILayoutGroupConfig[\"rule\"]) => void;\n}): React.ReactElement | null {\n const [open, setOpen] = useState(false);\n if (!group) return null;\n const hasRule = !!group.rule;\n return (\n <div className=\"shrink-0 rounded-lg border px-3 py-2\">\n <button\n type=\"button\"\n className=\"flex w-full items-center gap-1 heading-meta\"\n onClick={() => setOpen((v) => !v)}\n aria-expanded={open}\n >\n {open ? (\n <ChevronDown className=\"h-3 w-3\" />\n ) : (\n <ChevronRight className=\"h-3 w-3\" />\n )}\n Visibility of {group.label}\n <span className=\"ml-1 normal-case text-muted-foreground/70\">\n {hasRule ? \"conditional\" : \"always shown\"}\n </span>\n </button>\n {open && (\n <div className=\"mt-3 max-w-sm\">\n <RuleFields\n rule={group.rule}\n scopes={scopes}\n effects={VISIBILITY_EFFECT_OPTIONS}\n idPrefix=\"group-rule\"\n disabled={readOnly}\n onChange={(rule) =>\n onRule(rule as UILayoutGroupConfig[\"rule\"] | undefined)\n }\n />\n </div>\n )}\n </div>\n );\n}\n\n// The group strip: select a group to edit its rows, rename inline, add or remove.\nfunction GroupBar({\n groups,\n activeIndex,\n readOnly,\n onSelect,\n onAdd,\n onRename,\n onRemove,\n onMove,\n}: {\n groups: UILayoutGroupConfig[];\n activeIndex: number;\n readOnly: boolean;\n onSelect: (index: number) => void;\n onAdd: () => void;\n onRename: (index: number, label: string) => void;\n onRemove: (index: number) => void;\n onMove: (index: number, direction: -1 | 1) => void;\n}): React.ReactElement {\n return (\n <div\n role=\"tablist\"\n aria-label=\"Layout groups\"\n className=\"shrink-0 flex items-center gap-1 rounded-lg border p-1.5 overflow-x-auto\"\n >\n {groups.map((group, i) => (\n <GroupChip\n // Index alone would re-target GroupChip's in-flight rename state at a\n // different group when one is removed; include the label so identity\n // changes reset it.\n key={`${i}:${group.label}`}\n group={group}\n active={i === activeIndex}\n readOnly={readOnly}\n onSelect={() => onSelect(i)}\n onRename={(label) => onRename(i, label)}\n onRemove={() => onRemove(i)}\n onMoveLeft={i > 0 ? () => onMove(i, -1) : undefined}\n onMoveRight={i < groups.length - 1 ? () => onMove(i, 1) : undefined}\n />\n ))}\n {!readOnly && (\n <Button\n size=\"sm\"\n variant=\"outline\"\n className=\"gap-1.5 shrink-0\"\n onClick={onAdd}\n >\n <Plus className=\"h-4 w-4\" />\n Add group\n </Button>\n )}\n </div>\n );\n}\n\n// One group in the strip. Double-click the label to rename it.\nfunction GroupChip({\n group,\n active,\n readOnly,\n onSelect,\n onRename,\n onRemove,\n onMoveLeft,\n onMoveRight,\n}: {\n group: UILayoutGroupConfig;\n active: boolean;\n readOnly: boolean;\n onSelect: () => void;\n onRename: (label: string) => void;\n onRemove: () => void;\n onMoveLeft?: () => void;\n onMoveRight?: () => void;\n}): React.ReactElement {\n const [editing, setEditing] = useState(false);\n if (editing) {\n return (\n <Input\n autoFocus\n defaultValue={group.label}\n className=\"h-7 w-32 text-sm\"\n onBlur={(e) => {\n const next = e.target.value.trim();\n if (next && next !== group.label) onRename(next);\n setEditing(false);\n }}\n onKeyDown={(e) => {\n if (e.key === \"Enter\") e.currentTarget.blur();\n if (e.key === \"Escape\") setEditing(false);\n }}\n />\n );\n }\n const fieldCount = group.rows.reduce((n, r) => n + r.fields.length, 0);\n return (\n <span\n className={cn(\n \"group/group inline-flex shrink-0 items-center gap-1 rounded-md border pl-2 pr-1 py-0.5 text-sm\",\n active ? \"bg-accent border-accent-foreground/20\" : \"hover:bg-muted\",\n )}\n >\n {/* A real button so the strip is keyboard reachable; F2 renames, matching\n the platform convention (double-click also works with a mouse). */}\n <button\n type=\"button\"\n role=\"group\"\n aria-selected={active}\n className=\"inline-flex items-center gap-1 py-0.5\"\n onClick={onSelect}\n onDoubleClick={() => !readOnly && setEditing(true)}\n onKeyDown={(e) => {\n if (e.key === \"F2\" && !readOnly) {\n e.preventDefault();\n setEditing(true);\n }\n }}\n title={readOnly ? group.label : `${group.label} -- F2 to rename`}\n >\n {group.label}\n <span className=\"text-xs text-muted-foreground\">{fieldCount}</span>\n </button>\n {!readOnly && (\n <span className=\"flex items-center opacity-0 group-hover/group:opacity-100 focus-within:opacity-100\">\n {onMoveLeft && (\n <IconButton\n label={`Move ${group.label} left`}\n revealOnHover\n onClick={onMoveLeft}\n >\n <ChevronLeft />\n </IconButton>\n )}\n {onMoveRight && (\n <IconButton\n label={`Move ${group.label} right`}\n revealOnHover\n onClick={onMoveRight}\n >\n <ChevronRight />\n </IconButton>\n )}\n <IconButton\n label={`Remove ${group.label}`}\n tone=\"destructive\"\n revealOnHover\n onClick={onRemove}\n >\n <Trash2 />\n </IconButton>\n </span>\n )}\n </span>\n );\n}\n\nconst WIDTH_LABELS: Record<WidthToken, string> = {\n full: \"Full\",\n sm: \"Small\",\n md: \"Medium\",\n lg: \"Large\",\n};\n\n// Compact single-letter labels for the inline per-property width selector.\nconst WIDTH_SHORT: Record<WidthToken, string> = {\n full: \"F\",\n sm: \"S\",\n md: \"M\",\n lg: \"L\",\n};\n\nfunction Chip({\n label,\n readOnly,\n onRemove,\n onDragStart,\n onDragEnd,\n width,\n onWidth,\n widthDisabled,\n muted = false,\n}: {\n label: string;\n readOnly: boolean;\n onRemove?: () => void;\n onDragStart: () => void;\n onDragEnd: () => void;\n /** Dimmed styling for a property that currently belongs to another group. */\n muted?: boolean;\n // When provided, the chip shows an inline width selector (row members only).\n width?: WidthToken;\n onWidth?: (width: WidthToken) => void;\n widthDisabled?: boolean;\n}): React.ReactElement {\n return (\n <div\n draggable={!readOnly}\n onDragStart={(e) => {\n e.dataTransfer.setData(DRAG_MIME, label);\n e.dataTransfer.effectAllowed = \"move\";\n onDragStart();\n }}\n onDragEnd={onDragEnd}\n className={cn(\n \"group/chip flex items-center gap-1 rounded-md border bg-background px-2 py-1 text-sm cursor-grab active:cursor-grabbing\",\n muted && \"border-dashed text-muted-foreground\",\n )}\n >\n <GripVertical className=\"h-3.5 w-3.5 text-muted-foreground/60 shrink-0\" />\n <span className=\"truncate\">{label}</span>\n {onWidth && (\n <select\n value={width ?? \"full\"}\n onChange={(e) => onWidth(e.target.value as WidthToken)}\n disabled={readOnly || widthDisabled}\n title={\n widthDisabled ? \"Overridden by raw CSS columns\" : \"Column width\"\n }\n className=\"h-6 rounded border bg-background px-1 text-xs text-muted-foreground disabled:opacity-50\"\n >\n {([\"full\", \"sm\", \"md\", \"lg\"] as WidthToken[]).map((w) => (\n <option key={w} value={w} title={WIDTH_LABELS[w]}>\n {WIDTH_SHORT[w]}\n </option>\n ))}\n </select>\n )}\n {onRemove && !readOnly && (\n <IconButton label=\"Remove from row\" onClick={onRemove}>\n <Trash2 />\n </IconButton>\n )}\n </div>\n );\n}\n\nfunction RowCard({\n row,\n index,\n total,\n readOnly,\n dragActive,\n onDropKey,\n onRemoveKey,\n onDragStartKey,\n onDragEndKey,\n onMoveUp,\n onMoveDown,\n onDelete,\n onColumns,\n onGroup,\n onWidth,\n onArrange,\n}: {\n row: UILayoutRowConfig;\n index: number;\n total: number;\n readOnly: boolean;\n dragActive: boolean;\n onDropKey: (key: string | null) => void;\n onRemoveKey: (key: string) => void;\n onDragStartKey: (key: string) => void;\n onDragEndKey: () => void;\n onMoveUp: () => void;\n onMoveDown: () => void;\n onDelete: () => void;\n onColumns: (v: string) => void;\n onGroup: (v: string) => void;\n onWidth: (cell: number, width: WidthToken) => void;\n onArrange: (arrange: \"grid\" | \"flow\") => void;\n}): React.ReactElement {\n const [over, setOver] = useState(false);\n const isFlow = row.arrange === \"flow\";\n return (\n <div className=\"rounded-lg border p-3\">\n <div className=\"flex items-center gap-2 mb-2\">\n <span className=\"heading-meta\">Row {index + 1}</span>\n {!readOnly && (\n <span className=\"ml-auto flex gap-0.5\">\n <IconButton\n label=\"Move row up\"\n disabled={index === 0}\n onClick={onMoveUp}\n >\n <ChevronUp />\n </IconButton>\n <IconButton\n label=\"Move row down\"\n disabled={index === total - 1}\n onClick={onMoveDown}\n >\n <ChevronDown />\n </IconButton>\n <IconButton\n label=\"Delete row\"\n tone=\"destructive\"\n onClick={onDelete}\n >\n <Trash2 />\n </IconButton>\n </span>\n )}\n </div>\n\n <div className=\"mb-2 flex items-center gap-2\">\n <label className=\"text-xs text-muted-foreground w-16\">Group</label>\n <Input\n value={row.group ?? \"\"}\n onChange={(e) => onGroup(e.target.value)}\n placeholder=\"Section title (optional)\"\n disabled={readOnly}\n className=\"h-7 text-sm flex-1\"\n />\n </div>\n\n <div className=\"mb-2 flex items-center gap-2\">\n <label className=\"text-xs text-muted-foreground w-16\">Arrange</label>\n <select\n value={isFlow ? \"flow\" : \"grid\"}\n onChange={(e) => onArrange(e.target.value as \"grid\" | \"flow\")}\n disabled={readOnly}\n title=\"Grid: sized columns. Inline: fields at natural width, wrapping.\"\n className=\"h-7 rounded-md border bg-background px-2 text-sm text-foreground disabled:opacity-50\"\n >\n <option value=\"grid\">Grid (columns)</option>\n <option value=\"flow\">Inline (natural width)</option>\n </select>\n </div>\n\n <div\n className={`min-h-10 rounded-md border border-dashed p-2 flex flex-wrap gap-1 ${\n over && dragActive ? \"border-primary bg-accent\" : \"border-border\"\n }`}\n onDragOver={(e) => {\n if (dragActive) {\n e.preventDefault();\n setOver(true);\n }\n }}\n onDragLeave={() => setOver(false)}\n onDrop={(e) => {\n setOver(false);\n onDropKey(e.dataTransfer.getData(DRAG_MIME) || null);\n }}\n >\n {row.fields.length === 0 ? (\n <span className=\"text-xs text-muted-foreground p-1\">\n Drop properties here\n </span>\n ) : (\n row.fields.map((key, cell) => (\n <Chip\n key={key}\n label={key}\n readOnly={readOnly}\n onRemove={() => onRemoveKey(key)}\n onDragStart={() => onDragStartKey(key)}\n onDragEnd={onDragEndKey}\n width={row.widths?.[cell] ?? \"full\"}\n onWidth={isFlow ? undefined : (w) => onWidth(cell, w)}\n widthDisabled={!!row.columns}\n />\n ))\n )}\n </div>\n\n {/* Advanced: raw CSS grid columns. Grid mode only -- ignored in flow. */}\n {!isFlow && (\n <details className=\"mt-2\">\n <summary className=\"cursor-pointer text-xs text-muted-foreground\">\n Advanced: raw CSS columns\n </summary>\n <div className=\"mt-2 flex items-center gap-2\">\n <label className=\"text-xs text-muted-foreground w-16\">\n Columns\n </label>\n <Input\n value={row.columns ?? \"\"}\n onChange={(e) => onColumns(e.target.value)}\n placeholder=\"e.g. 1fr 1fr\"\n disabled={readOnly}\n className=\"h-7 text-sm flex-1\"\n />\n </div>\n <p className=\"mt-1 pl-[4.5rem] text-xs text-muted-foreground\">\n Raw <span className=\"font-mono\">grid-template-columns</span>. When\n set, it overrides the per-property widths. Blank = use widths.\n </p>\n </details>\n )}\n </div>\n );\n}\n","/**\n * RuleFields -- the presentational editor for a declarative UIRule\n * (effect + scope + operator + value).\n *\n * Purely controlled: it owns the incomplete-draft state that authoring passes\n * through (an effect chosen before a field cannot yet be a valid rule) and\n * calls `onChange` only once the rule is complete or fully cleared.\n *\n * Shared by the field-level rule editor (x-ui-rule on a property) and the\n * layout tab rule editor, which differ only in where the rule is stored and\n * which effects make sense.\n */\n\nimport React, { useEffect, useMemo, useState } from \"react\";\nimport { FormSelect } from \"@petrarca/sonnet-forms\";\nimport type { UIRule, UIRuleEffect } from \"@petrarca/sonnet-core/schema\";\nimport {\n OPERATOR_OPTIONS,\n operatorToConstraint,\n constraintToOperator,\n type ConditionOperator,\n type ScopeType,\n} from \"../model/conditions\";\nimport { OperatorValueInput } from \"./OperatorValueInput\";\nimport type { EffectOption } from \"./ruleEffects\";\n\n// A rule broken into the flat fields the form edits.\ninterface RuleForm {\n effect: \"\" | UIRuleEffect;\n scope: string;\n operator: ConditionOperator;\n value: string;\n}\n\nfunction ruleToForm(rule: UIRule | undefined): RuleForm {\n if (!rule) return { effect: \"\", scope: \"\", operator: \"=\", value: \"\" };\n const { operator, value } = constraintToOperator(rule.condition.schema);\n return { effect: rule.effect, scope: rule.condition.scope, operator, value };\n}\n\nfunction formToRule(form: RuleForm, scopeType: ScopeType): UIRule | undefined {\n if (!form.effect || !form.scope) return undefined;\n return {\n effect: form.effect,\n condition: {\n scope: form.scope,\n schema: operatorToConstraint(form.operator, form.value, scopeType),\n },\n };\n}\n\n/** True/false choices for a boolean scope; a text box cannot express them. */\nconst BOOLEAN_VALUE_OPTIONS = [\n { value: \"true\", label: \"true\" },\n { value: \"false\", label: \"false\" },\n];\n\n/** A field offered as the condition scope, with the type it holds. */\nexport interface ScopeOption {\n /** JSON Pointer into the form data, e.g. \"/gender\". */\n pointer: string;\n /** The field's declared type, used to write a correctly-typed comparand. */\n type?: ScopeType;\n}\n\nexport interface RuleFieldsProps {\n /** The stored rule, or undefined when there is none. */\n rule: UIRule | undefined;\n /** Fields offered as the condition scope. */\n scopes: ScopeOption[];\n /** Which effects to offer. */\n effects: EffectOption[];\n /** Unique prefix for the field ids (several editors can coexist). */\n idPrefix: string;\n disabled?: boolean;\n /** Called with a complete rule, or undefined when the rule is cleared. */\n onChange: (rule: UIRule | undefined) => void;\n}\n\nexport function RuleFields({\n rule,\n scopes,\n effects,\n idPrefix,\n disabled = false,\n onChange,\n}: RuleFieldsProps): React.ReactElement {\n const [form, setForm] = useState<RuleForm>(() => ruleToForm(rule));\n\n // Re-seed the draft when the stored rule changes externally (e.g. via the\n // JSON source tab). The serialized rule is the sole dependency, so this does\n // not fire on unrelated re-renders.\n const seed = JSON.stringify(rule ?? null);\n useEffect(() => {\n setForm(ruleToForm((JSON.parse(seed) as UIRule | null) ?? undefined));\n }, [seed]);\n\n // The declared type of the selected scope, so the comparand is written with\n // the type the form data actually carries (a boolean field needs `true`, not\n // the string \"true\", or the rule can never match).\n const scopeType = useMemo(\n () => scopes.find((s) => s.pointer === form.scope)?.type,\n [scopes, form.scope],\n );\n\n const commit = (next: RuleForm): void => {\n setForm(next);\n const nextType = scopes.find((s) => s.pointer === next.scope)?.type;\n const built = formToRule(next, nextType);\n // Write when complete, or clear when the effect was removed. Incomplete\n // drafts (effect set, no field yet) stay local until completed.\n if (built || next.effect === \"\") onChange(built);\n };\n\n const scopeOptions = useMemo(\n () => scopes.map((s) => ({ value: s.pointer, label: s.pointer.slice(1) })),\n [scopes],\n );\n const needsValue = form.operator !== \"exists\";\n const isBoolean = scopeType === \"boolean\";\n\n return (\n <div className=\"space-y-3\">\n <FormSelect\n id={`${idPrefix}-effect`}\n name=\"effect\"\n label=\"Effect\"\n options={effects}\n value={form.effect}\n onChange={(v) => commit({ ...form, effect: (v as UIRuleEffect) ?? \"\" })}\n clearable={false}\n disabled={disabled}\n />\n {form.effect !== \"\" && (\n <>\n <FormSelect\n id={`${idPrefix}-scope`}\n name=\"scope\"\n label=\"When field\"\n options={scopeOptions}\n value={form.scope || null}\n onChange={(v) => commit({ ...form, scope: v ?? \"\" })}\n placeholder=\"Select a field...\"\n clearable={false}\n disabled={disabled}\n />\n <FormSelect\n id={`${idPrefix}-operator`}\n name=\"operator\"\n label=\"Operator\"\n options={OPERATOR_OPTIONS}\n value={form.operator}\n onChange={(v) =>\n commit({ ...form, operator: (v as ConditionOperator) ?? \"=\" })\n }\n clearable={false}\n disabled={disabled}\n />\n {needsValue &&\n (isBoolean ? (\n <FormSelect\n id={`${idPrefix}-value`}\n name=\"value\"\n label=\"Value\"\n options={BOOLEAN_VALUE_OPTIONS}\n value={form.value === \"true\" ? \"true\" : \"false\"}\n onChange={(v) => commit({ ...form, value: v ?? \"false\" })}\n clearable={false}\n disabled={disabled || !form.scope}\n />\n ) : (\n <OperatorValueInput\n id={`${idPrefix}-value`}\n cacheKey={`${form.scope}:${form.operator}`}\n value={form.value}\n onCommit={(v) => commit({ ...form, value: v })}\n disabled={disabled || !form.scope}\n />\n ))}\n </>\n )}\n </div>\n );\n}\n","/**\n * Condition builder: the bridge between a friendly (property, operator, value)\n * triple and the JSON Schema `if` sub-schema the renderer evaluates.\n *\n * An `if` tests a sibling property. Operators map to standard schema keywords\n * (mirrors the FHIR operator table in fhir-questionnaire-adapter.md 7.1):\n *\n * = -> { properties: { field: { const: value } }, required: [field] }\n * != -> { properties: { field: { not: { const: value } } }, required: [field] }\n * > >= < <= -> exclusiveMinimum / minimum / exclusiveMaximum / maximum\n * exists -> { required: [field] }\n *\n * A value operator always adds `required: [field]` so an absent field does not\n * vacuously satisfy the condition.\n */\n\nimport type { JsonSchemaProperty } from \"@petrarca/sonnet-core/schema\";\n\nexport type ConditionOperator = \"=\" | \"!=\" | \">\" | \">=\" | \"<\" | \"<=\" | \"exists\";\n\nexport const CONDITION_OPERATORS: readonly ConditionOperator[] = [\n \"=\",\n \"!=\",\n \">\",\n \">=\",\n \"<\",\n \"<=\",\n \"exists\",\n];\n\n/** Human labels for the operator dropdown. */\nexport const CONDITION_OPERATOR_LABELS: Record<ConditionOperator, string> = {\n \"=\": \"equals\",\n \"!=\": \"not equals\",\n \">\": \"greater than\",\n \">=\": \"greater or equal\",\n \"<\": \"less than\",\n \"<=\": \"less or equal\",\n exists: \"exists\",\n};\n\n/** Shared select-option list for the operator dropdown (ConditionEditor + RuleEditor). */\nexport const OPERATOR_OPTIONS: { value: ConditionOperator; label: string }[] =\n CONDITION_OPERATORS.map((op) => ({\n value: op,\n label: CONDITION_OPERATOR_LABELS[op],\n }));\n\n/** A condition as edited in the inspector. */\nexport interface Condition {\n field: string;\n operator: ConditionOperator;\n /** Raw string value from the inspector; coerced to number where numeric. */\n value: string;\n}\n\n// Numeric operators need a numeric comparand.\nconst NUMERIC_OPS: ReadonlySet<ConditionOperator> = new Set([\n \">\",\n \">=\",\n \"<\",\n \"<=\",\n]);\n\n/** The JSON Schema type of the field a condition targets, when known. */\nexport type ScopeType = JsonSchemaProperty[\"type\"];\n\n// Coerce a string value to number when it is a finite numeric literal.\nfunction coerceValue(value: string): string | number {\n if (value.trim() === \"\") return value;\n const n = Number(value);\n return Number.isFinite(n) ? n : value;\n}\n\n/**\n * Coerce the editor's string value to the type the target field actually\n * holds. Without this a boolean field compared with the *string* \"true\" can\n * never match the boolean `true` the form produces -- the rule would be\n * authorable but silently dead.\n *\n * Numeric operators always compare numerically, whatever the declared type.\n */\nfunction coerceForScope(\n value: string,\n operator: ConditionOperator,\n type: ScopeType,\n): string | number | boolean {\n if (NUMERIC_OPS.has(operator)) return coerceValue(value);\n if (type === \"boolean\") return value === \"true\";\n if (type === \"number\" || type === \"integer\") return coerceValue(value);\n return value;\n}\n\n/**\n * The per-value constraint schema for an operator + value (e.g. \"=\" + \"female\"\n * -> { const: \"female\" }). This is the value-level building block shared by the\n * conditional `if` builder and the x-ui-rule builder. `exists` yields an empty\n * schema (presence is expressed by `required` at the caller).\n *\n * Pass the target field's `type` so the comparand is written with the type the\n * form data actually carries.\n */\nexport function operatorToConstraint(\n operator: ConditionOperator,\n value: string,\n type?: ScopeType,\n): JsonSchemaProperty {\n const v = coerceForScope(value, operator, type);\n switch (operator) {\n case \"=\":\n return { const: v };\n case \"!=\":\n return { not: { const: v } };\n case \">\":\n return { exclusiveMinimum: v as number };\n case \">=\":\n return { minimum: v as number };\n case \"<\":\n return { exclusiveMaximum: v as number };\n case \"<=\":\n return { maximum: v as number };\n case \"exists\":\n return {};\n }\n}\n\n/**\n * Build the `if` sub-schema for a condition. Returns undefined for no field.\n * Pass the field's `type` so the comparand matches the form data's type.\n */\nexport function conditionToIf(\n condition: Condition,\n type?: ScopeType,\n): JsonSchemaProperty | undefined {\n const { field, operator } = condition;\n if (!field) return undefined;\n if (operator === \"exists\") {\n return { required: [field] };\n }\n return {\n properties: {\n [field]: operatorToConstraint(operator, condition.value, type),\n },\n required: [field],\n };\n}\n\n/** Recover the operator + value from a per-value constraint schema. */\nexport function constraintToOperator(c: JsonSchemaProperty): {\n operator: ConditionOperator;\n value: string;\n} {\n if (c.not && \"const\" in c.not)\n return { operator: \"!=\", value: String(c.not.const) };\n if (c.exclusiveMinimum !== undefined)\n return { operator: \">\", value: String(c.exclusiveMinimum) };\n if (c.minimum !== undefined)\n return { operator: \">=\", value: String(c.minimum) };\n if (c.exclusiveMaximum !== undefined)\n return { operator: \"<\", value: String(c.exclusiveMaximum) };\n if (c.maximum !== undefined)\n return { operator: \"<=\", value: String(c.maximum) };\n if (\"const\" in c) return { operator: \"=\", value: String(c.const) };\n return { operator: \"exists\", value: \"\" };\n}\n\n/** Recover a Condition from an `if` sub-schema (inverse of conditionToIf). */\nexport function ifToCondition(\n ifSchema: JsonSchemaProperty | undefined,\n): Condition {\n const empty: Condition = { field: \"\", operator: \"=\", value: \"\" };\n if (!ifSchema) return empty;\n const props = ifSchema.properties ?? {};\n const field = Object.keys(props)[0] ?? ifSchema.required?.[0] ?? \"\";\n if (!field) return empty;\n const constraint = props[field];\n if (!constraint) return { field, operator: \"exists\", value: \"\" };\n const { operator, value } = constraintToOperator(constraint);\n return { field, operator, value };\n}\n","/**\n * Shared operator + value input used by both ConditionEditor and RuleEditor.\n * Renders a labelled Input that commits on blur via the provided callback.\n */\n\nimport React from \"react\";\nimport { Input } from \"@petrarca/sonnet-ui\";\n\nexport interface OperatorValueInputProps {\n id: string;\n /** A key that remounts the input when the operator or field changes. */\n cacheKey: string;\n value: string;\n onCommit: (value: string) => void;\n disabled: boolean;\n}\n\nexport function OperatorValueInput({\n id,\n cacheKey,\n value,\n onCommit,\n disabled,\n}: OperatorValueInputProps): React.ReactElement {\n return (\n <div className=\"space-y-1\">\n <label htmlFor={id} className=\"text-sm font-medium\">\n Value\n </label>\n <Input\n id={id}\n key={cacheKey}\n defaultValue={value}\n onBlur={(e) => onCommit(e.target.value)}\n disabled={disabled}\n placeholder=\"Value to compare\"\n />\n </div>\n );\n}\n","/**\n * Effect choices offered by the rule editors. Kept apart from the components\n * so a fast-refresh boundary is not broken by a non-component export.\n */\n\n/** One effect choice; \"\" clears the rule entirely. */\nexport interface EffectOption {\n value: string;\n label: string;\n}\n\n/** Visibility-only effects (a layout group cannot be \"disabled\"). */\nexport const VISIBILITY_EFFECT_OPTIONS: EffectOption[] = [\n { value: \"\", label: \"None (always shown)\" },\n { value: \"show\", label: \"Show when\" },\n { value: \"hide\", label: \"Hide when\" },\n];\n\n/** Visibility plus enablement, for a field. */\nexport const FIELD_EFFECT_OPTIONS: EffectOption[] = [\n { value: \"\", label: \"None (always visible)\" },\n { value: \"show\", label: \"Show when\" },\n { value: \"hide\", label: \"Hide when\" },\n { value: \"enable\", label: \"Enable when\" },\n { value: \"disable\", label: \"Disable when\" },\n];\n","/**\n * CapabilitiesPanel -- edits the SchemaDesignerCapabilities profile as JSON and\n * applies it live. A dev / power-user affordance shown only when the profile\n * lists \"capabilities\" in previews. Validates via `validateCapabilities` before\n * applying; invalid JSON or an invalid profile surfaces an inline error.\n *\n * Reuses SchemaSourcePanel for the editor + corner Copy/Apply chrome, keeping\n * the source tabs consistent.\n */\n\nimport React, { useMemo } from \"react\";\nimport {\n validateCapabilities,\n type SchemaDesignerCapabilities,\n} from \"../capabilities\";\nimport { SchemaSourcePanel } from \"./SchemaSourcePanel\";\n\nexport interface CapabilitiesPanelProps {\n capabilities?: SchemaDesignerCapabilities;\n onApply?: (next: SchemaDesignerCapabilities) => void;\n}\n\nexport function CapabilitiesPanel({\n capabilities,\n onApply,\n}: CapabilitiesPanelProps): React.ReactElement {\n const value = useMemo(\n () => JSON.stringify(capabilities ?? {}, null, 2),\n [capabilities],\n );\n\n return (\n <SchemaSourcePanel\n value={value}\n editable\n validate={(parsed) => {\n const result = validateCapabilities(parsed);\n return result.ok ? null : result.errors.join(\"; \");\n }}\n onApply={(parsed) => {\n const result = validateCapabilities(parsed);\n if (result.ok) onApply?.(result.value);\n }}\n />\n );\n}\n","/**\n * SchemaSourcePanel -- JSON source view for a designer artifact (the JSON\n * Schema or the UI Schema map), read-only or editable.\n *\n * When editable, the editor holds transient text; nothing is committed until\n * Apply. On Apply the text is parsed and, if valid JSON, passed to `onApply`\n * which replaces the corresponding artifact in the model. Subsequent visual\n * edits are surgical, so hand-authored constructs (oneOf, if/then/else, const,\n * $ref, ...) survive.\n *\n * Copy and Apply are corner-overlay buttons, consistent with the read-only JSON\n * views. The \"Combined\" view is intentionally not editable: it is a derived\n * projection (schema + embedded UI hints) that cannot be un-merged unambiguously.\n */\n\nimport React, { useEffect, useRef, useState } from \"react\";\nimport { Check, Copy } from \"lucide-react\";\nimport { Button } from \"@petrarca/sonnet-ui\";\nimport { JsonEditor } from \"@petrarca/sonnet-ui/json-editor\";\nimport { copyTextToClipboard } from \"@petrarca/sonnet-core\";\n\nexport interface SchemaSourcePanelProps {\n /** Serialized current value of the artifact. */\n value: string;\n /** Whether editing is allowed (false renders read-only). */\n editable: boolean;\n /** Called with the parsed object when the user applies a valid edit. */\n onApply: (parsed: unknown) => void;\n /** Optional validation returning an error string, or null when valid. */\n validate?: (parsed: unknown) => string | null;\n}\n\nexport function SchemaSourcePanel({\n value,\n editable,\n onApply,\n validate,\n}: SchemaSourcePanelProps): React.ReactElement {\n const [text, setText] = useState(value);\n const [error, setError] = useState<string | null>(null);\n const [copied, setCopied] = useState(false);\n // Dirty means the USER edited the text since we last adopted a model value.\n // It must NOT be derived from `text !== value`: when the model changes\n // underneath (e.g. a visual tree/inspector edit while this tab is open),\n // `text` lags `value` for one render, which `text !== value` would wrongly\n // read as a user edit -- staling the view and falsely enabling Apply.\n const [dirty, setDirty] = useState(false);\n\n // The last model value this panel has adopted into `text`. Compared against\n // incoming `value` to detect genuine external model changes.\n const lastValueRef = useRef(value);\n useEffect(() => {\n if (value === lastValueRef.current) return;\n // A model change always wins over a clean editor. It only yields to the\n // user when they have an unapplied edit (dirty) -- then we keep their text\n // and let them Apply or discard, rather than clobbering silently.\n // lastValueRef tracks only adopted values so a repeated model emission of\n // the same string (e.g. two normalizations to the same JSON) is not missed.\n if (!dirty) {\n lastValueRef.current = value;\n setText(value);\n setError(null);\n }\n }, [value, dirty]);\n\n // User typed in the editor: adopt the text and mark dirty. When the text\n // matches the current model again, the edit has been reverted -- clear dirty.\n const handleEditorChange = (next: string): void => {\n setText(next);\n setDirty(next !== value);\n };\n\n const handleCopy = (): void => {\n void copyTextToClipboard(editable ? text : value).then(() => {\n setCopied(true);\n setTimeout(() => setCopied(false), 1500);\n });\n };\n\n const handleApply = (): void => {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text || \"{}\");\n } catch {\n setError(\"Invalid JSON.\");\n return;\n }\n const validationError = validate?.(parsed);\n if (validationError) {\n setError(validationError);\n return;\n }\n setError(null);\n // The edit is applied; the model will re-serialize and flow back as a new\n // `value`, which the (now clean) effect adopts. Clear dirty and snap\n // lastValueRef so that incoming value is taken even if it equals prior text.\n setDirty(false);\n onApply(parsed);\n };\n\n return (\n <div className=\"absolute inset-0 rounded-md border overflow-hidden\">\n <div className=\"absolute right-2 top-2 z-10 flex items-center gap-2\">\n {error && (\n <span className=\"rounded bg-destructive px-2 py-1 text-xs font-medium text-destructive-foreground\">\n {error}\n </span>\n )}\n {editable && (\n <Button\n type=\"button\"\n size=\"sm\"\n onClick={handleApply}\n disabled={!dirty}\n >\n Apply\n </Button>\n )}\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n onClick={handleCopy}\n className=\"gap-1.5\"\n >\n {copied ? (\n <Check className=\"h-3.5 w-3.5\" />\n ) : (\n <Copy className=\"h-3.5 w-3.5\" />\n )}\n {copied ? \"Copied\" : \"Copy\"}\n </Button>\n </div>\n {editable ? (\n <JsonEditor\n value={text}\n editablePaths={[\"/\"]}\n fillContainer\n onChange={handleEditorChange}\n />\n ) : (\n <JsonEditor\n key={value}\n value={value}\n editablePaths={[]}\n fillContainer\n />\n )}\n </div>\n );\n}\n","/**\n * Inspector -- the right pane. Resolves the selected property and hosts the tabbed\n * editors (Data now; UI and Layout added incrementally). Empty state when no\n * property is selected.\n */\n\nimport React, { useEffect, useMemo, useRef, useState } from \"react\";\nimport {\n Tabs,\n TabsList,\n TabsTrigger,\n TabsContent,\n Input,\n IconButton,\n} from \"@petrarca/sonnet-ui\";\nimport { Pencil, Check, X } from \"lucide-react\";\nimport type { WidgetOptionDef } from \"@petrarca/sonnet-forms/widget-options\";\nimport type { DesignerState } from \"../hooks/useDesignerState\";\nimport { buildPropertyTree, type PropertyNode } from \"../model/view\";\nimport { samePath, pathKey, type PropertyPath } from \"../model/paths\";\nimport { DataTab } from \"./DataTab\";\nimport { UITab } from \"./UITab\";\nimport { EnumEditor } from \"./EnumEditor\";\nimport { TableHintsTab } from \"./TableHintsTab\";\nimport { ConditionEditor } from \"./ConditionEditor\";\nimport { RuleEditor } from \"./RuleEditor\";\nimport { ReferenceTab } from \"./ReferenceTab\";\n\n// Property types for which a fixed enum makes sense.\nconst ENUM_CAPABLE_TYPES = new Set([\"string\", \"number\", \"integer\"]);\n\nexport interface InspectorProps {\n state: DesignerState;\n /** Option descriptors for custom widgets (merged over built-ins). */\n widgetOptions?: Record<string, WidgetOptionDef[]>;\n}\n\n// Property key display + explicit edit affordance. Shows the key as static text\n// with a small pencil button (matching the graph-model rename pattern). Clicking\n// edit reveals an input with confirm/cancel; commit routes to renameProperty.\nfunction KeyField({\n fieldKey,\n onRename,\n readOnly,\n}: {\n fieldKey: string;\n onRename: (next: string) => void;\n readOnly: boolean;\n}): React.ReactElement {\n const [editing, setEditing] = useState(false);\n const [value, setValue] = useState(fieldKey);\n const ref = useRef<HTMLInputElement>(null);\n\n // Re-seed and exit edit mode when the selected property changes.\n useEffect(() => {\n setValue(fieldKey);\n setEditing(false);\n }, [fieldKey]);\n\n useEffect(() => {\n if (editing) {\n ref.current?.focus();\n ref.current?.select();\n }\n }, [editing]);\n\n const commit = () => {\n const trimmed = value.trim();\n if (trimmed && trimmed !== fieldKey) onRename(trimmed);\n setEditing(false);\n };\n const cancel = () => {\n setValue(fieldKey);\n setEditing(false);\n };\n\n if (!editing) {\n return (\n <div className=\"flex items-center gap-1\">\n <span className=\"text-sm font-semibold truncate\">{fieldKey}</span>\n {!readOnly && (\n <IconButton label=\"Rename property\" onClick={() => setEditing(true)}>\n <Pencil />\n </IconButton>\n )}\n </div>\n );\n }\n\n return (\n <div className=\"flex items-center gap-1\">\n <Input\n ref={ref}\n value={value}\n onChange={(e) => setValue(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === \"Enter\") {\n e.preventDefault();\n commit();\n } else if (e.key === \"Escape\") {\n e.preventDefault();\n cancel();\n }\n }}\n className=\"h-7 text-sm font-medium\"\n />\n <IconButton label=\"Confirm rename\" onClick={commit}>\n <Check />\n </IconButton>\n <IconButton label=\"Cancel rename\" onClick={cancel}>\n <X />\n </IconButton>\n </div>\n );\n}\n\n// Find the node for a path in the built tree.\nfunction findNode(\n nodes: PropertyNode[],\n path: PropertyPath,\n): PropertyNode | undefined {\n for (const node of nodes) {\n if (samePath(node.path, path)) return node;\n const inChild = findNode(node.children, path);\n if (inChild) return inChild;\n }\n return undefined;\n}\n\n// Header: the (maybe-renamable) key + the type label.\nfunction InspectorHeader({\n node,\n state,\n}: {\n node: PropertyNode;\n state: DesignerState;\n}): React.ReactElement {\n const isDefinition = node.kind === \"definition\";\n // Branches and conditionals have no renamable key. A definition renames via\n // renameDefinition (rewriting $refs); it is gated by the lock, not scoping.\n const noRename = isDefinition\n ? state.capabilities.locked\n : state.readOnly ||\n node.slotKind === \"branch\" ||\n node.slotKind === \"conditional\";\n const onRename = (next: string) =>\n isDefinition\n ? state.renameDefinition(node.key, next)\n : state.renameProperty(node.path, next);\n return (\n <div className=\"mb-3 space-y-1\">\n <KeyField\n key={pathKey(node.path)}\n fieldKey={node.key}\n readOnly={noRename}\n onRename={onRename}\n />\n <p className=\"font-mono text-xs text-muted-foreground\">\n {isDefinition ? \"definition\" : node.typeLabel}\n </p>\n </div>\n );\n}\n\n// The standard property editor: Data / Enum / UI / Table tabs.\nfunction PropertyTabs({\n node,\n state,\n widgetOptions,\n}: {\n node: PropertyNode;\n state: DesignerState;\n widgetOptions?: Record<string, WidgetOptionDef[]>;\n}): React.ReactElement {\n const enumCapable = ENUM_CAPABLE_TYPES.has(node.property.type ?? \"\");\n // Rule tab: x-ui-rule operates on a JSON Pointer into the root form data, so\n // it is not applicable inside branch/condition/slot paths. Def-field paths\n // cross a def segment but are otherwise normal properties -- allow Rule there.\n const ruleUnsupported = node.path.some(\n (s) => s.kind === \"branch\" || s.kind === \"condition\" || s.kind === \"slot\",\n );\n // UI tab: the uiSchema map is keyed by top-level property name; fields inside\n // any non-prop segment (branch, condition, slot, or def) cannot be addressed\n // without colliding with same-named properties at other paths.\n const uiUnsupported = node.path.some((s) => s.kind !== \"prop\");\n return (\n <Tabs key={`${pathKey(node.path)}:${enumCapable}`} defaultValue=\"data\">\n <TabsList className=\"mb-3\">\n <TabsTrigger value=\"data\">Data</TabsTrigger>\n {enumCapable && <TabsTrigger value=\"enum\">Enum</TabsTrigger>}\n <TabsTrigger value=\"ui\">UI</TabsTrigger>\n {!ruleUnsupported && <TabsTrigger value=\"rule\">Rule</TabsTrigger>}\n <TabsTrigger value=\"table\">Table</TabsTrigger>\n </TabsList>\n <TabsContent value=\"data\">\n <DataTab node={node} state={state} />\n </TabsContent>\n {enumCapable && (\n <TabsContent value=\"enum\">\n <EnumEditor node={node} state={state} />\n </TabsContent>\n )}\n {!ruleUnsupported && (\n <TabsContent value=\"rule\">\n <RuleEditor node={node} state={state} />\n </TabsContent>\n )}\n <TabsContent value=\"ui\">\n {/* uiSchema has no branch-index or def concept; widget hints for\n non-root-prop paths cannot be addressed without key collisions.\n Author them in the JSON Schema or UI Schema source tab instead. */}\n {uiUnsupported ? (\n <p className=\"text-sm text-muted-foreground p-2\">\n Widget hints for properties inside a variant branch or definition\n are not yet editable here. Author them in the JSON Schema or UI\n Schema tab.\n </p>\n ) : (\n <UITab node={node} state={state} widgetOptions={widgetOptions} />\n )}\n </TabsContent>\n <TabsContent value=\"table\">\n <TableHintsTab node={node} state={state} />\n </TabsContent>\n </Tabs>\n );\n}\n\n// The body for a node: a construct-specific panel, else the standard tabs.\nfunction InspectorBody({\n node,\n state,\n widgetOptions,\n}: {\n node: PropertyNode;\n state: DesignerState;\n widgetOptions?: Record<string, WidgetOptionDef[]>;\n}): React.ReactElement {\n const lastSeg = node.path[node.path.length - 1];\n // A $ref node: its referenced fields are read-only (edit the definition), but\n // 2020-12 allows local annotation overrides (title/description/default) at the\n // referencing site, plus a \"stop referencing\" action -- see ReferenceTab.\n if (node.kind === \"reference\") {\n return <ReferenceTab node={node} state={state} />;\n }\n // A field inside a referenced definition: read-only (edit it at the source).\n if (node.readOnly) {\n return (\n <p className=\"text-sm text-muted-foreground p-2\">\n This field comes from a shared definition and is read-only here. Edit\n the definition in the JSON Schema tab to change it.\n </p>\n );\n }\n // A definition ($defs entry): a reusable object schema. Rename it in the\n // header; edit its fields in the tree. Its scalar/type keys are not edited\n // at the definition level in v1 (author advanced shapes in the source tab).\n if (node.kind === \"definition\") {\n return (\n <p className=\"text-sm text-muted-foreground p-2\">\n Reusable definition <span className=\"font-medium\">{node.key}</span>. Add\n or edit its fields in the tree; reference it from a property to reuse\n its shape. Renaming it here updates every reference.\n </p>\n );\n }\n // A conditional member: edit its `if` in the condition builder.\n if (node.kind === \"conditional\") {\n return <ConditionEditor node={node} state={state} />;\n }\n // A then/else slot: an object container whose fields are edited in the tree.\n if (node.slotKind === \"conditional\" && lastSeg?.kind === \"slot\") {\n return (\n <p className=\"text-sm text-muted-foreground p-2\">\n Add fields to this <span className=\"font-medium\">{node.key}</span>{\" \"}\n branch from the tree. They apply when the condition{\" \"}\n {node.key === \"then\" ? \"holds\" : \"does not hold\"}.\n </p>\n );\n }\n return (\n <PropertyTabs node={node} state={state} widgetOptions={widgetOptions} />\n );\n}\n\nexport function Inspector({\n state,\n widgetOptions,\n}: InspectorProps): React.ReactElement {\n const tree = useMemo(\n () => buildPropertyTree(state.schema, state.refResolver),\n [state.schema, state.refResolver],\n );\n const node = state.selection ? findNode(tree, state.selection) : undefined;\n\n if (!node) {\n return (\n <p className=\"text-sm text-muted-foreground\">\n Select a property to edit.\n </p>\n );\n }\n\n return (\n <div>\n <InspectorHeader node={node} state={state} />\n <InspectorBody node={node} state={state} widgetOptions={widgetOptions} />\n </div>\n );\n}\n","/**\n * DataTab -- edits a property's data definition (type, title, description,\n * default, required, validation) via a meta-schema rendered with\n * JsonSchemaFormRenderer. Type and required are routed to dedicated mutations\n * (they reshape structure / live on the parent); the rest is a property patch.\n */\n\nimport React, { useMemo, useRef } from \"react\";\nimport { JsonSchemaFormRenderer } from \"@petrarca/sonnet-forms\";\nimport {\n Select,\n SelectTrigger,\n SelectValue,\n SelectContent,\n SelectItem,\n} from \"@petrarca/sonnet-ui\";\nimport type { DesignerState } from \"../hooks/useDesignerState\";\nimport type { PropertyNode } from \"../model/view\";\nimport { pathKey } from \"../model/paths\";\nimport type { PropertyTypeChoice } from \"../model/mutate\";\nimport {\n BRANCH_META_TYPE,\n buildDataMetaSchema,\n dataValuesToPatch,\n propertyToDataValues,\n type DataFormValues,\n} from \"./metaSchemas\";\n\nexport interface DataTabProps {\n node: PropertyNode;\n state: DesignerState;\n}\n\nexport function DataTab({ node, state }: DataTabProps): React.ReactElement {\n const isBranch = node.slotKind === \"branch\";\n // A branch is an anonymous object; its editable data is just its title.\n const type = isBranch\n ? BRANCH_META_TYPE\n : node.property.oneOf\n ? \"oneOf\"\n : (node.property.type ?? \"string\");\n const schema = useMemo(() => buildDataMetaSchema(type), [type]);\n const values = useMemo(\n () => propertyToDataValues(node.property, node.required),\n [node.property, node.required],\n );\n\n // Track previous values to detect which attribute changed.\n const prevRef = useRef<DataFormValues>(values);\n prevRef.current = values;\n\n const handleChange = (data: Record<string, unknown>) => {\n const next = data as unknown as DataFormValues;\n const prev = prevRef.current;\n\n // Each renderer onChange reflects a single attribute edit; route it to exactly\n // one mutation. Firing two mutations here would double-commit against the\n // same (pre-render) model and the second would clobber the first.\n\n // Type change reshapes the property (not applicable to a branch).\n if (!isBranch && next.type !== prev.type) {\n state.changePropertyType(node.path, next.type as PropertyTypeChoice);\n return;\n }\n // Required lives on the parent's required[], not on the property.\n if (next.required !== prev.required) {\n state.setRequired(node.path, !!next.required);\n return;\n }\n // Otherwise it is a property attribute change.\n state.updateProperty(node.path, dataValuesToPatch(next));\n };\n\n return (\n <div className=\"space-y-3\">\n {!isBranch && (\n <ReferencePicker node={node} state={state} disabled={state.readOnly} />\n )}\n <JsonSchemaFormRenderer\n key={pathKey(node.path) + \":\" + type}\n schema={schema}\n data={values as unknown as Record<string, unknown>}\n onChange={handleChange}\n deferStateUpdates\n showActions={false}\n showExtraProperties={false}\n readOnly={state.readOnly}\n />\n </div>\n );\n}\n\n// The definition names available to reference (2020-12 $defs or Draft-7\n// definitions). Excludes the definition currently being edited, if any.\nfunction availableDefinitions(\n state: DesignerState,\n node: PropertyNode,\n): string[] {\n const defs = state.schema.$defs ?? state.schema.definitions;\n if (!defs) return [];\n const selfName =\n node.path.length === 1 && node.path[0].kind === \"def\"\n ? node.path[0].name\n : undefined;\n return Object.keys(defs).filter((name) => name !== selfName);\n}\n\n// A picker that turns the property into a reference to a shared definition.\n// Only shown when definitions exist; choosing one writes a local $ref.\nfunction ReferencePicker({\n node,\n state,\n disabled,\n}: {\n node: PropertyNode;\n state: DesignerState;\n disabled: boolean;\n}): React.ReactElement | null {\n const names = availableDefinitions(state, node);\n if (names.length === 0) return null;\n // For an array the reference applies to its items (\"array of <def>\").\n const isArray = node.property.type === \"array\";\n const label = isArray\n ? \"Reference a definition (array items)\"\n : \"Reference a definition\";\n const placeholder = isArray\n ? \"Make items reuse a shared definition...\"\n : \"Reuse a shared definition...\";\n return (\n <div className=\"space-y-1\">\n <label className=\"text-xs font-medium text-muted-foreground\">\n {label}\n </label>\n <Select\n value=\"\"\n onValueChange={(name) => state.setReference(node.path, name)}\n disabled={disabled}\n >\n <SelectTrigger className=\"h-8 text-sm\">\n <SelectValue placeholder={placeholder} />\n </SelectTrigger>\n <SelectContent>\n {names.map((name) => (\n <SelectItem key={name} value={name}>\n {name}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n );\n}\n","/**\n * Meta-schemas -- JsonSchemas that describe a property definition, rendered by\n * JsonSchemaFormRenderer to produce the inspector's Data tab. Recomputed per\n * property type so only relevant validation constraints appear.\n *\n * This is the property-definition meta-schema (cf.\n * graph-model/PropertyFormSheet's buildSchema), kept in the designer for now.\n */\n\nimport type {\n JsonSchema,\n JsonSchemaProperty,\n} from \"@petrarca/sonnet-core/schema\";\n\nexport const PROPERTY_TYPES = [\n \"string\",\n \"number\",\n \"integer\",\n \"boolean\",\n \"object\",\n \"array\",\n \"null\",\n] as const;\n\n// The kind choices offered by the type dropdown. Extends the JSON Schema types\n// with logic constructs (\"oneOf\"). Values are PropertyTypeChoice (see mutate).\nexport const PROPERTY_TYPE_CHOICES = [...PROPERTY_TYPES, \"oneOf\"] as const;\n\n// Friendly labels for the type dropdown (null is a display-only text block).\nconst PROPERTY_TYPE_NAMES: Record<string, string> = {\n string: \"String\",\n number: \"Number\",\n integer: \"Integer\",\n boolean: \"Boolean\",\n object: \"Object\",\n array: \"Array\",\n null: \"Display (text only)\",\n oneOf: \"One of (variant)\",\n};\n\n/** The editable data-attributes of a property, as flat form data. */\nexport interface DataFormValues {\n type: string;\n title?: string;\n description?: string;\n default?: unknown;\n const?: string;\n required: boolean;\n // validation\n minLength?: number;\n maxLength?: number;\n pattern?: string;\n format?: string;\n minimum?: number;\n maximum?: number;\n minItems?: number;\n maxItems?: number;\n // oneOf\n discriminator?: string;\n}\n\nconst STRING_FORMATS = [\n \"\",\n \"email\",\n \"uri\",\n \"url\",\n \"date\",\n \"date-time\",\n \"time\",\n \"uuid\",\n];\n\n// Validation properties available per type.\nfunction validationProps(type: string): Record<string, JsonSchemaProperty> {\n switch (type) {\n case \"string\":\n return {\n format: { type: \"string\", title: \"Format\", enum: STRING_FORMATS },\n minLength: { type: \"integer\", title: \"Min length\", minimum: 0 },\n maxLength: { type: \"integer\", title: \"Max length\", minimum: 0 },\n pattern: { type: \"string\", title: \"Pattern (regex)\" },\n };\n case \"number\":\n case \"integer\":\n return {\n minimum: { type: \"number\", title: \"Minimum\" },\n maximum: { type: \"number\", title: \"Maximum\" },\n };\n case \"array\":\n return {\n minItems: { type: \"integer\", title: \"Min items\", minimum: 0 },\n maxItems: { type: \"integer\", title: \"Max items\", minimum: 0 },\n };\n default:\n return {};\n }\n}\n\n/**\n * Build the Data-tab meta-schema for a property of the given type. `isContainer`\n * (object/array) hides `default`, which is not meaningful there.\n */\n// Synthetic meta-type used for oneOf branches in the Data tab. Not a real JSON\n// Schema type -- used only within the inspector to select the branch sub-schema.\nexport const BRANCH_META_TYPE = \"branch\" as const;\n\n// Which meta-fields apply to a given property type.\ninterface TypeTraits {\n isDisplay: boolean;\n noDefault: boolean;\n noRequired: boolean;\n isScalar: boolean;\n isOneOf: boolean;\n}\n\nfunction typeTraits(type: string): TypeTraits {\n const isDisplay = type === \"null\";\n const isOneOf = type === \"oneOf\";\n const isContainer = type === \"object\" || type === \"array\";\n return {\n isDisplay,\n isOneOf,\n // Containers, display (null), and oneOf have no meaningful default value.\n noDefault: isContainer || isDisplay || isOneOf,\n // Display notes and oneOf unions are never \"required\" on their own.\n noRequired: isDisplay || isOneOf,\n // A fixed value (const) is only meaningful on scalar properties.\n isScalar:\n type === \"string\" ||\n type === \"number\" ||\n type === \"integer\" ||\n type === \"boolean\",\n };\n}\n\n/**\n * The Data-tab meta-schema for a `$ref` (reference) node. In JSON Schema\n * 2020-12, keywords alongside `$ref` are applied at the referencing site (they\n * are NOT ignored, unlike Draft 7). Only annotation overrides are meaningful\n * here -- structural type/validation belongs to the referenced definition, so\n * this exposes just title/description/default/required as local overrides.\n */\nexport function buildReferenceMetaSchema(): JsonSchema {\n return {\n title: \"\",\n type: \"object\",\n properties: {\n title: { type: \"string\", title: \"Label (title)\" },\n description: {\n type: \"string\",\n title: \"Description\",\n \"x-ui-widget\": \"textarea\",\n },\n required: { type: \"boolean\", title: \"Required\" },\n default: { type: \"string\", title: \"Default\" },\n },\n };\n}\n\nexport function buildDataMetaSchema(type: string): JsonSchema {\n // A oneOf branch: only its title (the branch label) is editable here; its\n // fields are edited as child properties in the tree.\n if (type === BRANCH_META_TYPE) {\n return {\n title: \"\",\n type: \"object\",\n properties: {\n title: { type: \"string\", title: \"Branch label (title)\" },\n },\n };\n }\n const { isDisplay, noDefault, noRequired, isScalar, isOneOf } =\n typeTraits(type);\n const properties: Record<string, JsonSchemaProperty> = {\n type: {\n type: \"string\",\n title: \"Type\",\n enum: [...PROPERTY_TYPE_CHOICES],\n \"x-ui-options\": { enumNames: PROPERTY_TYPE_NAMES },\n },\n title: { type: \"string\", title: isDisplay ? \"Text\" : \"Label (title)\" },\n description: {\n type: \"string\",\n title: \"Description\",\n \"x-ui-widget\": \"textarea\",\n },\n ...(isOneOf\n ? {\n discriminator: {\n type: \"string\",\n title: \"Discriminator property\",\n \"x-ui-description\":\n \"Shared property whose const value tags each branch. Auto-detected when blank.\",\n },\n }\n : {}),\n ...(noRequired ? {} : { required: { type: \"boolean\", title: \"Required\" } }),\n ...(noDefault ? {} : { default: { type: \"string\", title: \"Default\" } }),\n ...(isScalar\n ? {\n const: {\n type: \"string\",\n title: \"Const (fixed value)\",\n \"x-ui-description\":\n \"Fixed value this property must equal. Leave blank for none.\",\n },\n }\n : {}),\n ...validationProps(type),\n };\n return { title: \"\", type: \"object\", properties };\n}\n\n/** Extract flat Data-tab form values from a property + its required flag. */\nexport function propertyToDataValues(\n prop: JsonSchemaProperty,\n required: boolean,\n): DataFormValues {\n return {\n type: prop.oneOf ? \"oneOf\" : (prop.type ?? \"string\"),\n title: prop.title,\n description: prop.description,\n default: prop.default,\n // const may be any JSON type; the Data-tab field edits it as a string.\n const: prop.const == null ? undefined : String(prop.const),\n required,\n minLength: prop.minLength,\n maxLength: prop.maxLength,\n pattern: prop.pattern,\n format: prop.format,\n minimum: prop.minimum,\n maximum: prop.maximum,\n minItems: prop.minItems,\n maxItems: prop.maxItems,\n discriminator: prop.discriminator?.propertyName,\n };\n}\n\n/**\n * Produce the property patch (excluding `type` and `required`, which are\n * handled separately) from Data-tab form values. Empty strings/undefined clear\n * the corresponding key.\n */\nexport function dataValuesToPatch(\n values: DataFormValues,\n): Partial<JsonSchemaProperty> {\n const patch: Partial<JsonSchemaProperty> = {};\n const setStr = (k: keyof JsonSchemaProperty, v: unknown) => {\n if (typeof v === \"string\" && v.length > 0)\n (patch as Record<string, unknown>)[k] = v;\n else (patch as Record<string, unknown>)[k] = undefined;\n };\n const setNum = (k: keyof JsonSchemaProperty, v: unknown) => {\n if (typeof v === \"number\" && !Number.isNaN(v))\n (patch as Record<string, unknown>)[k] = v;\n else (patch as Record<string, unknown>)[k] = undefined;\n };\n setStr(\"title\", values.title);\n setStr(\"description\", values.description);\n setStr(\"default\", values.default);\n setStr(\"const\", values.const);\n setStr(\"format\", values.format);\n setStr(\"pattern\", values.pattern);\n setNum(\"minLength\", values.minLength);\n setNum(\"maxLength\", values.maxLength);\n setNum(\"minimum\", values.minimum);\n setNum(\"maximum\", values.maximum);\n setNum(\"minItems\", values.minItems);\n setNum(\"maxItems\", values.maxItems);\n // Discriminator: write discriminator.propertyName, or clear when blank.\n if (typeof values.discriminator === \"string\" && values.discriminator.length) {\n patch.discriminator = { propertyName: values.discriminator };\n } else {\n patch.discriminator = undefined;\n }\n return patch;\n}\n","/**\n * UITab -- edits a property's form presentation hints: the widget (x-ui-widget)\n * and its options (x-ui-options).\n *\n * The widget dropdown offers widgets compatible with the property's type (Auto\n * clears the override). The options editor is a JsonSchemaFormRenderer over a\n * schema derived from the selected widget's WidgetOptionDef[] (from the\n * design-time @petrarca/sonnet-forms/widget-options layer). Widgets with no\n * descriptor fall back to a raw JSON editor for x-ui-options.\n */\n\nimport React, { useMemo } from \"react\";\nimport { JsonSchemaFormRenderer } from \"@petrarca/sonnet-forms\";\nimport { JsonEditor } from \"@petrarca/sonnet-ui/json-editor\";\nimport {\n WIDGET_OPTION_DEFS,\n optionDefsToSchema,\n type WidgetOptionDef,\n} from \"@petrarca/sonnet-forms/widget-options\";\nimport { FormSelect } from \"@petrarca/sonnet-forms\";\nimport type {\n JsonSchema,\n UISchema,\n UISchemaOptions,\n UILayoutConfig,\n} from \"@petrarca/sonnet-core/schema\";\nimport type { DesignerState } from \"../hooks/useDesignerState\";\nimport type { PropertyNode } from \"../model/view\";\nimport { compatibleWidgets } from \"../model/compatibleWidgets\";\nimport { getUiEntryAtPath } from \"../model/mutate\";\nimport { pathKey } from \"../model/paths\";\n\nexport interface UITabProps {\n node: PropertyNode;\n state: DesignerState;\n /** Consumer-supplied option descriptors for custom widgets (merged over built-ins). */\n widgetOptions?: Record<string, WidgetOptionDef[]>;\n}\n\n// Meta-schema for the form presentation-text overrides. Keys are the actual\n// x-ui-* uiSchema keys so form data maps 1:1 to the entry.\nconst PRESENTATION_META_SCHEMA: JsonSchema = {\n title: \"\",\n type: \"object\",\n properties: {\n \"x-ui-title\": {\n type: \"string\",\n title: \"Label override\",\n description: \"Overrides the property title in the form.\",\n },\n \"x-ui-placeholder\": { type: \"string\", title: \"Placeholder\" },\n \"x-ui-description\": {\n type: \"string\",\n title: \"Help text\",\n \"x-ui-widget\": \"textarea\",\n },\n \"x-ui-width\": {\n type: \"string\",\n title: \"Field width\",\n description: \"Constrain the field's slot width in the form.\",\n enum: [\"full\", \"sm\", \"md\", \"lg\"],\n \"x-ui-options\": {\n enumNames: {\n full: \"Full width\",\n sm: \"Small\",\n md: \"Medium\",\n lg: \"Large\",\n },\n },\n },\n },\n};\n\n// Form presentation-text overrides (x-ui-title / x-ui-placeholder /\n// x-ui-description), written into the property's uiSchema entry.\nfunction PresentationEditor({\n fieldName,\n uiEntry,\n readOnly,\n onChange,\n}: {\n fieldName: string;\n uiEntry: UISchema;\n readOnly: boolean;\n onChange: (entry: UISchema) => void;\n}): React.ReactElement {\n const values = {\n \"x-ui-title\":\n typeof uiEntry[\"x-ui-title\"] === \"string\" ? uiEntry[\"x-ui-title\"] : \"\",\n \"x-ui-placeholder\": uiEntry[\"x-ui-placeholder\"] ?? \"\",\n \"x-ui-description\": uiEntry[\"x-ui-description\"] ?? \"\",\n \"x-ui-width\": uiEntry[\"x-ui-width\"] ?? \"full\",\n };\n\n const handleChange = (data: Record<string, unknown>) => {\n const next: UISchema = { ...uiEntry };\n for (const key of [\n \"x-ui-title\",\n \"x-ui-placeholder\",\n \"x-ui-description\",\n ] as const) {\n const v = data[key];\n if (typeof v === \"string\" && v.length > 0) next[key] = v;\n else delete next[key];\n }\n // Width: \"full\" is the default -- omit it to keep the uiSchema clean.\n const width = data[\"x-ui-width\"];\n if (width === \"sm\" || width === \"md\" || width === \"lg\") {\n next[\"x-ui-width\"] = width;\n } else {\n delete next[\"x-ui-width\"];\n }\n onChange(next);\n };\n\n return (\n <div>\n <p className=\"heading-meta mb-2\">Presentation (form overrides)</p>\n <JsonSchemaFormRenderer\n key={`${fieldName}:text`}\n schema={PRESENTATION_META_SCHEMA}\n data={values as Record<string, unknown>}\n onChange={handleChange}\n deferStateUpdates\n showActions={false}\n showExtraProperties={false}\n readOnly={readOnly}\n />\n </div>\n );\n}\n\n// Options editor: a generated form when the widget has descriptors, else a raw\n// JSON fallback. Kept separate to bound UITab's complexity.\nfunction OptionsEditor({\n widget,\n optionsSchema,\n currentOptions,\n readOnly,\n onChange,\n}: {\n widget: string;\n optionsSchema: JsonSchema | null;\n currentOptions: UISchemaOptions;\n readOnly: boolean;\n onChange: (opts: Record<string, unknown>) => void;\n}): React.ReactElement {\n if (optionsSchema) {\n return (\n <div>\n <p className=\"heading-meta mb-2\">Options</p>\n <JsonSchemaFormRenderer\n key={widget}\n schema={optionsSchema}\n data={currentOptions as Record<string, unknown>}\n onChange={onChange}\n deferStateUpdates\n showActions={false}\n showExtraProperties={false}\n readOnly={readOnly}\n />\n </div>\n );\n }\n return (\n <div>\n <p className=\"heading-meta mb-2\">Options (raw JSON)</p>\n <JsonEditor\n value={JSON.stringify(currentOptions ?? {}, null, 2)}\n editablePaths={readOnly ? [] : [\"/\"]}\n height=\"180px\"\n className=\"rounded-md border overflow-hidden\"\n onChange={(text) => {\n try {\n onChange(JSON.parse(text) as Record<string, unknown>);\n } catch {\n // ignore invalid JSON while typing\n }\n }}\n />\n </div>\n );\n}\n\nexport function UITab({\n node,\n state,\n widgetOptions,\n}: UITabProps): React.ReactElement {\n const idBase = pathKey(node.path);\n const uiEntry: UISchema = getUiEntryAtPath(state.uiSchema, node.path) ?? {};\n const currentWidget =\n typeof uiEntry[\"x-ui-widget\"] === \"string\"\n ? (uiEntry[\"x-ui-widget\"] as string)\n : null;\n const currentOptions = (uiEntry[\"x-ui-options\"] as UISchemaOptions) ?? {};\n\n // The form-level default this field inherits when it has no own override.\n const rootLayout = state.uiSchema[\"x-ui-layout\"] as\n | UILayoutConfig\n | undefined;\n const inheritedLabelPlacement = rootLayout?.labelPlacement ?? \"top\";\n\n const widgetChoices = useMemo(\n () => compatibleWidgets(node.property),\n [node.property],\n );\n\n const optionsSchema: JsonSchema | null = useMemo(() => {\n if (!currentWidget) return null;\n const merged = { ...WIDGET_OPTION_DEFS, ...(widgetOptions ?? {}) };\n const descriptors = merged[currentWidget];\n return descriptors && descriptors.length\n ? optionDefsToSchema(descriptors)\n : null;\n }, [currentWidget, widgetOptions]);\n\n const setWidget = (value: string | null) => {\n const next: UISchema = { ...uiEntry };\n if (value) next[\"x-ui-widget\"] = value;\n else delete next[\"x-ui-widget\"];\n state.setUiEntry(node.path, next);\n };\n\n const setOptions = (opts: Record<string, unknown>) => {\n const next: UISchema = { ...uiEntry };\n const cleaned = Object.fromEntries(\n Object.entries(opts).filter(([, v]) => v !== undefined && v !== \"\"),\n );\n if (Object.keys(cleaned).length) next[\"x-ui-options\"] = cleaned;\n else delete next[\"x-ui-options\"];\n state.setUiEntry(node.path, next);\n };\n\n // Label placement lives on x-ui-options. Three states in the UI:\n // \"__inherit__\" -> no key set; the field inherits the form-level default.\n // \"top\" / \"start\" -> an explicit per-field override.\n // Only an explicit value writes the key (and prunes an emptied x-ui-options).\n const setLabelPlacement = (value: string) => {\n const opts: UISchemaOptions = { ...currentOptions };\n if (value === \"top\" || value === \"start\") {\n opts.labelPlacement = value;\n } else {\n delete opts.labelPlacement;\n }\n const next: UISchema = { ...uiEntry };\n if (Object.keys(opts).length) next[\"x-ui-options\"] = opts;\n else delete next[\"x-ui-options\"];\n state.setUiEntry(node.path, next);\n };\n\n return (\n <div className=\"space-y-4\">\n <FormSelect\n id={`${idBase}-widget`}\n name=\"widget\"\n label=\"Widget\"\n value={currentWidget ?? \"__auto__\"}\n options={widgetChoices.map((c) => ({\n value: c.value ?? \"__auto__\",\n label: c.label,\n }))}\n onChange={(v) => setWidget(v === \"__auto__\" ? null : (v ?? null))}\n disabled={state.readOnly}\n clearable={false}\n />\n\n {currentWidget && (\n <OptionsEditor\n widget={`${idBase}:${currentWidget}`}\n optionsSchema={optionsSchema}\n currentOptions={currentOptions}\n readOnly={state.readOnly}\n onChange={setOptions}\n />\n )}\n\n <PresentationEditor\n fieldName={idBase}\n uiEntry={uiEntry}\n readOnly={state.readOnly}\n onChange={(entry) => state.setUiEntry(node.path, entry)}\n />\n\n <FormSelect\n id={`${idBase}-labelPlacement`}\n name=\"labelPlacement\"\n label=\"Label placement\"\n value={currentOptions.labelPlacement ?? \"__inherit__\"}\n options={[\n {\n value: \"__inherit__\",\n label: `Inherit (${inheritedLabelPlacement === \"start\" ? \"inline\" : \"above\"})`,\n },\n { value: \"top\", label: \"Above\" },\n { value: \"start\", label: \"Inline (start)\" },\n ]}\n onChange={(v) => setLabelPlacement(v ?? \"__inherit__\")}\n disabled={state.readOnly}\n clearable={false}\n />\n </div>\n );\n}\n","/**\n * EnumEditor -- edits a scalar property's allowed values (enum) and optional\n * display labels, as a row list.\n *\n * Each choice is a row: [value] [label] [remove]. An Add button appends a row.\n * Values write to property.enum; labels write to x-ui-options.enumNames (only\n * for top-level properties). All changes route through setEnum, which normalizes,\n * dedupes, and clears when empty.\n */\n\nimport React, { useEffect, useState } from \"react\";\nimport { Input, IconButton, Button } from \"@petrarca/sonnet-ui\";\nimport { Plus, Trash2 } from \"lucide-react\";\nimport type { DesignerState } from \"../hooks/useDesignerState\";\nimport type { PropertyNode } from \"../model/view\";\nimport { pathKey } from \"../model/paths\";\nimport {\n readEnumChoices,\n getUiEntryAtPath,\n type EnumChoice,\n} from \"../model/mutate\";\n\nexport interface EnumEditorProps {\n node: PropertyNode;\n state: DesignerState;\n}\n\nexport function EnumEditor({\n node,\n state,\n}: EnumEditorProps): React.ReactElement {\n // Local draft so typing an empty/duplicate value mid-edit is not dropped by\n // the normalizing mutation. Re-seed when the selected property changes.\n const [rows, setRows] = useState<EnumChoice[]>(() =>\n readEnumChoices(node.property, getUiEntryAtPath(state.uiSchema, node.path)),\n );\n useEffect(() => {\n setRows(\n readEnumChoices(\n node.property,\n getUiEntryAtPath(state.uiSchema, node.path),\n ),\n );\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [pathKey(node.path)]);\n\n const canEditLabels = true;\n\n const commit = (next: EnumChoice[]) => {\n setRows(next);\n state.setEnum(node.path, next);\n };\n\n const updateRow = (i: number, patch: Partial<EnumChoice>) => {\n commit(rows.map((r, idx) => (idx === i ? { ...r, ...patch } : r)));\n };\n const removeRow = (i: number) => commit(rows.filter((_, idx) => idx !== i));\n const addRow = () => setRows([...rows, { value: \"\", label: \"\" }]);\n\n return (\n <div className=\"space-y-3\">\n <div>\n <p className=\"text-sm font-medium\">Allowed values</p>\n <p className=\"text-xs text-muted-foreground\">\n Define a fixed set of choices. Leave empty for free input.\n </p>\n </div>\n\n {rows.length === 0 ? (\n <p className=\"text-xs text-muted-foreground\">No choices yet.</p>\n ) : (\n <div className=\"space-y-2\">\n {canEditLabels && (\n <div className=\"flex items-center gap-2 px-1\">\n <span className=\"heading-meta flex-1\">Value</span>\n <span className=\"heading-meta flex-1\">Label (optional)</span>\n <span className=\"w-7\" />\n </div>\n )}\n {rows.map((row, i) => (\n <div key={i} className=\"flex items-center gap-2\">\n <Input\n value={row.value}\n onChange={(e) => updateRow(i, { value: e.target.value })}\n placeholder=\"value\"\n disabled={state.readOnly}\n className=\"h-8 text-sm flex-1\"\n />\n {canEditLabels && (\n <Input\n value={row.label ?? \"\"}\n onChange={(e) => updateRow(i, { label: e.target.value })}\n placeholder={row.value || \"label\"}\n disabled={state.readOnly}\n className=\"h-8 text-sm flex-1\"\n />\n )}\n {!state.readOnly && (\n <IconButton\n label=\"Remove value\"\n tone=\"destructive\"\n onClick={() => removeRow(i)}\n >\n <Trash2 />\n </IconButton>\n )}\n </div>\n ))}\n </div>\n )}\n\n {!state.readOnly && (\n <Button\n variant=\"outline\"\n size=\"sm\"\n className=\"gap-1.5\"\n onClick={addRow}\n >\n <Plus className=\"h-4 w-4\" />\n Add value\n </Button>\n )}\n </div>\n );\n}\n","/**\n * TableHintsTab -- edits a property's table presentation hints (x-ui-cell,\n * x-ui-column, x-ui-cell-options), which EntityTable reads. These are embedded\n * on the schema property (not the uiSchema map). Live in the Table preview.\n *\n * The cell renderer list is derived from sonnet-ui's exported CELL_RENDERERS,\n * so it stays in sync with the actual table renderers. Cell options are edited\n * as raw JSON (varies per renderer).\n */\n\nimport React, { useMemo } from \"react\";\nimport { CELL_RENDERERS } from \"@petrarca/sonnet-ui\";\nimport { JsonEditor } from \"@petrarca/sonnet-ui/json-editor\";\nimport { FormSelect, JsonSchemaFormRenderer } from \"@petrarca/sonnet-forms\";\nimport type { JsonSchema } from \"@petrarca/sonnet-core/schema\";\nimport type { DesignerState } from \"../hooks/useDesignerState\";\nimport type { PropertyNode } from \"../model/view\";\nimport { readTableHints, type TableHints } from \"../model/mutate\";\nimport { pathKey } from \"../model/paths\";\n\nexport interface TableHintsTabProps {\n node: PropertyNode;\n state: DesignerState;\n}\n\nconst CELL_NAMES = Object.keys(CELL_RENDERERS);\n\n// Column meta-schema (flat fields; recomposed into x-ui-column on write).\nconst COLUMN_META_SCHEMA: JsonSchema = {\n title: \"\",\n type: \"object\",\n properties: {\n hidden: { type: \"boolean\", title: \"Hide column\" },\n order: { type: \"integer\", title: \"Column order\" },\n width: { type: \"integer\", title: \"Width (px)\", minimum: 0 },\n minWidth: { type: \"integer\", title: \"Min width (px)\", minimum: 0 },\n },\n};\n\ninterface ColumnFormValues {\n hidden?: boolean;\n order?: number;\n width?: number;\n minWidth?: number;\n}\n\nexport function TableHintsTab({\n node,\n state,\n}: TableHintsTabProps): React.ReactElement {\n const hints = readTableHints(node.property);\n\n const cellOptions = useMemo(\n () => JSON.stringify(hints.cellOptions ?? {}, null, 2),\n [hints.cellOptions],\n );\n\n const commit = (patch: Partial<TableHints>) =>\n state.setTableHints(node.path, { ...hints, ...patch });\n\n const columnValues: ColumnFormValues = {\n hidden: hints.column?.hidden,\n order: hints.column?.order,\n width: hints.column?.width,\n minWidth: hints.column?.minWidth,\n };\n\n const onColumnChange = (data: Record<string, unknown>) => {\n const v = data as ColumnFormValues;\n const column: NonNullable<TableHints[\"column\"]> = {};\n if (typeof v.hidden === \"boolean\") column.hidden = v.hidden;\n if (typeof v.order === \"number\" && !Number.isNaN(v.order))\n column.order = v.order;\n if (typeof v.width === \"number\" && !Number.isNaN(v.width))\n column.width = v.width;\n if (typeof v.minWidth === \"number\" && !Number.isNaN(v.minWidth))\n column.minWidth = v.minWidth;\n commit({ column });\n };\n\n return (\n <div className=\"space-y-4\">\n <FormSelect\n id={`${node.key}-cell`}\n name=\"cell\"\n label=\"Cell renderer\"\n value={hints.cell ?? \"__auto__\"}\n options={[\n { value: \"__auto__\", label: \"Auto (infer from type)\" },\n ...CELL_NAMES.map((n) => ({ value: n, label: n })),\n ]}\n onChange={(v: string | null) =>\n commit({ cell: !v || v === \"__auto__\" ? undefined : v })\n }\n disabled={state.readOnly}\n clearable={false}\n />\n\n <div>\n <p className=\"heading-meta mb-2\">Column</p>\n <JsonSchemaFormRenderer\n key={pathKey(node.path)}\n schema={COLUMN_META_SCHEMA}\n data={columnValues as Record<string, unknown>}\n onChange={onColumnChange}\n deferStateUpdates\n showActions={false}\n showExtraProperties={false}\n readOnly={state.readOnly}\n />\n </div>\n\n <div>\n <p className=\"heading-meta mb-2\">Cell options (JSON)</p>\n <JsonEditor\n value={cellOptions}\n editablePaths={state.readOnly ? [] : [\"/\"]}\n height=\"160px\"\n className=\"rounded-md border overflow-hidden\"\n onChange={(text) => {\n try {\n commit({\n cellOptions: JSON.parse(text) as Record<string, unknown>,\n });\n } catch {\n // ignore invalid JSON while typing\n }\n }}\n />\n </div>\n </div>\n );\n}\n","/**\n * ConditionEditor -- edits the `if` of a conditional (if/then/else) member.\n *\n * A condition tests a sibling property of the object that owns the conditional:\n * pick the property, an operator, and a value. The three combine into the `if`\n * sub-schema via conditionToIf; the renderer evaluates it live. then/else fields\n * are edited as child nodes in the tree, not here.\n */\n\nimport React, { useMemo } from \"react\";\nimport { FormSelect } from \"@petrarca/sonnet-forms\";\nimport type { JsonSchemaProperty } from \"@petrarca/sonnet-core/schema\";\nimport type { DesignerState } from \"../hooks/useDesignerState\";\nimport type { PropertyNode } from \"../model/view\";\nimport { getProperty } from \"../model/paths\";\nimport {\n conditionToIf,\n ifToCondition,\n OPERATOR_OPTIONS,\n type Condition,\n type ConditionOperator,\n} from \"../model/conditions\";\nimport { OperatorValueInput } from \"./OperatorValueInput\";\n\nexport interface ConditionEditorProps {\n node: PropertyNode;\n state: DesignerState;\n}\n\n// Sibling property names of the object that owns this conditional (the path\n// minus the trailing condition segment).\nfunction siblingFields(\n state: DesignerState,\n node: PropertyNode,\n): Record<string, JsonSchemaProperty> {\n const objectPath = node.path.slice(0, -1);\n const owner =\n objectPath.length === 0\n ? { properties: state.schema.properties }\n : getProperty(state.schema, objectPath);\n return owner?.properties ?? {};\n}\n\nexport function ConditionEditor({\n node,\n state,\n}: ConditionEditorProps): React.ReactElement {\n const condition = useMemo(\n () => ifToCondition(node.property.if),\n [node.property.if],\n );\n const fieldProps = useMemo(() => siblingFields(state, node), [state, node]);\n const fields = useMemo(() => Object.keys(fieldProps), [fieldProps]);\n const disabled = state.readOnly;\n\n // The combinator (AND/OR) is carried by the condition segment; it applies to\n // every condition on the owning object. Switching it migrates all of them.\n const lastSeg = node.path[node.path.length - 1];\n const combinator =\n lastSeg?.kind === \"condition\" ? lastSeg.combinator : \"allOf\";\n const objectPath = node.path.slice(0, -1);\n\n const commit = (next: Condition): void => {\n // Pass the target field's type so a boolean comparand is written as a\n // boolean, not the string \"true\" (which could never match).\n const ifSchema = conditionToIf(next, fieldProps[next.field]?.type);\n if (ifSchema) state.setCondition(node.path, ifSchema);\n };\n\n const fieldOptions = fields.map((f) => ({ value: f, label: f }));\n const needsValue = condition.operator !== \"exists\";\n\n return (\n <div className=\"space-y-3\">\n <p className=\"text-xs text-muted-foreground\">\n Show the <span className=\"font-medium\">then</span> fields when this\n condition holds (otherwise the <span className=\"font-medium\">else</span>{\" \"}\n fields, if any).\n </p>\n\n <FormSelect\n id=\"condition-match\"\n name=\"match\"\n label=\"Match (all conditions on this object)\"\n options={[\n { value: \"allOf\", label: \"All (AND)\" },\n { value: \"anyOf\", label: \"Any (OR)\" },\n ]}\n value={combinator}\n onChange={(v) =>\n state.setConditionalBehavior(\n objectPath,\n v === \"anyOf\" ? \"anyOf\" : \"allOf\",\n )\n }\n clearable={false}\n disabled={disabled}\n />\n\n <FormSelect\n id=\"condition-field\"\n name=\"field\"\n label=\"When property\"\n options={fieldOptions}\n value={condition.field || null}\n onChange={(v) => commit({ ...condition, field: v ?? \"\" })}\n placeholder=\"Select a property...\"\n clearable={false}\n disabled={disabled}\n />\n\n <FormSelect\n id=\"condition-operator\"\n name=\"operator\"\n label=\"Operator\"\n options={OPERATOR_OPTIONS}\n value={condition.operator}\n onChange={(v) =>\n commit({ ...condition, operator: (v as ConditionOperator) ?? \"=\" })\n }\n clearable={false}\n disabled={disabled}\n />\n\n {needsValue && (\n <OperatorValueInput\n id=\"condition-value\"\n cacheKey={`${node.path.length}:${condition.field}:${condition.operator}`}\n value={condition.value}\n onCommit={(v) => commit({ ...condition, value: v })}\n disabled={disabled || !condition.field}\n />\n )}\n </div>\n );\n}\n","/**\n * RuleEditor -- authors a field's declarative presentation rule (x-ui-rule):\n * show / hide / enable / disable this field based on another field's value.\n *\n * Unlike if/then/else, the field stays declared at its own position; the rule\n * only toggles presentation. The condition references another field by JSON\n * Pointer (scope) and an operator + value. The rule is stored on the property\n * and evaluated live by the renderer (evaluateUiRule).\n */\n\nimport React, { useMemo } from \"react\";\nimport type { JsonSchemaProperty } from \"@petrarca/sonnet-core/schema\";\nimport type { DesignerState } from \"../hooks/useDesignerState\";\nimport type { PropertyNode } from \"../model/view\";\nimport { RuleFields, type ScopeOption } from \"./RuleFields\";\nimport { FIELD_EFFECT_OPTIONS } from \"./ruleEffects\";\n\nexport interface RuleEditorProps {\n node: PropertyNode;\n state: DesignerState;\n}\n\n// Sibling field pointers as scope candidates (e.g. \"/gender\"). A conditional's\n// scope is a JSON Pointer into form data; v1 offers siblings, deeper pointers\n// can be hand-authored in the source tab.\nfunction siblingPointers(\n state: DesignerState,\n node: PropertyNode,\n): ScopeOption[] {\n // The node's own key is the last prop segment; siblings are the parent's keys.\n const parentProps =\n node.path.length <= 1\n ? state.schema.properties\n : findParentProperties(state, node);\n const self = node.key;\n return Object.entries(parentProps ?? {})\n .filter(([k]) => k !== self)\n .map(([k, prop]) => ({ pointer: `/${k}`, type: prop.type }));\n}\n\n// The properties map of the node's parent container (best-effort; root when top).\nfunction findParentProperties(\n state: DesignerState,\n node: PropertyNode,\n): Record<string, JsonSchemaProperty> | undefined {\n // Walk the schema following prop segments up to (but excluding) the last.\n let props: Record<string, JsonSchemaProperty> | undefined =\n state.schema.properties;\n for (let i = 0; i < node.path.length - 1; i++) {\n const seg = node.path[i];\n if (seg.kind !== \"prop\" || !props) return undefined;\n const next: JsonSchemaProperty | undefined = props[seg.key];\n props = next?.type === \"array\" ? next.items?.properties : next?.properties;\n if (!props) return undefined;\n }\n return props;\n}\n\nexport function RuleEditor({\n node,\n state,\n}: RuleEditorProps): React.ReactElement {\n const scopes = useMemo(() => siblingPointers(state, node), [state, node]);\n return (\n <div className=\"space-y-3\">\n <p className=\"text-xs text-muted-foreground\">\n Toggle this field's visibility (or enabled state) based on another\n field's value. The field keeps its position in the form.\n </p>\n <RuleFields\n rule={node.property[\"x-ui-rule\"]}\n scopes={scopes}\n effects={FIELD_EFFECT_OPTIONS}\n idPrefix=\"rule\"\n disabled={state.readOnly}\n onChange={(rule) =>\n state.updateProperty(node.path, { \"x-ui-rule\": rule })\n }\n />\n </div>\n );\n}\n","/**\n * ReferenceTab -- the Data tab for a `$ref` node. In JSON Schema 2020-12,\n * annotation keywords alongside `$ref` apply at the referencing site, so a\n * reference may carry local overrides (title, description, default, required)\n * on top of the shared definition. Structural type/validation belongs to the\n * definition and is edited there; here we offer only the overrides plus a\n * \"Stop referencing\" action that converts the property back to a concrete type.\n */\n\nimport React, { useMemo, useRef } from \"react\";\nimport { JsonSchemaFormRenderer } from \"@petrarca/sonnet-forms\";\nimport { Button } from \"@petrarca/sonnet-ui\";\nimport type { JsonSchemaProperty } from \"@petrarca/sonnet-core/schema\";\nimport type { DesignerState } from \"../hooks/useDesignerState\";\nimport type { PropertyNode } from \"../model/view\";\nimport { pathKey } from \"../model/paths\";\nimport { buildReferenceMetaSchema } from \"./metaSchemas\";\n\nexport interface ReferenceTabProps {\n node: PropertyNode;\n state: DesignerState;\n}\n\n// The override values a reference carries at its use site.\ninterface RefOverrides {\n title?: string;\n description?: string;\n default?: string;\n required: boolean;\n}\n\n// The reference's own overrides (from node.property, which keeps the $ref +\n// sibling keys -- not the resolved target).\nfunction toOverrides(\n prop: JsonSchemaProperty,\n required: boolean,\n): RefOverrides {\n return {\n title: prop.title,\n description: prop.description,\n // Coerce to string for the text field; non-string defaults (number, boolean)\n // are serialised and written back as strings -- v1 limitation.\n default: prop.default == null ? undefined : String(prop.default),\n required,\n };\n}\n\n// The property patch for changed override values; empty strings clear the key.\nfunction toPatch(values: RefOverrides): Partial<JsonSchemaProperty> {\n const str = (v: unknown) =>\n typeof v === \"string\" && v.length > 0 ? v : undefined;\n return {\n title: str(values.title),\n description: str(values.description),\n default: str(values.default),\n };\n}\n\nexport function ReferenceTab({\n node,\n state,\n}: ReferenceTabProps): React.ReactElement {\n const schema = useMemo(() => buildReferenceMetaSchema(), []);\n const values = useMemo(\n () => toOverrides(node.property, node.required),\n [node.property, node.required],\n );\n const prevRef = useRef<RefOverrides>(values);\n prevRef.current = values;\n\n const handleChange = (data: Record<string, unknown>) => {\n const next = data as unknown as RefOverrides;\n const prev = prevRef.current;\n // Required lives on the parent's required[], not on the property.\n if (next.required !== prev.required) {\n state.setRequired(node.path, !!next.required);\n return;\n }\n state.updateProperty(node.path, toPatch(next));\n };\n\n return (\n <div className=\"space-y-4\">\n <p className=\"text-sm text-muted-foreground\">\n References <span className=\"font-medium\">{node.reference}</span>. Its\n fields come from a shared definition (read-only here -- edit the\n definition to change all usages). The values below override the label,\n help text, and default for this usage only.\n </p>\n <JsonSchemaFormRenderer\n key={pathKey(node.path)}\n schema={schema}\n data={values as unknown as Record<string, unknown>}\n onChange={handleChange}\n deferStateUpdates\n showActions={false}\n showExtraProperties={false}\n readOnly={state.readOnly}\n />\n {!state.readOnly && state.canEditProperty(node.path) && (\n <div className=\"border-t pt-3\">\n <Button\n variant=\"outline\"\n size=\"sm\"\n onClick={() => state.changePropertyType(node.path, \"string\")}\n >\n Stop referencing\n </Button>\n <p className=\"mt-1 text-xs text-muted-foreground\">\n Removes the reference and turns this into an editable property.\n </p>\n </div>\n )}\n </div>\n );\n}\n"],"mappings":";AAoBA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AA2BA,SAAS,cAAc,KAAsB;AAClD,SAAO,iCAAiC,KAAK,GAAG;AAClD;AAGO,SAAS,KAAK,KAA0B;AAC7C,SAAO,EAAE,MAAM,QAAQ,IAAI;AAC7B;AAGO,SAAS,OAAO,OAA4B;AACjD,SAAO,EAAE,MAAM,UAAU,MAAM;AACjC;AAGO,SAAS,UACd,OACA,aAAkC,SACrB;AACb,SAAO,EAAE,MAAM,aAAa,YAAY,MAAM;AAChD;AAGO,SAAS,KAAK,MAA6B;AAChD,SAAO,EAAE,MAAM,QAAQ,MAAM,KAAK;AACpC;AAGO,SAAS,IAAI,MAA2B;AAC7C,SAAO,EAAE,MAAM,OAAO,KAAK;AAC7B;AAOA,IAAM,MAAM;AAGZ,SAAS,YAAY,KAAqB;AAC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A,eACF;AAAA,YACA,gBAAAA,MAAC,aAAU,OAAc,eAAe,MAAM,eAAe;AAAA;AAAA;AAAA,MAC/D;AAAA,OACF;AAAA,IAED,sBACC,gBAAAC,OAAC,SAAI,WAAU,0DACb;AAAA,sBAAAD;AAAA,QAACI;AAAA,QAAA;AAAA,UACC,OAAM;AAAA,UACN,SAAS,MAAM,sBAAsB,KAAK;AAAA,UAE1C,0BAAAJ,MAAC,kBAAe;AAAA;AAAA,MAClB;AAAA,MACA,gBAAAA;AAAA,QAACI;AAAA,QAAA;AAAA,UACC,OAAM;AAAA,UACN,SAAS,MAAM,gBAAgB,IAAI;AAAA,UAEnC,0BAAAJ,MAAC,YAAS;AAAA;AAAA,MACZ;AAAA,OACF;AAAA,IAGF,gBAAAA;AAAA,MAAC;AAAA;AAAA,QACC,MAAM;AAAA,QACN,cAAc;AAAA,QACd;AAAA;AAAA,IACF;AAAA,KACF;AAEJ;","names":["prop","isOneOf","prop","slot","prop","row","prop","prop","escapeToken","prop","useEffect","useState","IconButton","useMemo","useRef","useState","jsx","jsxs","useMemo","useState","useRef","isConditionalMember","isOneOf","useMemo","useState","JsonSchemaFormRenderer","useMemo","prop","jsx","useMemo","useMemo","useState","cn","Input","IconButton","FormSelect","JsonSchemaFormRenderer","Plus","Trash2","ChevronUp","ChevronDown","ChevronRight","useEffect","useMemo","useState","FormSelect","condition","Input","jsx","jsxs","Fragment","jsx","jsxs","useState","useEffect","useMemo","FormSelect","Fragment","jsx","jsxs","prop","JsonSchemaFormRenderer","useMemo","useState","Plus","FormSelect","cn","ChevronDown","ChevronRight","Input","IconButton","Trash2","ChevronUp","useMemo","useEffect","useRef","useState","Button","jsx","jsxs","jsx","useMemo","Fragment","jsx","jsxs","useState","useMemo","JsonSchemaFormRenderer","useEffect","useMemo","useRef","useState","Tabs","TabsList","TabsTrigger","TabsContent","Input","IconButton","Check","useMemo","useRef","JsonSchemaFormRenderer","isOneOf","isContainer","prop","jsx","jsxs","useMemo","useRef","JsonSchemaFormRenderer","useMemo","JsonSchemaFormRenderer","JsonEditor","FormSelect","jsx","jsxs","JsonSchemaFormRenderer","JsonEditor","useMemo","FormSelect","useEffect","useState","Input","IconButton","Button","Plus","Trash2","jsx","jsxs","useState","useEffect","Input","IconButton","Trash2","Button","Plus","useMemo","JsonEditor","FormSelect","JsonSchemaFormRenderer","jsx","jsxs","useMemo","FormSelect","JsonSchemaFormRenderer","JsonEditor","useMemo","FormSelect","jsx","jsxs","condition","useMemo","FormSelect","useMemo","jsx","jsxs","prop","useMemo","useMemo","useRef","JsonSchemaFormRenderer","Button","jsx","jsxs","prop","useMemo","useRef","JsonSchemaFormRenderer","Button","jsx","jsxs","useState","useRef","useEffect","IconButton","Input","Check","Tabs","TabsList","TabsTrigger","TabsContent","useMemo","Fragment","jsx","jsxs","useState","useEffect","IconButton"]}
|
|
1
|
+
{"version":3,"sources":["../src/model/paths.ts","../src/model/view.ts","../src/model/mutate.ts","../src/model/compatibleWidgets.ts","../src/model/embed.ts","../src/hooks/useDesignerState.ts","../src/capabilities.ts","../src/model/scoping.ts","../src/SchemaDesigner.tsx","../src/FormSettingsSheet.tsx","../src/inspector/layoutMetaSchemas.ts","../src/tree/PropertyTree.tsx","../src/preview/PreviewPane.tsx","../src/preview/TablePreview.tsx","../src/preview/sampleRows.ts","../src/designers/FormLayoutDesigner.tsx","../src/inspector/RuleFields.tsx","../src/model/conditions.ts","../src/inspector/OperatorValueInput.tsx","../src/inspector/ruleEffects.ts","../src/preview/CapabilitiesPanel.tsx","../src/preview/SchemaSourcePanel.tsx","../src/inspector/Inspector.tsx","../src/inspector/DataTab.tsx","../src/inspector/metaSchemas.ts","../src/inspector/UITab.tsx","../src/inspector/EnumEditor.tsx","../src/inspector/TableHintsTab.tsx","../src/inspector/ConditionEditor.tsx","../src/inspector/RuleEditor.tsx","../src/inspector/ruleScopes.ts","../src/inspector/ReferenceTab.tsx"],"sourcesContent":["/**\n * Path navigation over a JsonSchema tree.\n *\n * A path is a list of typed segments from the root down to a property. Most\n * segments are property keys (`{kind:\"prop\"}`) -- object children nest through\n * `properties`, array-of-object children through `items.properties`, and the\n * navigator descends through `items` transparently so an array and its item\n * object share one editing surface.\n *\n * Logic constructs introduce non-property segments: `{kind:\"branch\"}` for a\n * `oneOf`/`allOf` element, and `{kind:\"slot\"}` for a fixed schema slot\n * (`then`/`else`/`items`). The discriminated union keeps the distinction\n * explicit and type-checked; a single codec (pathKey/parsePathKey) owns all\n * conversion to/from strings.\n */\n\nimport type {\n JsonSchema,\n JsonSchemaProperty,\n} from \"@petrarca/sonnet-core/schema\";\nimport {\n isOneOf,\n getDiscriminator,\n getBranchLabel,\n} from \"@petrarca/sonnet-core/schema\";\n\n/** A fixed schema slot that holds a single sub-schema. */\nexport type PathSlot = \"then\" | \"else\" | \"items\";\n\n/**\n * The array a conditional (if/then/else) member lives in. `allOf` = every\n * condition must hold (AND); `anyOf` = any condition suffices (OR). Maps to\n * FHIR `enableBehavior` \"all\" / \"any\".\n */\nexport type ConditionCombinator = \"allOf\" | \"anyOf\";\n\n/** One step in a property path. */\nexport type PathSegment =\n | { kind: \"prop\"; key: string }\n | { kind: \"branch\"; index: number }\n | { kind: \"condition\"; combinator: ConditionCombinator; index: number }\n | { kind: \"slot\"; slot: PathSlot }\n | { kind: \"def\"; name: string };\n\nexport type PropertyPath = PathSegment[];\n\n/**\n * Whether a property key is reserved by the path codec. Keys matching\n * `/^#(branch|condition|def|slot):/` would corrupt the pathKey/parsePathKey\n * round-trip. The designer guards against these at rename/add time.\n */\nexport function isReservedKey(key: string): boolean {\n return /^#(branch|condition|def|slot):/.test(key);\n}\n\n/** Construct a property-key segment. */\nexport function prop(key: string): PathSegment {\n return { kind: \"prop\", key };\n}\n\n/** Construct a branch (oneOf element) segment. */\nexport function branch(index: number): PathSegment {\n return { kind: \"branch\", index };\n}\n\n/** Construct a condition (if/then/else member) segment for a combinator array. */\nexport function condition(\n index: number,\n combinator: ConditionCombinator = \"allOf\",\n): PathSegment {\n return { kind: \"condition\", combinator, index };\n}\n\n/** Construct a fixed-slot segment. */\nexport function slot(name: PathSlot): PathSegment {\n return { kind: \"slot\", slot: name };\n}\n\n/** Construct a definition ($defs entry) segment. Root-only in practice. */\nexport function def(name: string): PathSegment {\n return { kind: \"def\", name };\n}\n\n// ---- Codec: the single segment <-> string boundary ------------------------\n\n// Non-prop segments use a reserved \"#\" prefix that cannot be a JSON Schema\n// property key produced by the designer. Prop keys are percent-ish escaped so\n// the \".\" join is reversible even for keys containing separators.\nconst SEP = \"/\";\n\n// Escape backslash first, then the separator, so parse is unambiguous.\nfunction escapeToken(raw: string): string {\n return raw.replace(/\\\\/g, \"\\\\\\\\\").replace(/\\//g, \"\\\\/\");\n}\n\nfunction unescapeToken(raw: string): string {\n return raw.replace(/\\\\\\//g, \"/\").replace(/\\\\\\\\/g, \"\\\\\");\n}\n\nfunction encodeSegment(seg: PathSegment): string {\n switch (seg.kind) {\n case \"prop\":\n return escapeToken(seg.key);\n case \"branch\":\n return `#branch:${seg.index}`;\n case \"condition\":\n return `#condition:${seg.combinator}:${seg.index}`;\n case \"slot\":\n return `#slot:${seg.slot}`;\n case \"def\":\n return `#def:${escapeToken(seg.name)}`;\n }\n}\n\nconst VALID_SLOTS: readonly PathSlot[] = [\"then\", \"else\", \"items\"];\n\n// Parse a non-negative integer, defaulting to 0 for tampered/invalid tokens.\nfunction safeIndex(raw: string): number {\n const n = Number(raw);\n return Number.isInteger(n) && n >= 0 ? n : 0;\n}\n\n// Decode \"#condition:<combinator>:<index>\" (legacy \"#condition:<index>\" -> allOf).\nfunction decodeCondition(rest: string): PathSegment {\n const sep = rest.indexOf(\":\");\n const combinatorRaw = sep >= 0 ? rest.slice(0, sep) : \"allOf\";\n const combinator: ConditionCombinator =\n combinatorRaw === \"anyOf\" ? \"anyOf\" : \"allOf\";\n const index = safeIndex(sep >= 0 ? rest.slice(sep + 1) : rest);\n return { kind: \"condition\", combinator, index };\n}\n\nfunction decodeSegment(token: string): PathSegment {\n if (token.startsWith(\"#branch:\")) {\n return { kind: \"branch\", index: safeIndex(token.slice(\"#branch:\".length)) };\n }\n if (token.startsWith(\"#condition:\")) {\n return decodeCondition(token.slice(\"#condition:\".length));\n }\n if (token.startsWith(\"#slot:\")) {\n const s = token.slice(\"#slot:\".length) as PathSlot;\n return { kind: \"slot\", slot: VALID_SLOTS.includes(s) ? s : \"items\" };\n }\n if (token.startsWith(\"#def:\")) {\n return { kind: \"def\", name: unescapeToken(token.slice(\"#def:\".length)) };\n }\n return { kind: \"prop\", key: unescapeToken(token) };\n}\n\n// Split on unescaped separators.\nfunction splitTokens(key: string): string[] {\n const tokens: string[] = [];\n let current = \"\";\n for (let i = 0; i < key.length; i++) {\n const ch = key[i];\n if (ch === \"\\\\\" && i + 1 < key.length) {\n current += ch + key[i + 1];\n i++;\n } else if (ch === SEP) {\n tokens.push(current);\n current = \"\";\n } else {\n current += ch;\n }\n }\n tokens.push(current);\n return tokens;\n}\n\n/** Serialize a path to a stable string (React key, selection id, scope value). */\nexport function pathKey(path: PropertyPath): string {\n return path.map(encodeSegment).join(SEP);\n}\n\n/** Parse a string produced by {@link pathKey} back into a path. */\nexport function parsePathKey(key: string): PropertyPath {\n if (key === \"\") return [];\n return splitTokens(key).map(decodeSegment);\n}\n\n// ---- Comparison -----------------------------------------------------------\n\n// A stable string identity for a segment's payload; two segments are equal iff\n// their kind and identity string match. Keeps sameSegment's complexity flat.\nfunction segmentIdentity(seg: PathSegment): string {\n switch (seg.kind) {\n case \"prop\":\n return `prop:${seg.key}`;\n case \"branch\":\n return `branch:${seg.index}`;\n case \"condition\":\n return `condition:${seg.combinator}:${seg.index}`;\n case \"slot\":\n return `slot:${seg.slot}`;\n case \"def\":\n return `def:${seg.name}`;\n }\n}\n\n/** Whether two path segments refer to the same position. */\nexport function sameSegment(a: PathSegment, b: PathSegment): boolean {\n return segmentIdentity(a) === segmentIdentity(b);\n}\n\n/** Whether two paths refer to the same node (structural comparison). */\nexport function samePath(\n a: PropertyPath | null,\n b: PropertyPath | null,\n): boolean {\n if (a === null || b === null) return a === b;\n return a.length === b.length && a.every((seg, i) => sameSegment(seg, b[i]));\n}\n\n// ---- Child slots (the container abstraction) ------------------------------\n\n/** How a child slot is presented and mutated. */\nexport type SlotKind = \"property\" | \"branch\" | \"conditional\" | \"definition\";\n\n/** A single editable child of a property (or the root). */\nexport interface ChildSlot {\n /** Segment appended to the parent path to reach this child. */\n segment: PathSegment;\n /** Display label for the tree row. */\n label: string;\n /** The child schema. */\n property: JsonSchemaProperty;\n kind: SlotKind;\n removable: boolean;\n reorderable: boolean;\n}\n\n/**\n * The properties map that holds a property's named children, or undefined when\n * it has none. Object children live in `properties`; array-of-object children\n * live in `items.properties`. (Logic constructs use branch/slot children and\n * are surfaced via {@link childSlots}, not here.)\n */\nexport function childContainer(\n prop: JsonSchemaProperty,\n): Record<string, JsonSchemaProperty> | undefined {\n // A oneOf branch is an object-shaped schema that may omit `type`; treat\n // properties-bearing schemas with type \"object\" or no type (branches) as\n // containers. Exclude typed scalars that happen to carry a `properties` key\n // (valid in some JSON Schema dialects as an annotation) and oneOf unions\n // (whose children are branches, not properties).\n const typeIsObjectLike = prop.type === \"object\" || prop.type === undefined;\n if (typeIsObjectLike && prop.properties && !prop.oneOf)\n return prop.properties;\n if (prop.type === \"array\" && prop.items?.type === \"object\") {\n return prop.items.properties;\n }\n return undefined;\n}\n\n/** Whether an allOf/anyOf member is a conditional (carries an `if`). */\nfunction isConditionalMember(member: JsonSchemaProperty): boolean {\n return !!member.if;\n}\n\ninterface ConditionalMember {\n member: JsonSchemaProperty;\n combinator: ConditionCombinator;\n index: number;\n}\n\n// The conditional members in one combinator array, with their positional index.\nfunction membersOfCombinator(\n property: JsonSchemaProperty,\n combinator: ConditionCombinator,\n): ConditionalMember[] {\n const arr = property[combinator];\n if (!Array.isArray(arr)) return [];\n return arr\n .map((member, index) => ({ member, combinator, index }))\n .filter(({ member }) => isConditionalMember(member));\n}\n\n/** The conditional members of a property across both allOf (AND) and anyOf (OR). */\nfunction conditionalMembers(property: JsonSchemaProperty): ConditionalMember[] {\n return [\n ...membersOfCombinator(property, \"allOf\"),\n ...membersOfCombinator(property, \"anyOf\"),\n ];\n}\n\n// A short label for a conditional derived from its `if` (e.g. \"if smoker\").\n// The field is in `if.properties` for value operators, or `if.required` for the\n// bare `exists` operator (which has no per-property constraint).\nfunction conditionLabel(member: JsonSchemaProperty): string {\n const field =\n Object.keys(member.if?.properties ?? {})[0] ?? member.if?.required?.[0];\n return field ? `if ${field}` : \"if ...\";\n}\n\n// The then/else slots of a conditional member (only present ones are shown).\nfunction conditionalSlots(member: JsonSchemaProperty): ChildSlot[] {\n const slots: ChildSlot[] = [];\n const add = (name: \"then\" | \"else\", sub: JsonSchemaProperty | undefined) => {\n if (sub) {\n slots.push({\n segment: slot(name),\n label: name,\n property: sub,\n kind: \"conditional\",\n removable: false,\n reorderable: false,\n });\n }\n };\n add(\"then\", member.then);\n add(\"else\", member.else);\n return slots;\n}\n\n/**\n * The reusable definitions map of a schema. Canonically 2020-12 `$defs`; also\n * reads Draft-7 `definitions` so both dialects surface as editable nodes. New\n * definitions are always authored into `$defs` (see mutate.addDefinition).\n */\nexport function definitionsOf(\n property: JsonSchemaProperty,\n): Record<string, JsonSchemaProperty> | undefined {\n return property.$defs ?? property.definitions;\n}\n\n// One definition slot per $defs (or Draft-7 definitions) entry.\nfunction definitionSlots(property: JsonSchemaProperty): ChildSlot[] {\n const defs = definitionsOf(property);\n if (!defs) return [];\n return Object.keys(defs).map((name) => ({\n segment: def(name),\n label: name,\n property: defs[name],\n kind: \"definition\" as const,\n removable: true,\n reorderable: false,\n }));\n}\n\n/**\n * The ordered child slots of a property (the single extension point for the\n * tree/inspector/mutations). Surfaces object/array property children, oneOf\n * branches, if/then/else conditionals (allOf/anyOf members), and $defs\n * definitions (root-only in practice).\n */\nexport function childSlots(property: JsonSchemaProperty): ChildSlot[] {\n // A conditional (allOf member with an `if`) exposes its then/else as slots.\n if (isConditionalMember(property)) return conditionalSlots(property);\n // oneOf: one branch slot per element.\n if (isOneOf(property)) {\n const discriminator = getDiscriminator(property);\n return (property.oneOf ?? []).map((b, index) => ({\n segment: branch(index),\n label: getBranchLabel(b, discriminator, index),\n property: b,\n kind: \"branch\" as const,\n removable: true,\n reorderable: true,\n }));\n }\n // object / array-of-object: property slots, then any conditional members.\n const container = childContainer(property);\n const propertySlots: ChildSlot[] = container\n ? Object.keys(container).map((key) => ({\n segment: prop(key),\n label: key,\n property: container[key],\n kind: \"property\" as const,\n removable: true,\n reorderable: true,\n }))\n : [];\n const conditionSlots: ChildSlot[] = conditionalMembers(property).map(\n ({ member, combinator, index }) => ({\n segment: condition(index, combinator),\n label: conditionLabel(member),\n property: member,\n kind: \"conditional\" as const,\n removable: true,\n reorderable: false,\n }),\n );\n return [...propertySlots, ...conditionSlots, ...definitionSlots(property)];\n}\n\n// ---- Navigation -----------------------------------------------------------\n\n// Resolve the immediate child of a property named by one segment.\nfunction stepInto(\n parent: JsonSchemaProperty,\n seg: PathSegment,\n): JsonSchemaProperty | undefined {\n if (seg.kind === \"prop\") return childContainer(parent)?.[seg.key];\n if (seg.kind === \"branch\") return parent.oneOf?.[seg.index];\n if (seg.kind === \"condition\") return parent[seg.combinator]?.[seg.index];\n if (seg.kind === \"def\") return definitionsOf(parent)?.[seg.name];\n if (seg.slot === \"items\") return parent.items;\n return parent[seg.slot];\n}\n\n/**\n * Wrap a JsonSchema root as an object-shaped JsonSchemaProperty so the path\n * navigation machinery can traverse it with the same stepInto logic as any\n * nested property. Pass the keys needed by the caller; unused fields default\n * to undefined.\n */\nexport function schemaAsRootProp(schema: JsonSchema): JsonSchemaProperty {\n return {\n type: \"object\",\n properties: schema.properties,\n required: schema.required,\n \"x-ui-order\": schema[\"x-ui-order\"],\n allOf: schema.allOf,\n anyOf: schema.anyOf,\n $defs: schema.$defs,\n definitions: schema.definitions,\n };\n}\n\n/** Resolve a path to its property definition, or undefined if not found. */\nexport function getProperty(\n schema: JsonSchema,\n path: PropertyPath,\n): JsonSchemaProperty | undefined {\n if (path.length === 0) return undefined;\n // Treat the schema root as an object-shaped property so root children --\n // named properties AND allOf conditionals -- are reached the same way as\n // nested ones (step by step through the segment machinery).\n const root = schemaAsRootProp(schema);\n let current: JsonSchemaProperty | undefined = root;\n for (const seg of path) {\n if (!current) return undefined;\n current = stepInto(current, seg);\n }\n return current;\n}\n\n/** Whether a property has (or can have) child slots (properties, branches, conditionals). */\nexport function isContainer(prop: JsonSchemaProperty): boolean {\n return childSlots(prop).length > 0 || childContainer(prop) !== undefined;\n}\n","/**\n * Read-shaping: turn a JsonSchema into a property tree for the designer UI.\n *\n * Pure, no React. Ordering follows the renderer's rule: an explicit x-ui-order\n * first, then remaining keys in declaration order.\n */\n\nimport type {\n JsonSchema,\n JsonSchemaProperty,\n RefResolver,\n} from \"@petrarca/sonnet-core/schema\";\nimport {\n childSlots,\n isContainer,\n schemaAsRootProp,\n type ChildSlot,\n type PropertyPath,\n type SlotKind,\n} from \"./paths\";\nimport { isOneOf } from \"@petrarca/sonnet-core/schema\";\n\nexport type PropertyKind =\n | \"scalar\"\n | \"enum\"\n | \"object\"\n | \"array\"\n | \"oneOf\"\n | \"conditional\"\n | \"reference\"\n | \"definition\";\n\nexport interface PropertyNode {\n path: PropertyPath;\n key: string;\n property: JsonSchemaProperty;\n kind: PropertyKind;\n /** How this node sits in its parent: a named property or a oneOf branch. */\n slotKind: SlotKind;\n required: boolean;\n /** Short type descriptor for the tree row, e.g. \"string\", \"object[]\". */\n typeLabel: string;\n /** Resolved widget override (x-ui-widget) if any. */\n widget?: string;\n /**\n * When this node is a `$ref`, the ref string it points at. Undefined for\n * non-ref nodes.\n */\n reference?: string;\n /**\n * True for nodes that live inside a resolved `$ref` (the ref's descendants).\n * These come from a shared definition and are not editable here -- the tree\n * and inspector use this to show read-only affordances. Computed once at\n * build time (no per-render schema walks). The ref node itself is NOT marked\n * (the usage can be renamed/deleted).\n */\n readOnly?: boolean;\n children: PropertyNode[];\n}\n\n/** Classify a property into a tree kind. */\nexport function propertyKind(prop: JsonSchemaProperty): PropertyKind {\n if (prop.if) return \"conditional\";\n if (isOneOf(prop)) return \"oneOf\";\n if (prop.type === \"object\" && prop.properties) return \"object\";\n if (prop.type === \"array\") return \"array\";\n if (Array.isArray(prop.enum) && prop.enum.length > 0) return \"enum\";\n return \"scalar\";\n}\n\n// Cardinality inside the brackets, standard multiplicity notation:\n// [] -- unconstrained\n// [3] -- exactly 3 (min == max)\n// [1..5] -- between 1 and 5\n// [1..] -- at least 1\n// [..5] -- at most 5\nfunction arrayCardinality(\n min: number | undefined,\n max: number | undefined,\n): string {\n if (min == null && max == null) return \"\";\n if (min != null && min === max) return `${min}`;\n return `${min ?? \"\"}..${max ?? \"\"}`;\n}\n\nfunction typeLabelOf(prop: JsonSchemaProperty): string {\n if (prop.if) return \"if/then/else\";\n if (isOneOf(prop)) return \"oneOf\";\n if (prop.type === \"array\") {\n const itemType = prop.items?.type ?? \"any\";\n // Compact array indicator (e.g. \"object[]\", \"object[1..5]\") so the type\n // descriptor stays short and does not crowd out the property name.\n return `${itemType}[${arrayCardinality(prop.minItems, prop.maxItems)}]`;\n }\n return prop.type ?? \"any\";\n}\n\n/** Order keys by explicit x-ui-order, then remaining declaration order. */\nexport function orderedKeys(\n properties: Record<string, JsonSchemaProperty>,\n order: string[] | undefined,\n): string[] {\n const keys = Object.keys(properties);\n if (!order || order.length === 0) return keys;\n const inOrder = order.filter((k) => k in properties);\n const rest = keys.filter((k) => !inOrder.includes(k));\n return [...inOrder, ...rest];\n}\n\n// The required-key list for a container property (object -> its required;\n// array-of-object -> items.required). Branches/oneOf have none.\nfunction requiredOf(prop: JsonSchemaProperty): string[] | undefined {\n if (prop.type === \"object\") return prop.required;\n if (prop.type === \"array\") return prop.items?.required;\n return undefined;\n}\n\n// The x-ui-order for a container property (object own, array via items).\nfunction orderOf(prop: JsonSchemaProperty): string[] | undefined {\n if (prop.type === \"array\") return prop.items?.[\"x-ui-order\"];\n return prop[\"x-ui-order\"];\n}\n\n// The tree kind of a node built from a slot. Branches and then/else slots are\n// anonymous object schemas (may omit `type`), shown as \"object\"; a conditional\n// member (the allOf if/then/else) is shown as \"conditional\".\nfunction nodeKind(slot: ChildSlot, prop: JsonSchemaProperty): PropertyKind {\n if (slot.kind === \"branch\") return \"object\";\n if (slot.segment.kind === \"def\") return \"definition\";\n if (slot.segment.kind === \"slot\") return \"object\"; // then / else / items\n return propertyKind(prop);\n}\n\n// The required-key list a container exposes to its property children. For a\n// then/else slot the required lives on the slot schema itself.\nfunction requiredForChildren(\n prop: JsonSchemaProperty,\n isSlot: boolean,\n): string[] | undefined {\n return isSlot ? prop.required : requiredOf(prop);\n}\n\n// Resolve a $ref node one level to its target for child display; undefined when\n// the node is not a ref or the ref cannot be resolved.\nfunction resolveRefTarget(\n prop: JsonSchemaProperty,\n resolve: RefResolver | undefined,\n): JsonSchemaProperty | undefined {\n if (!prop.$ref || !resolve) return undefined;\n const target = resolve(prop.$ref);\n if (!target) return undefined;\n // Merge node-level overrides (e.g. title) over the target, as the renderer does.\n const { $ref: _drop, ...overrides } = prop;\n return { ...target, ...overrides };\n}\n\n// How a node relates to a shared definition: a direct $ref, an array whose\n// items is a $ref, or neither. `container` is the schema whose child slots the\n// node exposes (the resolved target for refs, else the property itself).\ninterface RefShape {\n kind: PropertyKind;\n typeLabel: string;\n reference?: string;\n container: JsonSchemaProperty;\n // Whether this node's children come from a shared definition (read-only).\n childrenFromRef: boolean;\n}\n\n// Classify a property's relationship to a definition and derive its display.\nfunction refShapeOf(\n slot: ChildSlot,\n prop: JsonSchemaProperty,\n resolve: RefResolver | undefined,\n): RefShape {\n // A $ref node keeps its original property (with $ref) for identity/marker,\n // but its children come from the resolved target (read-only).\n const refTarget = resolveRefTarget(prop, resolve);\n if (refTarget) {\n return {\n kind: \"reference\",\n typeLabel: refLabel(prop.$ref!),\n reference: prop.$ref,\n container: refTarget,\n childrenFromRef: true,\n };\n }\n // An array-of-$ref surfaces the referenced element's fields as read-only\n // children while remaining an array node.\n if (prop.type === \"array\" && prop.items?.$ref) {\n const itemTarget = resolveRefTarget(prop.items, resolve);\n if (itemTarget) {\n return {\n kind: \"array\",\n typeLabel: arrayItemLabel(prop.items.$ref, prop),\n reference: prop.items.$ref,\n container: itemTarget,\n childrenFromRef: true,\n };\n }\n }\n return {\n kind: nodeKind(slot, prop),\n typeLabel: typeLabelOf(prop),\n container: prop,\n childrenFromRef: false,\n };\n}\n\nfunction buildNode(\n slot: ChildSlot,\n parentPath: PropertyPath,\n required: boolean,\n resolve: RefResolver | undefined,\n inRef: boolean,\n): PropertyNode {\n const path = [...parentPath, slot.segment];\n const prop = slot.property;\n const widget =\n typeof prop[\"x-ui-widget\"] === \"string\" ? prop[\"x-ui-widget\"] : undefined;\n const ref = refShapeOf(slot, prop, resolve);\n const node: PropertyNode = {\n path,\n key: slot.label,\n property: prop,\n kind: ref.kind,\n slotKind: slot.kind,\n required,\n typeLabel: ref.typeLabel,\n widget,\n reference: ref.reference,\n readOnly: inRef || undefined,\n children: [],\n };\n if (isContainer(ref.container)) {\n const isSlot = slot.segment.kind === \"slot\";\n const req = requiredForChildren(ref.container, isSlot);\n // Descendants of a $ref node (or of an already-read-only node) are read-only.\n const childrenInRef = inRef || ref.childrenFromRef;\n node.children = orderedSlots(ref.container).map((child) =>\n buildNode(\n child,\n path,\n child.kind === \"property\" ? !!req?.includes(child.label) : false,\n resolve,\n childrenInRef,\n ),\n );\n }\n return node;\n}\n\n// The definition name from a local $ref pointer (or the trailing URI segment).\nfunction refName(ref: string): string {\n const local = ref.match(/^#\\/(?:\\$defs|definitions)\\/(.+)$/);\n return local ? local[1] : ref.split(\"/\").pop() || ref;\n}\n\n// A compact label for a ref, e.g. \"#/$defs/Address\" -> \"-> Address\"; a registry\n// id or URI shows the trailing segment.\nfunction refLabel(ref: string): string {\n return `\\u2192 ${refName(ref)}`;\n}\n\n// A compact label for an array-of-$ref, e.g. \"Address[1..3]\".\nfunction arrayItemLabel(ref: string, prop: JsonSchemaProperty): string {\n return `${refName(ref)}[${arrayCardinality(prop.minItems, prop.maxItems)}]`;\n}\n\n// Child slots in display order. x-ui-order applies ONLY to property children\n// (keyed by property name); branch/conditional/definition slots keep their\n// positional order and follow the properties. Ordering is scoped to property\n// slots so a definition sharing a name with a property (both label \"vitals\")\n// cannot shadow the property (label is not a unique key across slot kinds).\nfunction orderedSlots(prop: JsonSchemaProperty): ChildSlot[] {\n const slots = childSlots(prop);\n const propertySlots = slots.filter((s) => s.kind === \"property\");\n const otherSlots = slots.filter((s) => s.kind !== \"property\");\n const order = orderOf(prop);\n if (propertySlots.length === 0 || !order || order.length === 0) return slots;\n const byLabel = new Map(propertySlots.map((s) => [s.label, s]));\n const inOrder = order\n .filter((k) => byLabel.has(k))\n .map((k) => byLabel.get(k)!);\n const rest = propertySlots.filter((s) => !order.includes(s.label));\n return [...inOrder, ...rest, ...otherSlots];\n}\n\n/**\n * Build the full property tree for a schema. Pass `resolve` to expand `$ref`\n * nodes (read-only) so referenced structure is legible; without it, ref nodes\n * show as leaves. `resolve` mirrors the renderer's RefResolver.\n */\nexport function buildPropertyTree(\n schema: JsonSchema,\n resolve?: RefResolver,\n): PropertyNode[] {\n // Default to an in-document $defs/definitions resolver so local refs expand\n // without the consumer wiring anything; an injected resolver (registry/URI)\n // is tried first and this is the fallback.\n const effective = withInDocumentFallback(schema, resolve);\n const rootProp = schemaAsRootProp(schema);\n return orderedSlots(rootProp).map((slot) =>\n buildNode(\n slot,\n [],\n !!schema.required?.includes(slot.label),\n effective,\n false,\n ),\n );\n}\n\n// Compose the injected resolver (if any) with an in-document $defs lookup.\nfunction withInDocumentFallback(\n schema: JsonSchema,\n resolve: RefResolver | undefined,\n): RefResolver | undefined {\n const defs = schema.$defs ?? schema.definitions;\n if (!defs) return resolve;\n const local: RefResolver = (ref) => {\n const m = ref.match(/^#\\/(?:\\$defs|definitions)\\/(.+)$/);\n return m ? defs[m[1]] : undefined;\n };\n return resolve ? (ref) => resolve(ref) ?? local(ref) : local;\n}\n\n/**\n * A layout scope: a container whose fields can be arranged into rows. Root is\n * the form itself (path []); nested scopes are object/array containers.\n */\nexport interface LayoutScope {\n /** Empty for root, otherwise the property path to the container. */\n path: PropertyPath;\n /** Human label, e.g. \"Form (root)\" or \"contact\" or \"addresses (items)\". */\n label: string;\n}\n\n/** Enumerate all layout scopes: the root form plus every object/array container. */\nexport function layoutScopes(schema: JsonSchema): LayoutScope[] {\n const scopes: LayoutScope[] = [{ path: [], label: \"Form (root)\" }];\n const walk = (nodes: PropertyNode[], labelPrefix: string[]) => {\n for (const node of nodes) {\n // Layout rows are keyed by property name within a property container.\n // Skip containers reached through a non-property segment (oneOf branch,\n // conditional member, then/else slot) -- their fields are not laid out\n // by the property-name-based row model.\n const allProps = node.path.every((s) => s.kind === \"prop\");\n if (allProps && (node.kind === \"object\" || node.kind === \"array\")) {\n const labels = [...labelPrefix, node.key];\n const suffix = node.kind === \"array\" ? \" (items)\" : \"\";\n scopes.push({\n path: node.path,\n label: labels.join(\" \\u203a \") + suffix,\n });\n walk(node.children, labels);\n }\n }\n };\n walk(buildPropertyTree(schema), []);\n return scopes;\n}\n","/**\n * Pure edit operations over { schema, uiSchema }.\n *\n * Every function returns a new pair; nothing mutates in place. Operations keep\n * the schema and uiSchema consistent -- renaming a property rewrites the property\n * key, the uiSchema entry, the required entry, and any x-ui-order reference at\n * the same level. Mirrors the graph-model/mutate.ts discipline.\n */\n\nimport type {\n JsonSchema,\n JsonSchemaProperty,\n UISchema,\n UILayoutConfig,\n UILayoutRowConfig,\n UILayoutGroupConfig,\n UISchemaOptions,\n} from \"@petrarca/sonnet-core/schema\";\nimport {\n getProperty,\n isReservedKey,\n prop as propSeg,\n branch as branchSeg,\n condition as condSeg,\n def as defSeg,\n type ConditionCombinator,\n type PathSegment,\n type PropertyPath,\n} from \"./paths\";\n\nexport type UiSchemaMap = Record<string, UISchema>;\n\n// The property key of a segment, or undefined for non-property segments.\n// Phase 1 mutations operate on property (prop-kind) children only.\nfunction segKey(seg: PathSegment | undefined): string | undefined {\n return seg && seg.kind === \"prop\" ? seg.key : undefined;\n}\n\n// The property keys along a path (prop segments only). Used to walk the\n// uiSchema x-ui-fields nesting, which is keyed by property name.\nfunction propKeys(path: PropertyPath): string[] {\n return path.flatMap((s) => (s.kind === \"prop\" ? [s.key] : []));\n}\n\nexport interface DesignerModel {\n schema: JsonSchema;\n uiSchema: UiSchemaMap;\n}\n\n// Deep clone via structuredClone (available in the runtime targets).\nfunction clone<T>(v: T): T {\n return structuredClone(v);\n}\n\n/** Kinds that can be created as a new property. */\nexport type NewPropertyKind = \"scalar\" | \"object\" | \"array\" | \"oneOf\";\n\n/** A default property for a newly created property of a given kind. */\nexport function newProperty(kind: NewPropertyKind): JsonSchemaProperty {\n switch (kind) {\n case \"object\":\n return { type: \"object\", properties: {} };\n case \"array\":\n return { type: \"array\", items: { type: \"object\", properties: {} } };\n case \"oneOf\":\n // Start with two empty branches, each tagged by a `kind` discriminator.\n return {\n type: \"object\",\n discriminator: { propertyName: \"kind\" },\n oneOf: [newBranch(\"option_1\"), newBranch(\"option_2\")],\n };\n default:\n return { type: \"string\" };\n }\n}\n\n/** A default oneOf branch: an object with a const-valued `kind` discriminator. */\nexport function newBranch(value: string): JsonSchemaProperty {\n return {\n title: value,\n properties: { kind: { const: value } },\n };\n}\n\n// Resolve the properties container + order-owner for a parent path. Root when\n// path is empty. Returns the mutable container inside a cloned schema.\nfunction resolveContainer(\n schema: JsonSchema,\n parentPath: PropertyPath,\n): {\n properties: Record<string, JsonSchemaProperty>;\n getOrder: () => string[] | undefined;\n setOrder: (order: string[] | undefined) => void;\n getRequired: () => string[] | undefined;\n setRequired: (req: string[] | undefined) => void;\n} | null {\n if (parentPath.length === 0) {\n return {\n properties: schema.properties,\n getOrder: () => schema[\"x-ui-order\"],\n setOrder: (o) => {\n if (o) schema[\"x-ui-order\"] = o;\n else delete schema[\"x-ui-order\"];\n },\n getRequired: () => schema.required,\n setRequired: (r) => {\n if (r && r.length) schema.required = r;\n else delete schema.required;\n },\n };\n }\n const owner = getProperty(schema, parentPath);\n if (!owner) return null;\n // For arrays, order/required/properties live on items; otherwise on the\n // owner (objects and oneOf branches). A branch may not yet have a\n // properties map -- create one so children can be added.\n if (owner.oneOf) return null; // cannot add a bare property to a oneOf itself\n const target = owner.type === \"array\" ? owner.items : owner;\n if (!target) return null; // malformed array (no items)\n if (!target.properties) target.properties = {};\n const properties = target.properties;\n return {\n properties,\n getOrder: () => target[\"x-ui-order\"],\n setOrder: (o) => {\n if (o) target[\"x-ui-order\"] = o;\n else delete target[\"x-ui-order\"];\n },\n getRequired: () => target.required,\n setRequired: (r) => {\n if (r && r.length) target.required = r;\n else delete target.required;\n },\n };\n}\n\n// Unique key like \"property\", \"property_2\" within a container.\nfunction uniqueKey(\n base: string,\n properties: Record<string, JsonSchemaProperty>,\n): string {\n if (!(base in properties)) return base;\n let i = 2;\n while (`${base}_${i}` in properties) i++;\n return `${base}_${i}`;\n}\n\n/** Add a property under a parent path (root when empty). Returns the new model. */\nexport function addProperty(\n model: DesignerModel,\n parentPath: PropertyPath,\n kind: NewPropertyKind,\n): { model: DesignerModel; path: PropertyPath } {\n const schema = clone(model.schema);\n const container = resolveContainer(schema, parentPath);\n if (!container) return { model, path: parentPath };\n const key = uniqueKey(\"property\", container.properties);\n container.properties[key] = newProperty(kind);\n const order = container.getOrder();\n if (order) container.setOrder([...order, key]);\n return {\n model: { schema, uiSchema: model.uiSchema },\n path: [...parentPath, propSeg(key)],\n };\n}\n\n// Derive a branch value that is unique among existing branch titles/consts so\n// that the discriminator remains unambiguous after any add/remove sequence.\nfunction uniqueBranchValue(oneOf: JsonSchemaProperty[]): string {\n const existing = new Set(oneOf.map((b) => b.title).filter(Boolean));\n let i = 1;\n while (existing.has(`option_${i}`)) i++;\n return `option_${i}`;\n}\n\n/** Add a branch to the oneOf property at `path`. Returns the new model + branch path. */\nexport function addBranch(\n model: DesignerModel,\n path: PropertyPath,\n): { model: DesignerModel; path: PropertyPath } {\n const schema = clone(model.schema);\n const owner = getProperty(schema, path);\n if (!owner || !owner.oneOf) return { model, path };\n const index = owner.oneOf.length;\n owner.oneOf.push(newBranch(uniqueBranchValue(owner.oneOf)));\n return {\n model: { schema, uiSchema: model.uiSchema },\n path: [...path, branchSeg(index)],\n };\n}\n\n/** Remove the branch at `path` (a branch segment). Returns the new model. */\nexport function removeBranch(\n model: DesignerModel,\n path: PropertyPath,\n): DesignerModel {\n const last = path[path.length - 1];\n if (!last || last.kind !== \"branch\") return model;\n const schema = clone(model.schema);\n const owner = getProperty(schema, path.slice(0, -1));\n if (!owner?.oneOf) return model;\n owner.oneOf.splice(last.index, 1);\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** Move the branch at `path` up (-1) or down (+1) among its siblings. */\nexport function moveBranch(\n model: DesignerModel,\n path: PropertyPath,\n direction: -1 | 1,\n): DesignerModel {\n const last = path[path.length - 1];\n if (!last || last.kind !== \"branch\") return model;\n const schema = clone(model.schema);\n const owner = getProperty(schema, path.slice(0, -1));\n if (!owner?.oneOf) return model;\n const from = last.index;\n const to = from + direction;\n if (to < 0 || to >= owner.oneOf.length) return model;\n const [moved] = owner.oneOf.splice(from, 1);\n owner.oneOf.splice(to, 0, moved);\n return { schema, uiSchema: model.uiSchema };\n}\n\n// ---- Conditionals (if/then/else authored as allOf members) ----------------\n\n/**\n * A seed conditional member: an empty `if` (no field yet) plus an empty `then`.\n * The condition is filled in by setCondition; `then` fields are added like any\n * object's properties.\n */\nexport function newCondition(): JsonSchemaProperty {\n return { if: { properties: {} }, then: { properties: {} } };\n}\n\n/**\n * Add a conditional (if/then/else) to the object at `objectPath` (root when\n * empty), appended to the given combinator array (`allOf` = AND, default;\n * `anyOf` = OR). Returns the new model + the condition path.\n */\nexport function addConditional(\n model: DesignerModel,\n objectPath: PropertyPath,\n combinator: ConditionCombinator = \"allOf\",\n): { model: DesignerModel; path: PropertyPath } {\n const schema = clone(model.schema);\n const owner = conditionalOwner(schema, objectPath);\n if (!owner) return { model, path: objectPath };\n if (!Array.isArray(owner[combinator])) owner[combinator] = [];\n const arr = owner[combinator]!;\n const index = arr.length;\n arr.push(newCondition());\n return {\n model: { schema, uiSchema: model.uiSchema },\n path: [...objectPath, condSeg(index, combinator)],\n };\n}\n\n// The schema object that owns an `allOf` for a given object path: the root\n// schema (path []) or an object property. Arrays/oneOf/scalars cannot host a\n// conditional directly.\nfunction conditionalOwner(\n schema: JsonSchema,\n objectPath: PropertyPath,\n): JsonSchema | JsonSchemaProperty | null {\n if (objectPath.length === 0) return schema;\n const owner = getProperty(schema, objectPath);\n if (!owner) return null;\n const objectLike = owner.type === \"object\" || owner.type === undefined;\n if (!objectLike || owner.oneOf) return null;\n return owner;\n}\n\n/** Remove the conditional at `path` (a condition segment). Returns the new model. */\nexport function removeConditional(\n model: DesignerModel,\n path: PropertyPath,\n): DesignerModel {\n const last = path[path.length - 1];\n if (!last || last.kind !== \"condition\") return model;\n const schema = clone(model.schema);\n const owner = conditionalOwner(schema, path.slice(0, -1));\n const arr = owner?.[last.combinator];\n if (!arr) return model;\n arr.splice(last.index, 1);\n if (arr.length === 0) delete owner![last.combinator];\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** Write the `if` of the conditional at `path` from a condition triple. */\nexport function setCondition(\n model: DesignerModel,\n path: PropertyPath,\n ifSchema: JsonSchemaProperty,\n): DesignerModel {\n const last = path[path.length - 1];\n if (!last || last.kind !== \"condition\") return model;\n const schema = clone(model.schema);\n const member = getProperty(schema, path);\n if (!member) return model;\n member.if = ifSchema;\n if (!member.then) member.then = { properties: {} };\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** Add an empty `else` branch to the conditional at `path`. */\nexport function addElse(\n model: DesignerModel,\n path: PropertyPath,\n): DesignerModel {\n const last = path[path.length - 1];\n if (!last || last.kind !== \"condition\") return model;\n const schema = clone(model.schema);\n const member = getProperty(schema, path);\n if (!member || member.else) return model;\n member.else = { properties: {} };\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** Remove the `else` branch from the conditional at `path`. */\nexport function removeElse(\n model: DesignerModel,\n path: PropertyPath,\n): DesignerModel {\n const last = path[path.length - 1];\n if (!last || last.kind !== \"condition\") return model;\n const schema = clone(model.schema);\n const member = getProperty(schema, path);\n if (!member || !member.else) return model;\n delete member.else;\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** The other combinator. */\nfunction otherCombinator(c: ConditionCombinator): ConditionCombinator {\n return c === \"allOf\" ? \"anyOf\" : \"allOf\";\n}\n\n/**\n * Switch the combinator (AND/OR) for the conditionals of the object at\n * `objectPath`. Migrates every conditional member from the current combinator\n * array to `next`. Non-conditional members (structural allOf/anyOf entries)\n * stay put. No-op when already using `next` or when there are no conditionals.\n */\nexport function setConditionalBehavior(\n model: DesignerModel,\n objectPath: PropertyPath,\n next: ConditionCombinator,\n): DesignerModel {\n const schema = clone(model.schema);\n const owner = conditionalOwner(schema, objectPath);\n if (!owner) return model;\n const from = otherCombinator(next);\n const source = owner[from];\n if (!Array.isArray(source)) return model;\n\n const conditionals = source.filter((m) => !!m.if);\n if (conditionals.length === 0) return model;\n const rest = source.filter((m) => !m.if);\n\n // Move conditionals into the target array; leave structural members behind.\n if (rest.length > 0) owner[from] = rest;\n else delete owner[from];\n owner[next] = [...(owner[next] ?? []), ...conditionals];\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** Delete the property at path. Returns the new model. */\nexport function deleteProperty(\n model: DesignerModel,\n path: PropertyPath,\n): DesignerModel {\n if (path.length === 0) return model;\n const schema = clone(model.schema);\n const parentPath = path.slice(0, -1);\n const key = segKey(path[path.length - 1]);\n if (key === undefined) return model;\n const container = resolveContainer(schema, parentPath);\n if (!container || !(key in container.properties)) return model;\n delete container.properties[key];\n const order = container.getOrder();\n if (order) container.setOrder(order.filter((k) => k !== key));\n const required = container.getRequired();\n if (required) container.setRequired(required.filter((k) => k !== key));\n\n // Drop the uiSchema entry only for top-level properties (uiSchema is keyed by\n // top-level property name; nested UI lives under x-ui-fields, handled elsewhere).\n let uiSchema = model.uiSchema;\n if (parentPath.length === 0 && key in uiSchema) {\n uiSchema = { ...uiSchema };\n delete uiSchema[key];\n }\n return { schema, uiSchema };\n}\n\n// Rewrite one key to another within a properties map, preserving position.\nfunction renameKeyInPlace(\n properties: Record<string, JsonSchemaProperty>,\n prevKey: string,\n nextKey: string,\n): void {\n const rebuilt: Record<string, JsonSchemaProperty> = {};\n for (const [k, v] of Object.entries(properties)) {\n rebuilt[k === prevKey ? nextKey : k] = v;\n }\n for (const k of Object.keys(properties)) delete properties[k];\n Object.assign(properties, rebuilt);\n}\n\n// Move a top-level uiSchema entry to a new key (returns a new map if changed).\nfunction renameUiEntry(\n uiSchema: UiSchemaMap,\n parentPath: PropertyPath,\n prevKey: string,\n nextKey: string,\n): UiSchemaMap {\n if (parentPath.length !== 0 || !(prevKey in uiSchema)) return uiSchema;\n const next = { ...uiSchema };\n next[nextKey] = next[prevKey];\n delete next[prevKey];\n return next;\n}\n\n// Update order and required arrays when a key is renamed in a container.\nfunction updateContainerRefs(\n container: ReturnType<typeof resolveContainer> & object,\n prevKey: string,\n nextKey: string,\n): void {\n const rename = (k: string) => (k === prevKey ? nextKey : k);\n const order = container.getOrder();\n if (order) container.setOrder(order.map(rename));\n const required = container.getRequired();\n if (required) container.setRequired(required.map(rename));\n}\n\n/** Rename the property at path. Rewrites key, order, required, and uiSchema. */\nexport function renameProperty(\n model: DesignerModel,\n path: PropertyPath,\n nextKey: string,\n): { model: DesignerModel; path: PropertyPath } {\n if (path.length === 0) return { model, path };\n const parentPath = path.slice(0, -1);\n const prevKey = segKey(path[path.length - 1]);\n if (prevKey === undefined) return { model, path };\n if (nextKey === prevKey || !nextKey || isReservedKey(nextKey))\n return { model, path };\n\n const schema = clone(model.schema);\n const container = resolveContainer(schema, parentPath);\n if (!container || !(prevKey in container.properties)) return { model, path };\n if (nextKey in container.properties) return { model, path }; // collision: no-op\n\n renameKeyInPlace(container.properties, prevKey, nextKey);\n updateContainerRefs(container, prevKey, nextKey);\n const uiSchema = renameUiEntry(model.uiSchema, parentPath, prevKey, nextKey);\n return {\n model: { schema, uiSchema },\n path: [...parentPath, propSeg(nextKey)],\n };\n}\n\n/** Move the property at path up (-1) or down (+1) among its siblings. */\nexport function moveProperty(\n model: DesignerModel,\n path: PropertyPath,\n direction: -1 | 1,\n): DesignerModel {\n if (path.length === 0) return model;\n const schema = clone(model.schema);\n const parentPath = path.slice(0, -1);\n const key = segKey(path[path.length - 1]);\n if (key === undefined) return model;\n const container = resolveContainer(schema, parentPath);\n if (!container) return model;\n\n const keys = Object.keys(container.properties);\n const order = container.getOrder() ?? keys;\n // Normalize order to include every key.\n const full = [...order.filter((k) => keys.includes(k))];\n for (const k of keys) if (!full.includes(k)) full.push(k);\n\n const idx = full.indexOf(key);\n const swap = idx + direction;\n if (idx < 0 || swap < 0 || swap >= full.length) return model;\n [full[idx], full[swap]] = [full[swap], full[idx]];\n container.setOrder(full);\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** Toggle whether the property at path is required among its siblings. */\nexport function setRequired(\n model: DesignerModel,\n path: PropertyPath,\n required: boolean,\n): DesignerModel {\n if (path.length === 0) return model;\n const schema = clone(model.schema);\n const parentPath = path.slice(0, -1);\n const key = segKey(path[path.length - 1]);\n if (key === undefined) return model;\n const container = resolveContainer(schema, parentPath);\n if (!container) return model;\n const current = new Set(container.getRequired() ?? []);\n if (required) current.add(key);\n else current.delete(key);\n container.setRequired([...current]);\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** Replace the property definition at path (merges the given partial). */\nexport function updateProperty(\n model: DesignerModel,\n path: PropertyPath,\n patch: Partial<JsonSchemaProperty>,\n): DesignerModel {\n if (path.length === 0) return model;\n const schema = clone(model.schema);\n const prop = getProperty(schema, path);\n if (!prop) return model;\n // Apply the patch: set defined values, delete keys whose patch value is\n // undefined so they don't persist as ghost own-keys on the schema object.\n for (const [k, v] of Object.entries(patch)) {\n if (v === undefined) delete (prop as Record<string, unknown>)[k];\n else (prop as Record<string, unknown>)[k] = v;\n }\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** The kind a property can be changed to: a JSON Schema type, or a \"oneOf\" union. */\nexport type PropertyTypeChoice =\n | NonNullable<JsonSchemaProperty[\"type\"]>\n | \"oneOf\";\n\n// The current kind choice of a property (for no-op detection).\nfunction currentTypeChoice(prop: JsonSchemaProperty): PropertyTypeChoice {\n return prop.oneOf ? \"oneOf\" : (prop.type ?? \"string\");\n}\n\n/**\n * Change the kind of the property at path, reshaping structural keys: object\n * adds an empty `properties`; array adds `items`; oneOf adds branches + a\n * discriminator; leaving a kind strips its keys. Type-specific validation keys\n * that no longer apply are dropped.\n */\nexport function changePropertyType(\n model: DesignerModel,\n path: PropertyPath,\n next: PropertyTypeChoice,\n): DesignerModel {\n if (path.length === 0 || !next) return model;\n const schema = clone(model.schema);\n const prop = getProperty(schema, path);\n // A $ref node has no concrete type; always allow retyping it (which clears\n // the $ref below). Otherwise skip when the choice is unchanged.\n if (!prop || (!prop.$ref && currentTypeChoice(prop) === next)) return model;\n\n // Strip all structural + type-specific + logic keys from the previous kind.\n delete prop.properties;\n delete prop.items;\n delete prop.enum;\n delete prop.oneOf;\n delete prop.discriminator;\n delete prop.const;\n // A concrete type replaces any $ref: the property is no longer a reference.\n delete prop.$ref;\n // Conditionals (allOf if/then/else) belong to an object; drop them when the\n // owning property is no longer an object.\n if (next !== \"object\") {\n delete prop.allOf;\n delete prop.anyOf;\n }\n delete prop.minLength;\n delete prop.maxLength;\n delete prop.pattern;\n delete prop.format;\n delete prop.minimum;\n delete prop.maximum;\n delete prop.minItems;\n delete prop.maxItems;\n\n if (next === \"oneOf\") {\n const seed = newProperty(\"oneOf\");\n prop.type = seed.type;\n prop.discriminator = seed.discriminator;\n prop.oneOf = seed.oneOf;\n } else {\n prop.type = next;\n if (next === \"object\") prop.properties = {};\n if (next === \"array\") prop.items = { type: \"string\" };\n }\n return { schema, uiSchema: model.uiSchema };\n}\n\n// The local $ref pointer for a definition name (2020-12 canonical form).\nfunction defPointer(name: string): string {\n return `#/$defs/${name}`;\n}\n\n/**\n * Point the property at path to a definition by name, writing a local `$ref`\n * (`#/$defs/<name>`) and stripping type-specific keys. Turns a plain property\n * into a reference usage. No-op for the root or an unknown target.\n */\nexport function setReference(\n model: DesignerModel,\n path: PropertyPath,\n name: string,\n): DesignerModel {\n if (path.length === 0 || !name) return model;\n const schema = clone(model.schema);\n const prop = getProperty(schema, path);\n if (!prop) return model;\n const defs = schema.$defs ?? schema.definitions;\n if (!defs || !(name in defs)) return model;\n // For an array, the reference applies to its items (\"array of <def>\"); the\n // array keeps its type and cardinality. Otherwise the property itself becomes\n // the reference.\n if (prop.type === \"array\") {\n prop.items = { $ref: defPointer(name) };\n return { schema, uiSchema: model.uiSchema };\n }\n makeReference(prop, name);\n return { schema, uiSchema: model.uiSchema };\n}\n\n// Turn a property into a $ref node: strip structural and type-specific keys,\n// keeping only annotation overrides (title/description/default) that are valid\n// 2020-12 $ref siblings at the referencing site.\nfunction makeReference(prop: JsonSchemaProperty, name: string): void {\n delete prop.properties;\n delete prop.items;\n delete prop.enum;\n delete prop.oneOf;\n delete prop.discriminator;\n delete prop.const;\n delete prop.allOf;\n delete prop.anyOf;\n delete prop.type;\n // Strip type-specific validation so it does not silently constrain the\n // referencing site independently of the definition's own constraints.\n delete prop.minLength;\n delete prop.maxLength;\n delete prop.pattern;\n delete prop.format;\n delete prop.minimum;\n delete prop.maximum;\n delete prop.minItems;\n delete prop.maxItems;\n prop.$ref = defPointer(name);\n}\n\n// Visit every object node in a schema tree, calling visitor on each.\n// The visitor receives the object and the key under which it was reached\n// (undefined for the root); returning true from the visitor skips recursing\n// into the object's children (used to skip already-matched nodes).\nfunction walkSchemaNodes(\n node: unknown,\n visitor: (obj: Record<string, unknown>, key: string | undefined) => void,\n parentKey?: string,\n): void {\n if (Array.isArray(node)) {\n for (const item of node) walkSchemaNodes(item, visitor, parentKey);\n return;\n }\n if (!node || typeof node !== \"object\") return;\n const obj = node as Record<string, unknown>;\n visitor(obj, parentKey);\n for (const key of Object.keys(obj)) {\n walkSchemaNodes(obj[key], visitor, key);\n }\n}\n\n/** Recursively rewrite every local `$ref` targeting `from` to point at `to`. */\nfunction rewriteRefs(node: unknown, from: string, to: string): void {\n walkSchemaNodes(node, (obj, key) => {\n // Only rewrite when reached via a non-$ref key, so we are visiting the\n // containing object (not a string value that happens to equal `from`).\n if (key !== \"$ref\" && obj.$ref === from) obj.$ref = to;\n });\n}\n\n// Count local $ref usages of a definition across the whole schema.\nfunction countRefUsages(schema: JsonSchema, name: string): number {\n let count = 0;\n const pointers = new Set([`#/$defs/${name}`, `#/definitions/${name}`]);\n walkSchemaNodes(schema, (obj) => {\n if (typeof obj.$ref === \"string\" && pointers.has(obj.$ref)) count++;\n });\n return count;\n}\n\n/**\n * Add a new empty object definition under `$defs`. Returns the new model and the\n * path to the created definition for selection.\n */\nexport function addDefinition(\n model: DesignerModel,\n name?: string,\n): { model: DesignerModel; path: PropertyPath } {\n const schema = clone(model.schema);\n if (!schema.$defs) schema.$defs = {};\n const key = uniqueKey(name ?? \"Definition\", schema.$defs);\n schema.$defs[key] = { type: \"object\", properties: {} };\n return {\n model: { schema, uiSchema: model.uiSchema },\n path: [defSeg(key)],\n };\n}\n\n/**\n * Rename a `$defs` entry, preserving order, and rewrite every local `$ref` that\n * targets it (both `#/$defs/` and `#/definitions/` forms) to the new pointer.\n * No-op on collision, reserved, or empty names.\n */\nexport function renameDefinition(\n model: DesignerModel,\n oldName: string,\n newName: string,\n): { model: DesignerModel; path: PropertyPath } {\n const path: PropertyPath = [defSeg(oldName)];\n if (!newName || newName === oldName || isReservedKey(newName))\n return { model, path };\n const schema = clone(model.schema);\n // Support both 2020-12 $defs and Draft-7 definitions; author to the map\n // that already contains the entry.\n const defs = schema.$defs ?? schema.definitions;\n if (!defs || !(oldName in defs) || newName in defs) return { model, path };\n\n renameKeyInPlace(defs, oldName, newName);\n rewriteRefs(schema, `#/$defs/${oldName}`, `#/$defs/${newName}`);\n rewriteRefs(schema, `#/definitions/${oldName}`, `#/$defs/${newName}`);\n return {\n model: { schema, uiSchema: model.uiSchema },\n path: [defSeg(newName)],\n };\n}\n\n/**\n * Remove a `$defs` entry. Blocked (no-op) while any local `$ref` still targets\n * it; the UI surfaces the usage count. Drops the `$defs` map when it empties.\n */\nexport function removeDefinition(\n model: DesignerModel,\n name: string,\n): DesignerModel {\n const schema = clone(model.schema);\n // Support both 2020-12 $defs and Draft-7 definitions.\n const inDefs = schema.$defs && name in schema.$defs;\n const inDefs7 = schema.definitions && name in schema.definitions;\n if (!inDefs && !inDefs7) return model;\n if (countRefUsages(schema, name) > 0) return model; // in use: keep it\n if (inDefs) {\n delete schema.$defs![name];\n if (Object.keys(schema.$defs!).length === 0) delete schema.$defs;\n } else {\n delete schema.definitions![name];\n if (Object.keys(schema.definitions!).length === 0)\n delete schema.definitions;\n }\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** Whether a definition is referenced anywhere (for UI delete-guard messaging). */\nexport function definitionUsageCount(schema: JsonSchema, name: string): number {\n return countRefUsages(schema, name);\n}\n\n/** One enum choice: a value and an optional display label. */\nexport interface EnumChoice {\n value: string;\n label?: string;\n}\n\n/**\n * Set the enum choices for the property at path. Values write to `property.enum`;\n * labels write to the property's `x-ui-options.enumNames` in the uiSchema (only\n * for top-level properties, where the uiSchema map is keyed). An empty list clears\n * both. Deduplicates and drops empty values.\n */\n// Normalize choices: trim, drop empties, dedupe by value (first wins).\nfunction normalizeChoices(choices: EnumChoice[]): EnumChoice[] {\n const seen = new Set<string>();\n const clean: EnumChoice[] = [];\n for (const c of choices) {\n const value = c.value.trim();\n if (!value || seen.has(value)) continue;\n seen.add(value);\n clean.push({ value, label: c.label?.trim() || undefined });\n }\n return clean;\n}\n\n// Update a UISchema entry's x-ui-options.enumNames from labelled choices,\n// returning the new entry (or undefined if empty).\nfunction withEnumNames(\n entry: UISchema | undefined,\n choices: EnumChoice[],\n): UISchema | undefined {\n const enumNames: Record<string, string> = {};\n for (const c of choices) if (c.label) enumNames[c.value] = c.label;\n\n const next: UISchema = { ...(entry ?? {}) };\n const options = {\n ...((next[\"x-ui-options\"] as Record<string, unknown>) ?? {}),\n };\n if (Object.keys(enumNames).length) options.enumNames = enumNames;\n else delete options.enumNames;\n if (Object.keys(options).length) next[\"x-ui-options\"] = options;\n else delete next[\"x-ui-options\"];\n\n return Object.keys(next).length ? next : undefined;\n}\n\nexport function setEnum(\n model: DesignerModel,\n path: PropertyPath,\n choices: EnumChoice[],\n): DesignerModel {\n if (path.length === 0) return model;\n const schema = clone(model.schema);\n const prop = getProperty(schema, path);\n if (!prop) return model;\n\n const clean = normalizeChoices(choices);\n if (clean.length === 0) delete prop.enum;\n else prop.enum = clean.map((c) => c.value);\n\n // enumNames lives in the property's uiSchema entry (at any nesting depth).\n const nextEntry = withEnumNames(\n getUiEntryAtPath(model.uiSchema, path),\n clean,\n );\n const uiSchema = setEntryIn(model.uiSchema, propKeys(path), nextEntry);\n\n return { schema, uiSchema };\n}\n\n/** Read the current enum choices for a property + its uiSchema entry. */\nexport function readEnumChoices(\n prop: JsonSchemaProperty,\n uiEntry: UISchema | undefined,\n): EnumChoice[] {\n if (!Array.isArray(prop.enum)) return [];\n const enumNames =\n (uiEntry?.[\"x-ui-options\"] as { enumNames?: Record<string, string> })\n ?.enumNames ?? {};\n return prop.enum.map((v) => {\n const value = String(v);\n return { value, label: enumNames[value] };\n });\n}\n\n/** Table presentation hints for a property (embedded in the schema). */\nexport interface TableHints {\n cell?: string;\n cellOptions?: Record<string, unknown>;\n column?: NonNullable<JsonSchemaProperty[\"x-ui-column\"]>;\n}\n\n/**\n * Set (or clear) a property's table hints: x-ui-cell, x-ui-cell-options, and\n * x-ui-column. These live embedded on the property (EntityTable reads them\n * there). Empty values clear the corresponding key.\n */\nexport function setTableHints(\n model: DesignerModel,\n path: PropertyPath,\n hints: TableHints,\n): DesignerModel {\n if (path.length === 0) return model;\n const schema = clone(model.schema);\n const prop = getProperty(schema, path);\n if (!prop) return model;\n\n if (hints.cell) prop[\"x-ui-cell\"] = hints.cell;\n else delete prop[\"x-ui-cell\"];\n\n if (hints.cellOptions && Object.keys(hints.cellOptions).length > 0) {\n prop[\"x-ui-cell-options\"] = hints.cellOptions;\n } else {\n delete prop[\"x-ui-cell-options\"];\n }\n\n if (hints.column && Object.keys(hints.column).length > 0) {\n prop[\"x-ui-column\"] = hints.column;\n } else {\n delete prop[\"x-ui-column\"];\n }\n\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** Read a property's current table hints. */\nexport function readTableHints(prop: JsonSchemaProperty): TableHints {\n return {\n cell: typeof prop[\"x-ui-cell\"] === \"string\" ? prop[\"x-ui-cell\"] : undefined,\n cellOptions: prop[\"x-ui-cell-options\"] as\n | Record<string, unknown>\n | undefined,\n column: prop[\"x-ui-column\"],\n };\n}\n\n/** Set (or clear) the top-level uiSchema entry for a property name. */\n// -- Path-aware uiSchema navigation --------------------------------------\n//\n// The uiSchema map is keyed by top-level property name. A nested property's\n// UISchema entry lives under its ancestor's `x-ui-fields` sub-map: the first\n// path segment indexes the top-level map, each subsequent segment indexes\n// through `x-ui-fields`. This mirrors how ObjectWidget/ArrayWidget read it.\n\ntype UiFieldsMap = Record<string, UISchema>;\n\n/** Read the UISchema entry for a property path, or undefined. */\nexport function getUiEntryAtPath(\n uiSchema: UiSchemaMap,\n path: PropertyPath,\n): UISchema | undefined {\n const keys = propKeys(path);\n if (keys.length === 0) return undefined;\n let entry: UISchema | undefined = uiSchema[keys[0]];\n for (let i = 1; i < keys.length && entry; i++) {\n const fields = entry[\"x-ui-fields\"] as UiFieldsMap | undefined;\n entry = fields?.[keys[i]];\n }\n return entry;\n}\n\n// Recursively set `entry` at `keys` within a fields map, pruning empties on the\n// way back up (empty entry -> removed; empty x-ui-fields -> removed).\nfunction setEntryIn(\n map: UiFieldsMap,\n keys: string[],\n entry: UISchema | undefined,\n): UiFieldsMap {\n const [head, ...rest] = keys;\n const next: UiFieldsMap = { ...map };\n\n if (rest.length === 0) {\n if (entry && Object.keys(entry).length > 0) next[head] = entry;\n else delete next[head];\n return next;\n }\n\n const current: UISchema = { ...(next[head] ?? {}) };\n const childFields = (current[\"x-ui-fields\"] as UiFieldsMap | undefined) ?? {};\n const updatedFields = setEntryIn(childFields, rest, entry);\n\n if (Object.keys(updatedFields).length > 0) {\n current[\"x-ui-fields\"] = updatedFields;\n } else {\n delete current[\"x-ui-fields\"];\n }\n\n if (Object.keys(current).length > 0) next[head] = current;\n else delete next[head];\n return next;\n}\n\n/** Set (or clear) the UISchema entry at a property path (any nesting depth). */\nexport function setUiEntry(\n model: DesignerModel,\n path: PropertyPath,\n entry: UISchema | undefined,\n): DesignerModel {\n if (path.length === 0) return model;\n const uiSchema = setEntryIn(model.uiSchema, propKeys(path), entry);\n return { schema: model.schema, uiSchema };\n}\n\n/**\n * Set (or clear) the x-ui-layout of an object/array property at path. Object\n * layout lives on the property; array layout lives on `items`.\n */\nexport function setPropertyLayout(\n model: DesignerModel,\n path: PropertyPath,\n layout: UILayoutConfig | undefined,\n): DesignerModel {\n if (path.length === 0) return model;\n const schema = clone(model.schema);\n const prop = getProperty(schema, path);\n if (!prop) return model;\n const target = prop.type === \"array\" ? prop.items : prop;\n if (!target) return model;\n if (layout) target[\"x-ui-layout\"] = layout;\n else delete target[\"x-ui-layout\"];\n return { schema, uiSchema: model.uiSchema };\n}\n\n// The uiSchema map is keyed by property name (UISchema values) but also carries\n// special top-level keys (x-ui-layout, x-ui-globalOptions) whose values are not\n// UISchema. Read/write them through this looser view.\ntype RootUiSchema = UiSchemaMap & {\n \"x-ui-layout\"?: UILayoutConfig;\n \"x-ui-globalOptions\"?: UISchemaOptions;\n};\n\n/** Set (or clear) the root form layout (uiSchema[\"x-ui-layout\"]). */\nexport function setRootLayout(\n model: DesignerModel,\n layout: UILayoutConfig | undefined,\n): DesignerModel {\n const uiSchema = { ...model.uiSchema } as RootUiSchema;\n if (layout) uiSchema[\"x-ui-layout\"] = layout;\n else delete uiSchema[\"x-ui-layout\"];\n return { schema: model.schema, uiSchema };\n}\n\n/**\n * Set (or clear) the root layout rows (uiSchema[\"x-ui-layout\"].rows),\n * preserving other x-ui-layout keys. Clearing rows to empty removes the key;\n * if x-ui-layout then has no keys, it is removed entirely.\n */\nexport function setRootLayoutRows(\n model: DesignerModel,\n rows: UILayoutConfig[\"rows\"],\n): DesignerModel {\n const uiSchema = { ...model.uiSchema } as RootUiSchema;\n const layout: UILayoutConfig = { ...(uiSchema[\"x-ui-layout\"] ?? {}) };\n if (rows && rows.length > 0) layout.rows = rows;\n else delete layout.rows;\n if (Object.keys(layout).length > 0) uiSchema[\"x-ui-layout\"] = layout;\n else delete uiSchema[\"x-ui-layout\"];\n return { schema: model.schema, uiSchema };\n}\n\n/**\n * Set the layout rows for a scope: the root form (path []) or an object/array\n * container (its property path). Root rows live in uiSchema[\"x-ui-layout\"];\n * a container's rows live on the property's x-ui-layout (array -> items).\n * Preserves other x-ui-layout keys.\n */\nexport function setScopedLayoutRows(\n model: DesignerModel,\n scopePath: PropertyPath,\n rows: UILayoutConfig[\"rows\"],\n): DesignerModel {\n if (scopePath.length === 0) return setRootLayoutRows(model, rows);\n\n const schema = clone(model.schema);\n const prop = getProperty(schema, scopePath);\n if (!prop) return model;\n const target = prop.type === \"array\" ? prop.items : prop;\n if (!target) return model;\n\n const layout: UILayoutConfig = { ...(target[\"x-ui-layout\"] ?? {}) };\n if (rows && rows.length > 0) layout.rows = rows;\n else delete layout.rows;\n if (Object.keys(layout).length > 0) target[\"x-ui-layout\"] = layout;\n else delete target[\"x-ui-layout\"];\n return { schema, uiSchema: model.uiSchema };\n}\n\n/** Read the current x-ui-layout for a scope (root or a container property). */\nexport function getScopedLayout(\n schema: JsonSchema,\n uiSchema: UiSchemaMap,\n scopePath: PropertyPath,\n): UILayoutConfig | undefined {\n if (scopePath.length === 0) {\n return (uiSchema as RootUiSchema)[\"x-ui-layout\"];\n }\n const prop = getProperty(schema, scopePath);\n const target = prop?.type === \"array\" ? prop.items : prop;\n return target?.[\"x-ui-layout\"];\n}\n\n/**\n * Merge scalar layout options (direction/gap/labels/compact) into a scope's\n * x-ui-layout, preserving rows and other keys. Undefined values clear the key.\n */\nexport function setScopedLayoutOptions(\n model: DesignerModel,\n scopePath: PropertyPath,\n options: Pick<UILayoutConfig, \"direction\" | \"gap\" | \"labels\" | \"compact\">,\n): DesignerModel {\n const current =\n getScopedLayout(model.schema, model.uiSchema, scopePath) ?? {};\n const merged: UILayoutConfig = { ...current };\n for (const key of [\"direction\", \"gap\", \"labels\", \"compact\"] as const) {\n const v = options[key];\n if (v === undefined || (typeof v === \"number\" && Number.isNaN(v)))\n delete merged[key];\n else (merged as Record<string, unknown>)[key] = v;\n }\n const layout = Object.keys(merged).length > 0 ? merged : undefined;\n if (scopePath.length === 0) return setRootLayout(model, layout);\n return setPropertyLayout(model, scopePath, layout);\n}\n\n/**\n * Set the group definitions for a scope, preserving other x-ui-layout keys.\n * Passing an empty list (or undefined) clears groups, returning the scope to the\n * flat row layout. Root groups live in uiSchema[\"x-ui-layout\"]; a container's\n * live on the property's x-ui-layout (array -> items).\n *\n * Groups and flat rows are mutually exclusive (the renderer gives groups\n * precedence), so setting groups drops `rows` -- otherwise the orphaned list\n * would be invisible in both the form and the designer.\n */\nexport function setScopedLayoutGroups(\n model: DesignerModel,\n scopePath: PropertyPath,\n groups: UILayoutConfig[\"groups\"],\n): DesignerModel {\n const current =\n getScopedLayout(model.schema, model.uiSchema, scopePath) ?? {};\n const merged: UILayoutConfig = { ...current };\n if (groups && groups.length > 0) {\n merged.groups = groups;\n delete merged.rows;\n } else {\n delete merged.groups;\n }\n const layout = Object.keys(merged).length > 0 ? merged : undefined;\n if (scopePath.length === 0) return setRootLayout(model, layout);\n return setPropertyLayout(model, scopePath, layout);\n}\n\n/** The groups currently defined for a scope. */\nfunction groupsOf(\n model: DesignerModel,\n scopePath: PropertyPath,\n): UILayoutGroupConfig[] {\n return getScopedLayout(model.schema, model.uiSchema, scopePath)?.groups ?? [];\n}\n\n/** Append an empty group. The label defaults to the next ordinal (\"Group 3\"). */\nexport function addLayoutGroup(\n model: DesignerModel,\n scopePath: PropertyPath,\n label?: string,\n): DesignerModel {\n const groups = groupsOf(model, scopePath);\n const next = { label: label ?? `Group ${groups.length + 1}`, rows: [] };\n return setScopedLayoutGroups(model, scopePath, [...groups, next]);\n}\n\n/** Rename one group. No-op for an unknown index or a blank label. */\nexport function renameLayoutGroup(\n model: DesignerModel,\n scopePath: PropertyPath,\n groupIndex: number,\n label: string,\n): DesignerModel {\n const groups = groupsOf(model, scopePath);\n if (!groups[groupIndex] || !label.trim()) return model;\n return setScopedLayoutGroups(\n model,\n scopePath,\n groups.map((group, i) => (i === groupIndex ? { ...group, label } : group)),\n );\n}\n\n/**\n * Place a property into one group's row, removing it from wherever it currently\n * sits across *all* groups. Passing a null target returns it to the pool.\n *\n * Needed because each group owns its own rows: without a cross-group operation a\n * field could only be moved between groups by visiting its old group first.\n */\nexport function placeFieldInGroup(\n model: DesignerModel,\n scopePath: PropertyPath,\n key: string,\n target: { groupIndex: number; rowIndex: number } | null,\n): DesignerModel {\n const groups = groupsOf(model, scopePath);\n if (!key || groups.length === 0) return model;\n const stripped = groups.map((group) => ({\n ...group,\n rows: group.rows.map((row) => ({\n ...row,\n fields: row.fields.filter((f) => f !== key),\n })),\n }));\n if (!target) return setScopedLayoutGroups(model, scopePath, stripped);\n\n const { groupIndex, rowIndex } = target;\n const row = stripped[groupIndex]?.rows[rowIndex];\n if (!row) return setScopedLayoutGroups(model, scopePath, stripped);\n stripped[groupIndex].rows = stripped[groupIndex].rows.map((r, i) =>\n i === rowIndex ? { ...r, fields: [...r.fields, key] } : r,\n );\n return setScopedLayoutGroups(model, scopePath, stripped);\n}\n\n/** Move one group left (-1) or right (+1). No-op at the ends. */\nexport function moveLayoutGroup(\n model: DesignerModel,\n scopePath: PropertyPath,\n groupIndex: number,\n direction: -1 | 1,\n): DesignerModel {\n const groups = groupsOf(model, scopePath);\n const target = groupIndex + direction;\n if (!groups[groupIndex] || target < 0 || target >= groups.length)\n return model;\n const next = [...groups];\n [next[groupIndex], next[target]] = [next[target], next[groupIndex]];\n return setScopedLayoutGroups(model, scopePath, next);\n}\n\n/**\n * Set (or clear) a group's show/hide rule. Passing undefined makes the group\n * unconditional.\n */\nexport function setLayoutGroupRule(\n model: DesignerModel,\n scopePath: PropertyPath,\n groupIndex: number,\n rule: UILayoutGroupConfig[\"rule\"],\n): DesignerModel {\n const groups = groupsOf(model, scopePath);\n if (!groups[groupIndex]) return model;\n const next = groups.map((group, i) => {\n if (i !== groupIndex) return group;\n const { rule: _drop, ...rest } = group;\n return rule ? { ...rest, rule } : rest;\n });\n return setScopedLayoutGroups(model, scopePath, next);\n}\n\n/**\n * Set the group presentation for a scope (\"groups\", \"stepper\", or a custom\n * template name). Passing undefined restores the default group presentation.\n */\nexport function setScopedLayoutVariant(\n model: DesignerModel,\n scopePath: PropertyPath,\n variant: UILayoutConfig[\"variant\"],\n): DesignerModel {\n const current =\n getScopedLayout(model.schema, model.uiSchema, scopePath) ?? {};\n const merged: UILayoutConfig = { ...current };\n if (variant && variant !== \"groups\") merged.variant = variant;\n else delete merged.variant;\n const layout = Object.keys(merged).length > 0 ? merged : undefined;\n if (scopePath.length === 0) return setRootLayout(model, layout);\n return setPropertyLayout(model, scopePath, layout);\n}\n\n/**\n * Remove one group. Its rows are not discarded: removing the last remaining group\n * flattens them back into the scope's flat row layout, so a single click can\n * never destroy every field placement.\n */\nexport function removeLayoutGroup(\n model: DesignerModel,\n scopePath: PropertyPath,\n groupIndex: number,\n): DesignerModel {\n const groups = groupsOf(model, scopePath);\n if (!groups[groupIndex]) return model;\n const remaining = groups.filter((_, i) => i !== groupIndex);\n if (remaining.length > 0) {\n return setScopedLayoutGroups(model, scopePath, remaining);\n }\n const cleared = setScopedLayoutGroups(model, scopePath, []);\n return setScopedLayoutRows(cleared, scopePath, groups[groupIndex].rows);\n}\n\n/** Replace the rows of one group in a scope. No-op for an unknown group index. */\nexport function setScopedGroupRows(\n model: DesignerModel,\n scopePath: PropertyPath,\n groupIndex: number,\n rows: UILayoutRowConfig[],\n): DesignerModel {\n const groups = getScopedLayout(\n model.schema,\n model.uiSchema,\n scopePath,\n )?.groups;\n if (!groups?.[groupIndex]) return model;\n const next = groups.map((group, i) =>\n i === groupIndex ? { ...group, rows } : group,\n );\n return setScopedLayoutGroups(model, scopePath, next);\n}\n\n/**\n * Switch a scope between flat rows and groups, carrying the existing layout over\n * so no field placement is lost: rows become the first group's rows, and leaving\n * group mode flattens every group's rows back into one list.\n */\nexport function setScopedLayoutMode(\n model: DesignerModel,\n scopePath: PropertyPath,\n mode: \"rows\" | \"groups\",\n): DesignerModel {\n const layout = getScopedLayout(model.schema, model.uiSchema, scopePath) ?? {};\n const groups = layout.groups ?? [];\n const rows = layout.rows ?? [];\n if (mode === \"groups\") {\n if (groups.length > 0) return model; // already tabbed\n // setScopedLayoutGroups drops the flat rows, so seed the group with them first.\n return setScopedLayoutGroups(model, scopePath, [\n { label: \"Group 1\", rows },\n ]);\n }\n if (groups.length === 0) return model; // already flat\n // Keep any pre-existing flat rows ahead of the flattened group rows so nothing\n // is overwritten if both somehow coexist (hand-authored uiSchema).\n const flattened = [...rows, ...groups.flatMap((group) => group.rows)];\n const cleared = setScopedLayoutGroups(model, scopePath, []);\n return setScopedLayoutRows(cleared, scopePath, flattened);\n}\n\n/** Set (or clear) the root global options (uiSchema[\"x-ui-globalOptions\"]). */\nexport function setGlobalOptions(\n model: DesignerModel,\n options: UISchemaOptions | undefined,\n): DesignerModel {\n const uiSchema = { ...model.uiSchema } as RootUiSchema;\n if (options) uiSchema[\"x-ui-globalOptions\"] = options;\n else delete uiSchema[\"x-ui-globalOptions\"];\n return { schema: model.schema, uiSchema };\n}\n","/**\n * Type -> compatible form widgets for the inspector's widget dropdown.\n *\n * Mirrors the renderer's resolution vocabulary (sonnet-forms widgetResolver):\n * the dropdown offers widgets that make sense for a property's type, plus an\n * \"Auto\" choice (value null) that clears x-ui-widget and lets the renderer\n * resolve from structure/type. Keep aligned with DEFAULT_WIDGETS.\n */\n\nimport type { JsonSchemaProperty } from \"@petrarca/sonnet-core/schema\";\n\nexport interface WidgetChoice {\n /** x-ui-widget value (lowercase alias), or null for Auto (no override). */\n value: string | null;\n label: string;\n}\n\nconst AUTO: WidgetChoice = { value: null, label: \"Auto (resolve from schema)\" };\n\nconst STRING_WIDGETS: WidgetChoice[] = [\n { value: \"text\", label: \"Text input\" },\n { value: \"textarea\", label: \"Textarea\" },\n { value: \"select\", label: \"Select\" },\n { value: \"date\", label: \"Date\" },\n { value: \"date-time\", label: \"Date & time\" },\n { value: \"time\", label: \"Time\" },\n { value: \"tags\", label: \"Tags\" },\n { value: \"entity-select\", label: \"Entity select\" },\n { value: \"json-editor\", label: \"JSON editor\" },\n];\n\nconst NUMBER_WIDGETS: WidgetChoice[] = [\n { value: \"number\", label: \"Number\" },\n { value: \"select\", label: \"Select\" },\n { value: \"quantity\", label: \"Quantity\" },\n];\n\nconst BOOLEAN_WIDGETS: WidgetChoice[] = [\n { value: \"checkbox\", label: \"Checkbox\" },\n];\n\nconst OBJECT_WIDGETS: WidgetChoice[] = [\n { value: \"object\", label: \"Object (sub-form)\" },\n { value: \"json-editor\", label: \"JSON editor\" },\n];\n\nconst ARRAY_WIDGETS: WidgetChoice[] = [\n { value: \"array\", label: \"Array (repeatable)\" },\n { value: \"select\", label: \"Multi-select\" },\n { value: \"tags\", label: \"Tags\" },\n];\n\nconst NULL_WIDGETS: WidgetChoice[] = [{ value: \"display\", label: \"Display\" }];\n\nconst ONEOF_WIDGETS: WidgetChoice[] = [\n { value: \"one-of\", label: \"One of (variant)\" },\n];\n\n/** Widgets offered for a property, Auto first. */\nexport function compatibleWidgets(prop: JsonSchemaProperty): WidgetChoice[] {\n if (Array.isArray(prop.oneOf) && prop.oneOf.length > 0) {\n return [AUTO, ...ONEOF_WIDGETS];\n }\n switch (prop.type) {\n case \"string\":\n return [AUTO, ...STRING_WIDGETS];\n case \"number\":\n case \"integer\":\n return [AUTO, ...NUMBER_WIDGETS];\n case \"boolean\":\n return [AUTO, ...BOOLEAN_WIDGETS];\n case \"object\":\n return [AUTO, ...OBJECT_WIDGETS];\n case \"array\":\n return [AUTO, ...ARRAY_WIDGETS];\n case \"null\":\n return [AUTO, ...NULL_WIDGETS];\n default:\n return [AUTO];\n }\n}\n","/**\n * Output shaping: merge a separate uiSchema map's form hints into the JSON\n * schema as embedded x-ui-* keys, for consumers that want a single\n * self-contained schema.\n *\n * The designer edits the two artifacts separately (clean data/presentation\n * split); embedding is applied only at the emit boundary when outputMode is\n * \"embedded\". Only top-level form hints are embedded in v1 (x-ui-widget,\n * x-ui-options, x-ui-title, x-ui-placeholder, x-ui-description), matching what\n * uiSchema carries for top-level properties.\n */\n\nimport type {\n JsonSchema,\n JsonSchemaProperty,\n UISchema,\n} from \"@petrarca/sonnet-core/schema\";\n\nconst EMBEDDABLE_KEYS = [\n \"x-ui-widget\",\n \"x-ui-options\",\n \"x-ui-title\",\n \"x-ui-placeholder\",\n \"x-ui-description\",\n] as const;\n\n/**\n * Return a new schema with each top-level property's uiSchema form hints copied\n * onto the corresponding property as x-ui-* keys. The input schema/uiSchema are\n * not mutated. uiSchema hints win over any pre-existing embedded key.\n */\nexport function embedUiSchema(\n schema: JsonSchema,\n uiSchema: Record<string, UISchema>,\n): JsonSchema {\n const next = structuredClone(schema);\n for (const [fieldName, entry] of Object.entries(uiSchema)) {\n const prop: JsonSchemaProperty | undefined = next.properties[fieldName];\n if (!prop || !entry) continue;\n for (const key of EMBEDDABLE_KEYS) {\n if (entry[key] !== undefined) {\n (prop as Record<string, unknown>)[key] = entry[key];\n }\n }\n }\n return next;\n}\n","/**\n * useDesignerState -- owns the designer's { schema, uiSchema, selection } and\n * exposes bound mutation operations.\n *\n * Controlled: pass `schema` + `uiSchema` + `onChange`; the hook holds no schema\n * state and every op calls `onChange`. Uncontrolled: pass `initialSchema`\n * (+ optional `initialUiSchema`); the hook manages the schema internally.\n * Selection (the active property path) is always internal UI state.\n */\n\nimport { useCallback, useMemo, useRef, useState } from \"react\";\nimport type {\n JsonSchema,\n JsonSchemaProperty,\n UISchema,\n UILayoutConfig,\n UILayoutRowConfig,\n UILayoutGroupConfig,\n UISchemaOptions,\n RefResolver,\n} from \"@petrarca/sonnet-core/schema\";\nimport {\n addProperty,\n addBranch,\n removeBranch,\n moveBranch,\n addConditional,\n removeConditional,\n setCondition,\n setConditionalBehavior,\n addElse,\n removeElse,\n deleteProperty,\n moveProperty,\n renameProperty,\n setRequired,\n updateProperty,\n changePropertyType,\n setReference,\n addDefinition,\n renameDefinition,\n removeDefinition,\n type NewPropertyKind,\n type PropertyTypeChoice,\n setEnum,\n setUiEntry,\n setTableHints,\n type TableHints,\n setPropertyLayout,\n setRootLayout,\n setRootLayoutRows,\n setScopedLayoutRows,\n setScopedLayoutOptions,\n setScopedLayoutGroups,\n setScopedGroupRows,\n setScopedLayoutMode,\n addLayoutGroup,\n renameLayoutGroup,\n removeLayoutGroup,\n moveLayoutGroup,\n setLayoutGroupRule,\n setScopedLayoutVariant,\n placeFieldInGroup,\n setGlobalOptions,\n type DesignerModel,\n type UiSchemaMap,\n type EnumChoice,\n} from \"../model/mutate\";\nimport {\n samePath,\n sameSegment,\n slot as slotSeg,\n condition as condSeg,\n def as defSeg,\n getProperty,\n type ConditionCombinator,\n type PathSegment,\n type PropertyPath,\n} from \"../model/paths\";\nimport {\n resolveCapabilities,\n type SchemaDesignerCapabilities,\n type ResolvedCapabilities,\n} from \"../capabilities\";\nimport { isPropertyEditable, canAddChildTo } from \"../model/scoping\";\n\n// Whether path `p` is `prefix` or a descendant of it (segment-wise).\nfunction pathStartsWith(p: PropertyPath, prefix: PropertyPath): boolean {\n if (p.length < prefix.length) return false;\n return prefix.every((seg, i) => sameSegment(seg, p[i]));\n}\n\n// Whether path `p` runs through the same parent as `removed` (every segment\n// before the removed one matches). `removed` ends in an indexed segment.\nfunction sharesParentPrefix(p: PropertyPath, removed: PropertyPath): boolean {\n if (p.length < removed.length) return false;\n const parentLen = removed.length - 1;\n for (let i = 0; i < parentLen; i++) {\n if (!sameSegment(p[i], removed[i])) return false;\n }\n return true;\n}\n\n// When an indexed sibling (branch or condition) at `removed` is spliced out,\n// adjust a selection that pointed at it (clear) or at a higher-indexed sibling\n// (shift its index down by one) -- including selections nested inside such a\n// sibling. Selections elsewhere are returned unchanged.\n// Whether two indexed segments (branch/condition) index the same array -- i.e.\n// they are siblings whose positions shift together. For conditions this\n// requires the same combinator; branches share one array.\nfunction sameIndexedArray(a: PathSegment, b: PathSegment): boolean {\n if (a.kind !== b.kind) return false;\n if (a.kind === \"branch\" && b.kind === \"branch\") return true;\n if (a.kind === \"condition\" && b.kind === \"condition\")\n return a.combinator === b.combinator;\n return false;\n}\n\n// The selected segment sitting in the same indexed array as the removed one,\n// or null when the selection is unaffected by the removal.\nfunction affectedSibling(\n prev: PropertyPath,\n removed: PropertyPath,\n kind: \"branch\" | \"condition\",\n): { at: number; seg: Extract<PathSegment, { index: number }> } | null {\n const last = removed[removed.length - 1];\n if (!last || last.kind !== kind) return null;\n if (!sharesParentPrefix(prev, removed)) return null;\n const at = removed.length - 1;\n const seg = prev[at];\n if (!seg || !sameIndexedArray(seg, last) || !(\"index\" in seg)) return null;\n return { at, seg };\n}\n\nfunction adjustIndexedSelection(\n prev: PropertyPath | null,\n removed: PropertyPath,\n kind: \"branch\" | \"condition\",\n): PropertyPath | null {\n if (!prev) return null;\n const hit = affectedSibling(prev, removed, kind);\n if (!hit) return prev;\n const removedIndex = (removed[removed.length - 1] as { index: number }).index;\n if (hit.seg.index === removedIndex) return null; // selected the removed node\n if (hit.seg.index < removedIndex) return prev; // sits before -- unchanged\n // Sits after the removed one: shift its index down (spread keeps combinator).\n const shifted = { ...hit.seg, index: hit.seg.index - 1 };\n return [...prev.slice(0, hit.at), shifted, ...prev.slice(hit.at + 1)];\n}\n\nfunction adjustBranchSelection(\n prev: PropertyPath | null,\n removed: PropertyPath,\n): PropertyPath | null {\n return adjustIndexedSelection(prev, removed, \"branch\");\n}\n\n// The number of conditional members (with an `if`) in one combinator array.\nfunction countConditionals(arr: { if?: unknown }[] | undefined): number {\n return Array.isArray(arr) ? arr.filter((m) => !!m.if).length : 0;\n}\n\n// The selected condition segment at `objectPath` when it belongs to combinator\n// `from`, else null. Encapsulates the \"does this selection apply\" guards.\nfunction selectedConditionInCombinator(\n prev: PropertyPath | null,\n objectPath: PropertyPath,\n from: ConditionCombinator,\n): { at: number; index: number } | null {\n if (!prev) return null;\n const at = objectPath.length;\n const seg = prev[at];\n if (!seg || seg.kind !== \"condition\" || seg.combinator !== from) return null;\n if (!samePath(prev.slice(0, at), objectPath)) return null;\n return { at, index: seg.index };\n}\n\n/**\n * After a Match (AND/OR) switch on the object at `objectPath`, keep the\n * selection on the same conditional by remapping its segment to the target\n * combinator + new index. Uses the PRE-migration model to compute positions.\n * Returns `prev` unchanged when the selection is not a conditional here.\n */\nfunction remapConditionSelection(\n before: DesignerModel,\n prev: PropertyPath | null,\n objectPath: PropertyPath,\n next: ConditionCombinator,\n): PropertyPath | null {\n const from: ConditionCombinator = next === \"allOf\" ? \"anyOf\" : \"allOf\";\n const hit = selectedConditionInCombinator(prev, objectPath, from);\n if (!hit || !prev) return prev;\n\n const owner =\n objectPath.length === 0\n ? { allOf: before.schema.allOf, anyOf: before.schema.anyOf }\n : getProperty(before.schema, objectPath);\n const sourceArr = owner?.[from] as { if?: unknown }[] | undefined;\n if (!Array.isArray(sourceArr)) return prev;\n\n // Conditionals move to the end of the target's existing conditionals, keeping\n // relative order. New index = (target's prior conditionals) + (this member's\n // position among the source conditionals).\n const posAmongSource = countConditionals(sourceArr.slice(0, hit.index));\n const targetOffset = countConditionals(\n owner?.[next] as { if?: unknown }[] | undefined,\n );\n return [\n ...prev.slice(0, hit.at),\n condSeg(targetOffset + posAmongSource, next),\n ...prev.slice(hit.at + 1),\n ];\n}\n\nexport interface UseDesignerStateArgs {\n schema?: JsonSchema;\n uiSchema?: UiSchemaMap;\n initialSchema?: JsonSchema;\n initialUiSchema?: UiSchemaMap;\n onChange?: (schema: JsonSchema, uiSchema: UiSchemaMap) => void;\n readOnly?: boolean;\n capabilities?: SchemaDesignerCapabilities;\n /** Optional resolver for non-local `$ref`s (registry id / URI); local $defs\n * resolve automatically. Used to expand ref nodes (read-only) in the tree. */\n refResolver?: RefResolver;\n}\n\nexport interface DesignerState {\n schema: JsonSchema;\n uiSchema: UiSchemaMap;\n selection: PropertyPath | null;\n readOnly: boolean;\n /** Resolver for $ref expansion in the tree (undefined = local $defs only). */\n refResolver?: RefResolver;\n /** Resolved capability profile (readOnly + editablePaths applied). */\n capabilities: ResolvedCapabilities;\n /** Whether the property at path may be renamed / deleted / retyped / reordered. */\n canEditProperty: (path: PropertyPath) => boolean;\n /** Whether a child property may be added to the container at path (root = []). */\n canAddChild: (path: PropertyPath) => boolean;\n select: (path: PropertyPath | null) => void;\n addProperty: (parentPath: PropertyPath, kind: NewPropertyKind) => void;\n /** Add a branch to the oneOf property at path. */\n addBranch: (path: PropertyPath) => void;\n /** Remove the branch at path (a branch segment). */\n removeBranch: (path: PropertyPath) => void;\n /** Move the branch at path up (-1) or down (+1). */\n moveBranch: (path: PropertyPath, direction: -1 | 1) => void;\n /** Add an if/then/else conditional to the object at path (root when empty). */\n addConditional: (\n objectPath: PropertyPath,\n combinator?: ConditionCombinator,\n ) => void;\n /** Switch the AND/OR combinator for the conditionals of the object at path. */\n setConditionalBehavior: (\n objectPath: PropertyPath,\n combinator: ConditionCombinator,\n ) => void;\n /** Remove the conditional at path (a condition segment). */\n removeConditional: (path: PropertyPath) => void;\n /** Write the `if` schema of the conditional at path. */\n setCondition: (path: PropertyPath, ifSchema: JsonSchemaProperty) => void;\n /** Add an empty `else` branch to the conditional at path. */\n addElse: (path: PropertyPath) => void;\n /** Remove the `else` branch from the conditional at path. */\n removeElse: (path: PropertyPath) => void;\n deleteProperty: (path: PropertyPath) => void;\n renameProperty: (path: PropertyPath, nextKey: string) => void;\n moveProperty: (path: PropertyPath, direction: -1 | 1) => void;\n setRequired: (path: PropertyPath, required: boolean) => void;\n updateProperty: (\n path: PropertyPath,\n patch: Partial<JsonSchemaProperty>,\n ) => void;\n changePropertyType: (path: PropertyPath, next: PropertyTypeChoice) => void;\n /** Point the property at path at a definition (writes a local `$ref`). */\n setReference: (path: PropertyPath, name: string) => void;\n /** Add a new empty object definition to `$defs`. Selects the new node. */\n addDefinition: (name?: string) => void;\n /** Rename a `$defs` entry; rewrites every local `$ref` that targets it. */\n renameDefinition: (oldName: string, newName: string) => void;\n /** Remove an unused `$defs` entry (blocked while any `$ref` targets it). */\n removeDefinition: (name: string) => void;\n /** Replace the whole JSON Schema (from the editable JSON Schema source tab). */\n replaceSchema: (schema: JsonSchema) => void;\n /** Replace the whole UI Schema map (from the editable UI Schema source tab). */\n replaceUiSchema: (uiSchema: UiSchemaMap) => void;\n setEnum: (path: PropertyPath, choices: EnumChoice[]) => void;\n setUiEntry: (path: PropertyPath, entry: UISchema | undefined) => void;\n setTableHints: (path: PropertyPath, hints: TableHints) => void;\n setPropertyLayout: (\n path: PropertyPath,\n layout: UILayoutConfig | undefined,\n ) => void;\n setRootLayout: (layout: UILayoutConfig | undefined) => void;\n setRootLayoutRows: (rows: UILayoutConfig[\"rows\"]) => void;\n setScopedLayoutRows: (\n scopePath: PropertyPath,\n rows: UILayoutConfig[\"rows\"],\n ) => void;\n setScopedLayoutOptions: (\n scopePath: PropertyPath,\n options: Pick<UILayoutConfig, \"direction\" | \"gap\" | \"labels\" | \"compact\">,\n ) => void;\n /** Replace a scope's group definitions (empty clears groups -> flat rows). */\n setScopedLayoutGroups: (\n scopePath: PropertyPath,\n groups: UILayoutConfig[\"groups\"],\n ) => void;\n /** Replace the rows of one group within a scope. */\n setScopedGroupRows: (\n scopePath: PropertyPath,\n groupIndex: number,\n rows: UILayoutRowConfig[],\n ) => void;\n /** Switch a scope between flat rows and groups, carrying placements over. */\n setScopedLayoutMode: (\n scopePath: PropertyPath,\n mode: \"rows\" | \"groups\",\n ) => void;\n /** Append an empty group to a scope. */\n addLayoutGroup: (scopePath: PropertyPath, label?: string) => void;\n /** Rename one group of a scope. */\n renameLayoutGroup: (\n scopePath: PropertyPath,\n groupIndex: number,\n label: string,\n ) => void;\n /** Remove one group; removing the last flattens its rows back to flat rows. */\n removeLayoutGroup: (scopePath: PropertyPath, groupIndex: number) => void;\n /** Move one group left (-1) or right (+1). */\n moveLayoutGroup: (\n scopePath: PropertyPath,\n groupIndex: number,\n direction: -1 | 1,\n ) => void;\n /** Set (or clear) a group's show/hide rule. */\n setLayoutGroupRule: (\n scopePath: PropertyPath,\n groupIndex: number,\n rule: UILayoutGroupConfig[\"rule\"],\n ) => void;\n /** Choose the group presentation (\"tabs\", \"stepper\", \"sections\", ...). */\n setScopedLayoutVariant: (\n scopePath: PropertyPath,\n variant: UILayoutConfig[\"variant\"],\n ) => void;\n /** Place a property into a group's row, or back in the pool (null target). */\n placeFieldInGroup: (\n scopePath: PropertyPath,\n key: string,\n target: { groupIndex: number; rowIndex: number } | null,\n ) => void;\n setGlobalOptions: (options: UISchemaOptions | undefined) => void;\n}\n\nconst EMPTY_SCHEMA: JsonSchema = {\n title: \"\",\n type: \"object\",\n properties: {},\n};\n\nexport function useDesignerState(args: UseDesignerStateArgs): DesignerState {\n const { onChange, readOnly = false } = args;\n const controlled = args.schema !== undefined;\n\n const [internal, setInternal] = useState<DesignerModel>(() => ({\n schema: args.initialSchema ?? EMPTY_SCHEMA,\n uiSchema: args.initialUiSchema ?? {},\n }));\n const [selection, setSelection] = useState<PropertyPath | null>(null);\n\n // The live model: controlled props win; otherwise internal state.\n const model: DesignerModel = controlled\n ? { schema: args.schema!, uiSchema: args.uiSchema ?? {} }\n : internal;\n\n // Keep a ref so the mutation callbacks are stable but read the latest model.\n const modelRef = useRef(model);\n modelRef.current = model;\n\n const commit = useCallback(\n (next: DesignerModel) => {\n if (!controlled) setInternal(next);\n onChange?.(next.schema, next.uiSchema);\n },\n [controlled, onChange],\n );\n\n const select = useCallback((path: PropertyPath | null) => {\n setSelection((prev) => (samePath(prev, path) ? prev : path));\n }, []);\n\n const capabilities = useMemo(\n () => resolveCapabilities(args.capabilities, readOnly),\n [args.capabilities, readOnly],\n );\n\n // Structural gating: readOnly locks everything; scoped restricts edits to the\n // children of editablePaths. Read the latest model via the ref so callbacks\n // stay stable.\n const canEditProperty = useCallback(\n (path: PropertyPath) => {\n if (capabilities.locked) return false;\n return isPropertyEditable(\n modelRef.current.schema,\n path,\n capabilities.editablePaths,\n );\n },\n [capabilities.locked, capabilities.editablePaths],\n );\n const canAddChild = useCallback(\n (path: PropertyPath) => {\n if (capabilities.locked) return false;\n return canAddChildTo(\n modelRef.current.schema,\n path,\n capabilities.editablePaths,\n );\n },\n [capabilities.locked, capabilities.editablePaths],\n );\n\n const ops = useMemo(\n () => ({\n addProperty(parentPath: PropertyPath, kind: NewPropertyKind) {\n if (!canAddChild(parentPath)) return;\n const res = addProperty(modelRef.current, parentPath, kind);\n commit(res.model);\n setSelection(res.path);\n },\n addBranch(path: PropertyPath) {\n if (!canEditProperty(path)) return;\n const res = addBranch(modelRef.current, path);\n commit(res.model);\n setSelection(res.path);\n },\n removeBranch(path: PropertyPath) {\n if (!canEditProperty(path)) return;\n commit(removeBranch(modelRef.current, path));\n setSelection((prev) => adjustBranchSelection(prev, path));\n },\n moveBranch(path: PropertyPath, direction: -1 | 1) {\n if (!canEditProperty(path)) return;\n commit(moveBranch(modelRef.current, path, direction));\n },\n addConditional(\n objectPath: PropertyPath,\n combinator: ConditionCombinator = \"allOf\",\n ) {\n // Adding a conditional augments the object -- gate like adding a child.\n if (!canAddChild(objectPath)) return;\n const res = addConditional(modelRef.current, objectPath, combinator);\n commit(res.model);\n setSelection(res.path);\n },\n setConditionalBehavior(\n objectPath: PropertyPath,\n combinator: ConditionCombinator,\n ) {\n if (!canAddChild(objectPath)) return;\n const before = modelRef.current;\n commit(setConditionalBehavior(before, objectPath, combinator));\n // Keep the selection pointing at the same conditional after migration:\n // remap its combinator + index to the target array.\n setSelection((prev) =>\n remapConditionSelection(before, prev, objectPath, combinator),\n );\n },\n removeConditional(path: PropertyPath) {\n // Editing a conditional is scoped to its owning object.\n if (!canAddChild(path.slice(0, -1))) return;\n commit(removeConditional(modelRef.current, path));\n // Splicing the allOf member shifts higher-indexed siblings down.\n setSelection((prev) => adjustIndexedSelection(prev, path, \"condition\"));\n },\n setCondition(path: PropertyPath, ifSchema: JsonSchemaProperty) {\n if (!canAddChild(path.slice(0, -1))) return;\n commit(setCondition(modelRef.current, path, ifSchema));\n },\n addElse(path: PropertyPath) {\n if (!canAddChild(path.slice(0, -1))) return;\n commit(addElse(modelRef.current, path));\n },\n removeElse(path: PropertyPath) {\n if (!canAddChild(path.slice(0, -1))) return;\n commit(removeElse(modelRef.current, path));\n // Clear a selection that was on the removed else slot (or nested under it).\n const elsePath = [...path, slotSeg(\"else\")];\n setSelection((prev) =>\n prev && pathStartsWith(prev, elsePath) ? null : prev,\n );\n },\n deleteProperty(path: PropertyPath) {\n if (!canEditProperty(path)) return;\n commit(deleteProperty(modelRef.current, path));\n setSelection((prev) => (samePath(prev, path) ? null : prev));\n },\n renameProperty(path: PropertyPath, nextKey: string) {\n if (!canEditProperty(path)) return;\n const res = renameProperty(modelRef.current, path, nextKey);\n commit(res.model);\n setSelection(res.path);\n },\n moveProperty(path: PropertyPath, direction: -1 | 1) {\n if (!canEditProperty(path)) return;\n commit(moveProperty(modelRef.current, path, direction));\n },\n setRequired(path: PropertyPath, required: boolean) {\n if (!canEditProperty(path)) return;\n commit(setRequired(modelRef.current, path, required));\n },\n updateProperty(path: PropertyPath, patch: Partial<JsonSchemaProperty>) {\n if (!canEditProperty(path)) return;\n commit(updateProperty(modelRef.current, path, patch));\n },\n changePropertyType(path: PropertyPath, next: PropertyTypeChoice) {\n if (!canEditProperty(path)) return;\n commit(changePropertyType(modelRef.current, path, next));\n },\n setReference(path: PropertyPath, name: string) {\n if (!canEditProperty(path)) return;\n commit(setReference(modelRef.current, path, name));\n },\n // Definitions are document-level, not path-scoped: gate on lock only.\n addDefinition(name?: string) {\n if (capabilities.locked) return;\n const res = addDefinition(modelRef.current, name);\n commit(res.model);\n setSelection(res.path);\n },\n renameDefinition(oldName: string, newName: string) {\n if (capabilities.locked) return;\n const res = renameDefinition(modelRef.current, oldName, newName);\n commit(res.model);\n // Keep the selection on the renamed definition.\n setSelection((prev) =>\n prev && samePath(prev, [defSeg(oldName)]) ? res.path : prev,\n );\n },\n removeDefinition(name: string) {\n if (capabilities.locked) return;\n commit(removeDefinition(modelRef.current, name));\n // Clear a selection sitting on (or inside) the removed definition.\n setSelection((prev) =>\n prev && pathStartsWith(prev, [defSeg(name)]) ? null : prev,\n );\n },\n // Replace the whole JSON Schema (from the editable JSON Schema tab).\n // The uiSchema is preserved. Gated by capabilities.locked only -- a\n // wholesale replace is not subject to per-path scoping.\n replaceSchema(schema: JsonSchema) {\n if (capabilities.locked) return;\n commit({ schema, uiSchema: modelRef.current.uiSchema });\n setSelection(null);\n },\n // Replace the whole UI Schema map (from the editable UI Schema tab).\n replaceUiSchema(uiSchema: UiSchemaMap) {\n if (readOnly) return;\n commit({ schema: modelRef.current.schema, uiSchema });\n },\n setEnum(path: PropertyPath, choices: EnumChoice[]) {\n if (!canEditProperty(path)) return;\n commit(setEnum(modelRef.current, path, choices));\n },\n // UI-schema / presentation ops use `readOnly` (not `capabilities.locked`)\n // because they are not subject to scoped-path gating: presentation hints\n // are always either fully editable or fully locked.\n setUiEntry(path: PropertyPath, entry: UISchema | undefined) {\n if (readOnly) return;\n commit(setUiEntry(modelRef.current, path, entry));\n },\n setTableHints(path: PropertyPath, hints: TableHints) {\n if (readOnly) return;\n commit(setTableHints(modelRef.current, path, hints));\n },\n setPropertyLayout(\n path: PropertyPath,\n layout: UILayoutConfig | undefined,\n ) {\n if (readOnly) return;\n commit(setPropertyLayout(modelRef.current, path, layout));\n },\n setRootLayout(layout: UILayoutConfig | undefined) {\n if (readOnly) return;\n commit(setRootLayout(modelRef.current, layout));\n },\n setRootLayoutRows(rows: UILayoutConfig[\"rows\"]) {\n if (readOnly) return;\n commit(setRootLayoutRows(modelRef.current, rows));\n },\n setScopedLayoutRows(\n scopePath: PropertyPath,\n rows: UILayoutConfig[\"rows\"],\n ) {\n if (readOnly) return;\n commit(setScopedLayoutRows(modelRef.current, scopePath, rows));\n },\n setScopedLayoutOptions(\n scopePath: PropertyPath,\n options: Pick<\n UILayoutConfig,\n \"direction\" | \"gap\" | \"labels\" | \"compact\"\n >,\n ) {\n if (readOnly) return;\n commit(setScopedLayoutOptions(modelRef.current, scopePath, options));\n },\n setScopedLayoutGroups(\n scopePath: PropertyPath,\n groups: UILayoutConfig[\"groups\"],\n ) {\n if (readOnly) return;\n commit(setScopedLayoutGroups(modelRef.current, scopePath, groups));\n },\n setScopedGroupRows(\n scopePath: PropertyPath,\n groupIndex: number,\n rows: UILayoutRowConfig[],\n ) {\n if (readOnly) return;\n commit(\n setScopedGroupRows(modelRef.current, scopePath, groupIndex, rows),\n );\n },\n setScopedLayoutMode(scopePath: PropertyPath, mode: \"rows\" | \"groups\") {\n if (readOnly) return;\n commit(setScopedLayoutMode(modelRef.current, scopePath, mode));\n },\n addLayoutGroup(scopePath: PropertyPath, label?: string) {\n if (readOnly) return;\n commit(addLayoutGroup(modelRef.current, scopePath, label));\n },\n renameLayoutGroup(\n scopePath: PropertyPath,\n groupIndex: number,\n label: string,\n ) {\n if (readOnly) return;\n commit(\n renameLayoutGroup(modelRef.current, scopePath, groupIndex, label),\n );\n },\n removeLayoutGroup(scopePath: PropertyPath, groupIndex: number) {\n if (readOnly) return;\n commit(removeLayoutGroup(modelRef.current, scopePath, groupIndex));\n },\n moveLayoutGroup(\n scopePath: PropertyPath,\n groupIndex: number,\n direction: -1 | 1,\n ) {\n if (readOnly) return;\n commit(\n moveLayoutGroup(modelRef.current, scopePath, groupIndex, direction),\n );\n },\n setLayoutGroupRule(\n scopePath: PropertyPath,\n groupIndex: number,\n rule: UILayoutGroupConfig[\"rule\"],\n ) {\n if (readOnly) return;\n commit(\n setLayoutGroupRule(modelRef.current, scopePath, groupIndex, rule),\n );\n },\n setScopedLayoutVariant(\n scopePath: PropertyPath,\n variant: UILayoutConfig[\"variant\"],\n ) {\n if (readOnly) return;\n commit(setScopedLayoutVariant(modelRef.current, scopePath, variant));\n },\n placeFieldInGroup(\n scopePath: PropertyPath,\n key: string,\n target: { groupIndex: number; rowIndex: number } | null,\n ) {\n if (readOnly) return;\n commit(placeFieldInGroup(modelRef.current, scopePath, key, target));\n },\n setGlobalOptions(options: UISchemaOptions | undefined) {\n if (readOnly) return;\n commit(setGlobalOptions(modelRef.current, options));\n },\n }),\n [commit, readOnly, capabilities.locked, canEditProperty, canAddChild],\n );\n\n return {\n schema: model.schema,\n uiSchema: model.uiSchema,\n selection,\n readOnly,\n refResolver: args.refResolver,\n capabilities,\n canEditProperty,\n canAddChild,\n select,\n ...ops,\n };\n}\n","/**\n * SchemaDesigner capabilities -- a small profile that gates what a consumer can\n * author. Mirrors the discipline of GraphModelEditor's capabilities: the Zod\n * schema below is the single source of truth, the TypeScript types are inferred\n * from it, and `resolveCapabilities` applies defaults (with `readOnly` as a\n * fully-locked shorthand). Every field is optional and defaults to the most\n * permissive value, so adding a capability never tightens an existing profile.\n *\n * Design: docs/design/schema-designer.md in this package; usage in\n * docs/usage/capabilities.md.\n */\n\nimport { z } from \"zod\";\nimport { warnLog } from \"@petrarca/sonnet-core\";\n\n/**\n * A tab the center pane can offer. \"form\" / \"table\" / \"json\" preview the\n * schema; \"capabilities\" is a meta-editor for the profile itself (a dev /\n * power-user affordance), not a preview -- it is opt-in and never in a default.\n */\nconst previewKindSchema = z.enum([\"form\", \"table\", \"json\", \"capabilities\"]);\n\nexport type PreviewKind = z.infer<typeof previewKindSchema>;\n\n/**\n * The capabilities schema. Small by design -- it covers the real consumer needs\n * (locked-down, single-schema editors embedded in an application) without a\n * per-area matrix we do not use yet.\n */\nexport const capabilitiesSchema = z\n .object({\n mode: z.enum([\"data\", \"full\"]).default(\"full\").meta({\n description:\n \"What the designer authors. 'full' (default): JSON Schema + uiSchema (form presentation hints). 'data': JSON Schema only -- the UI Schema tab, Combined tab, and the inspector's per-field UI tab are hidden (pure data schemas: audit events, terminology).\",\n }),\n previews: z.array(previewKindSchema).optional().meta({\n description:\n \"Which tabs the center pane offers, in order. 'form'/'table'/'json' preview the schema; 'capabilities' is a JSON editor for this profile (opt-in, never in a default). When omitted, defaults to ['form','table','json'] in 'full' mode and ['json'] in 'data' mode. An empty list hides the center pane entirely.\",\n }),\n editablePaths: z.array(z.string()).optional().meta({\n description:\n \"Scoped editing. When set, the passed-in schema is fixed EVERYWHERE except the children of these JSON Pointer (RFC 6901) paths, which the user may add / delete / edit. Absent = fully editable. readOnly overrides this to fully locked.\",\n }),\n })\n .meta({\n id: \"SchemaDesignerCapabilities\",\n title: \"SchemaDesignerCapabilities\",\n description:\n \"Capability profile for SchemaDesigner. Gates what a consumer can author. Every field is optional and defaults to the most permissive value (forward-compatible). Passing readOnly to the designer overrides this object to a fully-locked profile.\",\n });\n\n/**\n * The capabilities a consumer may pass. Inferred from the schema, with all\n * fields optional on input (defaults are applied by resolveCapabilities).\n */\nexport type SchemaDesignerCapabilities = z.input<typeof capabilitiesSchema>;\n\n/**\n * The schema's own fields once resolved. Derived from the schema rather than\n * restated, so adding or retyping a capability cannot silently drift from it.\n * `Required` because resolveCapabilities defaults every optional field --\n * `previews` by mode, `editablePaths` to empty -- so none is absent downstream.\n */\ntype ResolvedSchemaFields = Required<z.output<typeof capabilitiesSchema>>;\n\n/** The fully-resolved capabilities, plus the derived flags used for gating. */\nexport interface ResolvedCapabilities extends ResolvedSchemaFields {\n /** No structural edits at all (readOnly shorthand). */\n locked: boolean;\n /** editablePaths is non-empty -- only designated subtrees are editable. */\n scoped: boolean;\n /** The Capabilities editor tab is listed in previews. */\n showCapabilities: boolean;\n /** Whether the center pane renders at all (previews non-empty). */\n showPreview: boolean;\n}\n\n/** Default preview lists per mode. */\nfunction defaultPreviews(mode: \"data\" | \"full\"): PreviewKind[] {\n return mode === \"data\" ? [\"json\"] : [\"form\", \"table\", \"json\"];\n}\n\n/**\n * Resolve the effective capabilities: readOnly wins (fully locked), otherwise\n * parse the provided capabilities (applying per-field defaults). Invalid input\n * falls back to permissive defaults rather than throwing.\n */\nexport function resolveCapabilities(\n capabilities: SchemaDesignerCapabilities | undefined,\n readOnly: boolean | undefined,\n): ResolvedCapabilities {\n const parsed = capabilitiesSchema.safeParse(capabilities ?? {});\n const value = parsed.success ? parsed.data : capabilitiesSchema.parse({});\n if (!parsed.success) {\n warnLog(\n \"[SchemaDesigner] Invalid capabilities — falling back to defaults.\",\n parsed.error.issues,\n );\n }\n const mode = value.mode;\n const previews = value.previews ?? defaultPreviews(mode);\n const editablePaths = value.editablePaths ?? [];\n return {\n mode,\n previews,\n editablePaths,\n locked: !!readOnly,\n scoped: !readOnly && editablePaths.length > 0,\n showCapabilities: previews.includes(\"capabilities\"),\n showPreview: previews.length > 0,\n };\n}\n\n/** Result of validating an untrusted capabilities object. */\nexport type CapabilitiesValidation =\n | { ok: true; value: SchemaDesignerCapabilities }\n | { ok: false; errors: string[] };\n\n/**\n * Validate a hand-authored / external capabilities object. Returns the parsed\n * value or a list of readable error messages. Does not throw.\n */\nexport function validateCapabilities(input: unknown): CapabilitiesValidation {\n const parsed = capabilitiesSchema.safeParse(input);\n if (parsed.success) return { ok: true, value: parsed.data };\n const errors = parsed.error.issues.map((i) => {\n const path = i.path.length ? i.path.join(\".\") : \"(root)\";\n return `${path}: ${i.message}`;\n });\n return { ok: false, errors };\n}\n","/**\n * Scoped-editing helpers. When capabilities carry `editablePaths` (JSON Pointer,\n * RFC 6901), the schema is fixed everywhere except the *children* of those\n * paths. This module maps the designer's key-array PropertyPath to the JSON\n * Pointer of the container that holds a property, and decides whether a given\n * property (or the root) is editable.\n *\n * A property's own pointer is built by walking the schema from the root:\n * each segment contributes `/properties/<key>`, and an array crossing inserts\n * `/items` before descending (mirroring childContainer navigation). The\n * *parent container* pointer is the property pointer with the trailing\n * `/<key>` removed -- this is what `editablePaths` names (e.g.\n * `/properties/metadata/properties`).\n */\n\nimport type {\n JsonSchema,\n JsonSchemaProperty,\n} from \"@petrarca/sonnet-core/schema\";\nimport { childContainer } from \"./paths\";\nimport type { PropertyPath } from \"./paths\";\n\ntype PropMap = Record<string, JsonSchemaProperty>;\n\n/** RFC 6901 escape for a single reference token. */\nfunction escapeToken(token: string): string {\n return token.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n}\n\n/**\n * The JSON Pointer of the container object that holds the property at `path`\n * (i.e. the `...properties` pointer the property lives under). Returns\n * `/properties` for a top-level property. Returns undefined if the path does\n * not resolve.\n */\nexport function parentContainerPointer(\n schema: JsonSchema,\n path: PropertyPath,\n): string | undefined {\n if (path.length === 0) return undefined;\n let container: PropMap | undefined = schema.properties;\n let pointer = \"/properties\";\n for (let i = 0; i < path.length; i++) {\n if (!container) return undefined;\n const segment = path[i];\n // Scoping applies to property containers only; a non-property segment\n // (branch/slot) has no `.../properties` pointer.\n if (segment.kind !== \"prop\") return undefined;\n const key = segment.key;\n const prop = container[key];\n if (!prop) return undefined;\n // The container holding this segment is `pointer`. For the last segment we\n // are done -- that pointer is the parent container.\n if (i === path.length - 1) return pointer;\n // Descend: cross `/items` for array-of-object, then into `/properties`.\n const next = childContainer(prop);\n if (!next) return undefined;\n pointer =\n prop.type === \"array\"\n ? `${pointer}/${escapeToken(key)}/items/properties`\n : `${pointer}/${escapeToken(key)}/properties`;\n container = next;\n }\n return pointer;\n}\n\n/**\n * Whether the property at `path` is editable (rename / delete / retype /\n * reorder). In scoped mode a property is editable only when its parent\n * container is one of the editablePaths (i.e. it is a user-added member of a\n * designated area). Without editablePaths, everything is editable.\n */\nexport function isPropertyEditable(\n schema: JsonSchema,\n path: PropertyPath,\n editablePaths: string[],\n): boolean {\n if (editablePaths.length === 0) return true;\n // For paths that cross a branch/slot segment (e.g. into a oneOf branch),\n // walk up to the nearest all-prop prefix and evaluate editability there.\n // Editing inside a branch is permitted whenever the oneOf property itself\n // is editable.\n const allPropPrefix = path.slice(\n 0,\n path.findIndex((s) => s.kind !== \"prop\") + 1 || path.length,\n );\n const effectivePath =\n allPropPrefix.length < path.length ? allPropPrefix : path;\n const parent = parentContainerPointer(schema, effectivePath);\n if (parent === undefined) return false;\n return editablePaths.includes(parent);\n}\n\n/**\n * Whether children may be added to the container at `path` (or the root when\n * path is empty). Adding is allowed when the container's own children pointer\n * is a designated editable path. Without editablePaths, always true.\n */\nexport function canAddChildTo(\n schema: JsonSchema,\n path: PropertyPath,\n editablePaths: string[],\n): boolean {\n if (editablePaths.length === 0) return true;\n if (path.length === 0) return editablePaths.includes(\"/properties\");\n const own = ownChildContainerPointer(schema, path);\n return own !== undefined && editablePaths.includes(own);\n}\n\n/** The `.../properties` pointer of a container property (array-aware). */\nexport function ownChildContainerPointer(\n schema: JsonSchema,\n path: PropertyPath,\n): string | undefined {\n const parent = parentContainerPointer(schema, path);\n if (parent === undefined) return undefined;\n // Resolve the property to know if it is an array (crosses /items).\n let container: PropMap | undefined = schema.properties;\n for (let i = 0; i < path.length; i++) {\n const segment = path[i];\n if (segment.kind !== \"prop\") return undefined;\n const prop = container?.[segment.key];\n if (!prop) return undefined;\n if (i === path.length - 1) {\n const seg = escapeToken(segment.key);\n return prop.type === \"array\"\n ? `${parent}/${seg}/items/properties`\n : `${parent}/${seg}/properties`;\n }\n container = childContainer(prop);\n }\n return undefined;\n}\n","/**\n * SchemaDesigner -- visual, controlled designer for a JsonSchema (+ uiSchema).\n *\n * Layout: Tree | Preview | Inspector. The preview (the live form) is the hero\n * and takes the flexible center, matching visual-builder convention; the\n * inspector is the resizable/collapsible right pane. Controlled via `schema` +\n * `uiSchema` + `onChange`, or uncontrolled via `initialSchema`. Read-only is a\n * mode of the same component.\n *\n * This is the assembly shell; the tree, preview, and inspector are built up\n * incrementally.\n */\n\nimport React, { useEffect, useState } from \"react\";\nimport { ResizeHandle, IconButton } from \"@petrarca/sonnet-ui\";\nimport { useResizablePanel } from \"@petrarca/sonnet-core/hooks\";\nimport {\n Settings,\n PanelRightClose,\n PanelRightOpen,\n PanelLeftOpen,\n} from \"lucide-react\";\nimport type {\n JsonSchema,\n UISchema,\n RefResolver,\n} from \"@petrarca/sonnet-core/schema\";\nimport type { WidgetOptionDef } from \"@petrarca/sonnet-forms/widget-options\";\nimport { useDesignerState } from \"./hooks/useDesignerState\";\nimport type { SchemaDesignerCapabilities } from \"./capabilities\";\nimport { FormSettingsSheet } from \"./FormSettingsSheet\";\nimport { PropertyTree } from \"./tree/PropertyTree\";\nimport { PreviewPane } from \"./preview/PreviewPane\";\nimport { Inspector } from \"./inspector/Inspector\";\n\nexport interface SchemaDesignerProps {\n /** Controlled schema. Provide with onChange. */\n schema?: JsonSchema;\n /** Controlled uiSchema map (form presentation hints). */\n uiSchema?: Record<string, UISchema>;\n /** Uncontrolled seed schema (used when `schema` is omitted). */\n initialSchema?: JsonSchema;\n /** Uncontrolled seed uiSchema. */\n initialUiSchema?: Record<string, UISchema>;\n /**\n * Called on every edit with the new schema + uiSchema (always the separate\n * form: schema is the data model, form hints live in uiSchema). Use the\n * exported `embedUiSchema` helper if a single self-contained schema is wanted.\n */\n onChange?: (schema: JsonSchema, uiSchema: Record<string, UISchema>) => void;\n /** View-only: no edit affordances, onChange never fires. Shorthand for a fully-locked profile. */\n readOnly?: boolean;\n /** Capability profile: gates data/full mode, preview renderers, and scoped editing. */\n capabilities?: SchemaDesignerCapabilities;\n /** Option descriptors for custom widgets, keyed by widget name (merged over built-ins). */\n widgetOptions?: Record<string, WidgetOptionDef[]>;\n /**\n * Optional resolver for non-local `$ref`s (schema-registry id / canonical\n * URI). Local `#/$defs` refs resolve automatically. When provided, ref nodes\n * are expanded read-only in the tree. Synchronous -- pre-load referenced\n * schemas and pass a lookup.\n */\n refResolver?: RefResolver;\n}\n\nexport function SchemaDesigner(props: SchemaDesignerProps): React.ReactElement {\n // Editable capabilities: seeded from the prop, live-editable via the\n // Capabilities tab (when previews include \"capabilities\"). Re-seeds via\n // useEffect when the prop identity changes (avoids a render-phase update).\n const [capabilities, setCapabilities] = useState<\n SchemaDesignerCapabilities | undefined\n >(props.capabilities);\n useEffect(() => {\n setCapabilities(props.capabilities);\n }, [props.capabilities]);\n\n const state = useDesignerState({ ...props, capabilities });\n\n const {\n panelWidth: inspectorWidth,\n handlePointerDown: startInspectorResize,\n handleDoubleClick: resetInspectorWidth,\n separatorProps: inspectorSepProps,\n } = useResizablePanel({\n defaultWidth: 360,\n minWidth: 300,\n maxWidth: 640,\n direction: \"left-edge\",\n });\n\n const {\n panelWidth: treeWidth,\n handlePointerDown: startTreeResize,\n handleDoubleClick: resetTreeWidth,\n separatorProps: treeSepProps,\n } = useResizablePanel({\n defaultWidth: 288,\n minWidth: 220,\n maxWidth: 520,\n direction: \"right-edge\",\n });\n\n const [inspectorCollapsed, setInspectorCollapsed] = useState(false);\n const [treeCollapsed, setTreeCollapsed] = useState(false);\n const [settingsOpen, setSettingsOpen] = useState(false);\n\n return (\n <div className=\"flex w-full h-full overflow-hidden border rounded-lg bg-background\">\n {/* Left: property tree (resizable/collapsible). Grows to fill when the\n center preview pane is hidden (tree + inspector only). */}\n {!treeCollapsed && (\n <>\n <div\n style={\n state.capabilities.showPreview ? { width: treeWidth } : undefined\n }\n className={\n state.capabilities.showPreview\n ? \"shrink-0 overflow-hidden p-3 flex flex-col min-h-0\"\n : \"flex-1 min-w-0 overflow-hidden p-3 flex flex-col min-h-0\"\n }\n >\n <PropertyTree\n state={state}\n onCollapse={() => setTreeCollapsed(true)}\n />\n </div>\n {state.capabilities.showPreview && (\n <ResizeHandle\n orientation=\"vertical\"\n {...treeSepProps}\n onPointerDown={startTreeResize}\n onDoubleClick={resetTreeWidth}\n />\n )}\n </>\n )}\n {treeCollapsed && (\n <div className=\"shrink-0 border-r flex flex-col items-center gap-1 p-1\">\n <IconButton\n label=\"Expand properties\"\n onClick={() => setTreeCollapsed(false)}\n >\n <PanelLeftOpen />\n </IconButton>\n </div>\n )}\n\n {/* Center: preview (the hero -- live form + JSON). Hidden when the\n capability profile lists no previews (structure-editing only). */}\n {state.capabilities.showPreview && (\n <div className=\"flex-1 min-w-0 overflow-hidden p-4 flex flex-col min-h-0\">\n <PreviewPane\n state={state}\n capabilities={capabilities}\n onCapabilitiesChange={setCapabilities}\n />\n </div>\n )}\n\n {/* Right: inspector (resizable/collapsible) */}\n {!inspectorCollapsed && (\n <>\n <ResizeHandle\n orientation=\"vertical\"\n {...inspectorSepProps}\n onPointerDown={startInspectorResize}\n onDoubleClick={resetInspectorWidth}\n />\n <div\n style={{ width: inspectorWidth }}\n className=\"shrink-0 border-l overflow-auto p-4 bg-card\"\n >\n <div className=\"flex items-center gap-1 mb-2\">\n <p className=\"heading-meta\">Inspector</p>\n <span className=\"ml-auto flex gap-0.5\">\n <IconButton\n label=\"Form settings\"\n onClick={() => setSettingsOpen(true)}\n >\n <Settings />\n </IconButton>\n <IconButton\n label=\"Collapse inspector\"\n onClick={() => setInspectorCollapsed(true)}\n >\n <PanelRightClose />\n </IconButton>\n </span>\n </div>\n <Inspector state={state} widgetOptions={props.widgetOptions} />\n </div>\n </>\n )}\n {inspectorCollapsed && (\n <div className=\"shrink-0 border-l flex flex-col items-center gap-1 p-1\">\n <IconButton\n label=\"Expand inspector\"\n onClick={() => setInspectorCollapsed(false)}\n >\n <PanelRightOpen />\n </IconButton>\n <IconButton\n label=\"Form settings\"\n onClick={() => setSettingsOpen(true)}\n >\n <Settings />\n </IconButton>\n </div>\n )}\n\n <FormSettingsSheet\n open={settingsOpen}\n onOpenChange={setSettingsOpen}\n state={state}\n />\n </div>\n );\n}\n\nexport default SchemaDesigner;\n","/**\n * FormSettingsSheet -- form-level (root) settings in a right-side Sheet, opened\n * from a gear button. Holds settings that are not tied to a single property:\n * the root form layout (x-ui-layout) and global options (x-ui-globalOptions).\n *\n * Uses the house-standard Sheet pattern (as in graph-model's PropertyFormSheet).\n * Kept out of the inspector's per-property tabs, which do not scale to\n * form-wide concerns.\n */\n\nimport React from \"react\";\nimport {\n Sheet,\n SheetContent,\n SheetHeader,\n SheetBody,\n SheetTitle,\n SheetDescription,\n} from \"@petrarca/sonnet-ui\";\nimport { JsonSchemaFormRenderer, FormSelect } from \"@petrarca/sonnet-forms\";\nimport type {\n UISchemaOptions,\n UILayoutConfig,\n} from \"@petrarca/sonnet-core/schema\";\nimport type { DesignerState } from \"./hooks/useDesignerState\";\nimport {\n buildGlobalOptionsMetaSchema,\n globalOptionsToValues,\n valuesToGlobalOptions,\n type GlobalOptionsFormValues,\n} from \"./inspector/layoutMetaSchemas\";\n\nexport interface FormSettingsSheetProps {\n open: boolean;\n onOpenChange: (open: boolean) => void;\n state: DesignerState;\n}\n\nexport function FormSettingsSheet({\n open,\n onOpenChange,\n state,\n}: FormSettingsSheetProps): React.ReactElement {\n const globalOptions = state.uiSchema[\"x-ui-globalOptions\"] as\n | UISchemaOptions\n | undefined;\n\n const optionValues = globalOptionsToValues(globalOptions);\n\n const rootLayout = state.uiSchema[\"x-ui-layout\"] as\n | UILayoutConfig\n | undefined;\n const labelPlacement = rootLayout?.labelPlacement ?? \"top\";\n\n // \"top\" is the default -- omit it (and prune an emptied layout) so the\n // uiSchema stays clean.\n const setLabelPlacement = (value: \"top\" | \"start\") => {\n const next: UILayoutConfig = { ...(rootLayout ?? {}) };\n if (value === \"start\") next.labelPlacement = \"start\";\n else delete next.labelPlacement;\n state.setRootLayout(Object.keys(next).length ? next : undefined);\n };\n\n return (\n <Sheet open={open} onOpenChange={onOpenChange}>\n <SheetContent>\n <SheetHeader>\n <SheetTitle>Form settings</SheetTitle>\n <SheetDescription>\n Options applied to every field in the form.\n </SheetDescription>\n </SheetHeader>\n <SheetBody className=\"space-y-6\">\n <section className=\"space-y-2\">\n <p className=\"heading-meta\">Layout</p>\n <FormSelect\n id=\"root-labelPlacement\"\n name=\"labelPlacement\"\n label=\"Label placement\"\n value={labelPlacement}\n options={[\n { value: \"top\", label: \"Above\" },\n { value: \"start\", label: \"Inline (start)\" },\n ]}\n onChange={(v) =>\n setLabelPlacement(v === \"start\" ? \"start\" : \"top\")\n }\n disabled={state.readOnly}\n clearable={false}\n />\n </section>\n <section className=\"space-y-2\">\n <p className=\"heading-meta\">Global options</p>\n <JsonSchemaFormRenderer\n schema={buildGlobalOptionsMetaSchema()}\n data={optionValues as unknown as Record<string, unknown>}\n onChange={(data) =>\n state.setGlobalOptions(\n valuesToGlobalOptions(data as GlobalOptionsFormValues),\n )\n }\n showActions={false}\n showExtraProperties={false}\n readOnly={state.readOnly}\n />\n </section>\n </SheetBody>\n </SheetContent>\n </Sheet>\n );\n}\n","/**\n * Meta-schemas for layout (x-ui-layout) and global options (x-ui-globalOptions),\n * rendered by JsonSchemaFormRenderer. Covers the scalar array-item layout\n * options (direction / gap / labels / compact); the visual row builder lives in\n * FormLayoutDesigner.\n */\n\nimport type {\n JsonSchema,\n UILayoutConfig,\n UISchemaOptions,\n} from \"@petrarca/sonnet-core/schema\";\n\n/** Tier-1 layout meta-schema (no row builder). */\nexport function buildLayoutMetaSchema(): JsonSchema {\n return {\n title: \"\",\n type: \"object\",\n properties: {\n direction: {\n type: \"string\",\n title: \"Direction\",\n enum: [\"vertical\", \"horizontal\"],\n description: \"Stack fields vertically or lay them out horizontally.\",\n },\n gap: {\n type: \"integer\",\n title: \"Gap (px)\",\n minimum: 0,\n description: \"Space between fields.\",\n },\n labels: {\n type: \"boolean\",\n title: \"Show labels\",\n },\n compact: {\n type: \"boolean\",\n title: \"Compact\",\n description: \"Smaller control sizing.\",\n },\n },\n };\n}\n\n/** Flat form values for the layout meta-schema. */\nexport interface LayoutFormValues {\n direction?: string;\n gap?: number;\n labels?: boolean;\n compact?: boolean;\n}\n\n/** Read tier-1 layout values from a UILayoutConfig. */\nexport function layoutToValues(\n layout: UILayoutConfig | undefined,\n): LayoutFormValues {\n return {\n direction: layout?.direction,\n gap: layout?.gap,\n labels: layout?.labels,\n compact: layout?.compact,\n };\n}\n\n/**\n * Merge tier-1 form values back into an existing layout, preserving keys the\n * tier-1 form does not manage (e.g. rows, columns). Empty/undefined clears the\n * managed key. Returns undefined when the result is empty.\n */\nexport function valuesToLayout(\n values: LayoutFormValues,\n existing: UILayoutConfig | undefined,\n): UILayoutConfig | undefined {\n const next: UILayoutConfig = { ...(existing ?? {}) };\n\n if (values.direction === \"vertical\" || values.direction === \"horizontal\") {\n next.direction = values.direction;\n } else {\n delete next.direction;\n }\n if (typeof values.gap === \"number\" && !Number.isNaN(values.gap)) {\n next.gap = values.gap;\n } else {\n delete next.gap;\n }\n if (typeof values.labels === \"boolean\") next.labels = values.labels;\n else delete next.labels;\n if (typeof values.compact === \"boolean\") next.compact = values.compact;\n else delete next.compact;\n\n return Object.keys(next).length > 0 ? next : undefined;\n}\n\n/** Global options meta-schema (x-ui-globalOptions -- applies to all fields). */\nexport function buildGlobalOptionsMetaSchema(): JsonSchema {\n return {\n title: \"\",\n type: \"object\",\n properties: {\n disabled: { type: \"boolean\", title: \"Disable all fields\" },\n readonly: { type: \"boolean\", title: \"Read-only all fields\" },\n hideLabels: {\n type: \"boolean\",\n title: \"Hide all labels\",\n description: \"Sets label: false on every field.\",\n },\n compact: { type: \"boolean\", title: \"Compact all fields\" },\n },\n };\n}\n\n/** Flat form values for the global-options meta-schema. */\nexport interface GlobalOptionsFormValues {\n disabled?: boolean;\n readonly?: boolean;\n hideLabels?: boolean;\n compact?: boolean;\n}\n\n/** Read global-options form values from a UISchemaOptions object. */\nexport function globalOptionsToValues(\n options: UISchemaOptions | undefined,\n): GlobalOptionsFormValues {\n return {\n disabled: options?.disabled,\n readonly: options?.readonly,\n hideLabels: options?.label === false,\n compact: options?.compact,\n };\n}\n\n/** Merge global-options form values into a UISchemaOptions; undefined if empty. */\nexport function valuesToGlobalOptions(\n values: GlobalOptionsFormValues,\n): UISchemaOptions | undefined {\n const next: UISchemaOptions = {};\n if (values.disabled) next.disabled = true;\n if (values.readonly) next.readonly = true;\n if (values.hideLabels) next.label = false;\n if (values.compact) next.compact = true;\n return Object.keys(next).length > 0 ? next : undefined;\n}\n","/**\n * PropertyTree -- the left pane. Renders the schema's properties as a\n * hierarchical list with select / add / delete / reorder. Row idiom matches\n * graph-model/TypeDetailPanel for cross-editor consistency.\n */\n\nimport React, { useEffect, useMemo, useRef, useState } from \"react\";\nimport { cn } from \"@petrarca/sonnet-core\";\nimport { IconButton, Input } from \"@petrarca/sonnet-ui\";\nimport {\n Plus,\n Trash2,\n ChevronUp,\n ChevronDown,\n PanelLeftClose,\n Lock,\n GitBranch,\n SplitSquareHorizontal,\n Eye,\n Braces,\n Brackets,\n GitFork,\n CornerDownRight,\n Type,\n List,\n ToggleLeft,\n Hash,\n Link2,\n Puzzle,\n ChevronRight,\n type LucideIcon,\n} from \"lucide-react\";\nimport type { UIRule } from \"@petrarca/sonnet-core/schema\";\nimport type { DesignerState } from \"../hooks/useDesignerState\";\nimport { buildPropertyTree, type PropertyNode } from \"../model/view\";\nimport { pathKey, samePath } from \"../model/paths\";\nimport { definitionUsageCount } from \"../model/mutate\";\n\n// Build a memoized set of definition names that have at least one $ref,\n// computed once per schema change at the DefinitionsRegion level so row\n// renders do not each trigger a full schema walk.\nfunction buildInUseDefs(\n schema: DesignerState[\"schema\"],\n names: string[],\n): Set<string> {\n return new Set(names.filter((n) => definitionUsageCount(schema, n) > 0));\n}\n\nexport interface PropertyTreeProps {\n state: DesignerState;\n /** When provided, renders a collapse button in the header. */\n onCollapse?: () => void;\n}\n\nexport function PropertyTree({\n state,\n onCollapse,\n}: PropertyTreeProps): React.ReactElement {\n const nodes = useMemo(\n () => buildPropertyTree(state.schema, state.refResolver),\n [state.schema, state.refResolver],\n );\n // Definitions ($defs) render in their own region, separate from properties.\n const propertyNodes = useMemo(\n () => nodes.filter((n) => n.kind !== \"definition\"),\n [nodes],\n );\n const definitionNodes = useMemo(\n () => nodes.filter((n) => n.kind === \"definition\"),\n [nodes],\n );\n const canEditDefs = !state.capabilities.locked;\n const [propsOpen, setPropsOpen] = useState(true);\n\n return (\n <div className=\"flex h-full flex-col min-h-0\">\n <div className=\"mb-2 flex items-center gap-2 shrink-0\">\n <button\n type=\"button\"\n className=\"flex items-center gap-1 heading-meta\"\n onClick={() => setPropsOpen((v) => !v)}\n >\n {propsOpen ? (\n <ChevronDown className=\"h-3 w-3\" />\n ) : (\n <ChevronRight className=\"h-3 w-3\" />\n )}\n Properties\n {propertyNodes.length > 0 && (\n <span className=\"text-muted-foreground/60\">\n ({propertyNodes.length})\n </span>\n )}\n </button>\n <span className=\"ml-auto flex gap-1\">\n {state.canAddChild([]) && (\n <IconButton\n label=\"Add property\"\n onClick={() => {\n setPropsOpen(true);\n state.addProperty([], \"scalar\");\n }}\n >\n <Plus />\n </IconButton>\n )}\n {state.canAddChild([]) && (\n <IconButton\n label=\"Add condition\"\n onClick={() => {\n setPropsOpen(true);\n state.addConditional([]);\n }}\n >\n <GitBranch />\n </IconButton>\n )}\n {onCollapse && (\n <IconButton label=\"Collapse properties\" onClick={onCollapse}>\n <PanelLeftClose />\n </IconButton>\n )}\n </span>\n </div>\n\n {propsOpen &&\n (propertyNodes.length === 0 ? (\n <p className=\"text-xs text-muted-foreground\">No properties yet.</p>\n ) : (\n <div className=\"flex-1 min-h-0 overflow-auto rounded-lg border divide-y\">\n {propertyNodes.map((node) => (\n <PropertyRow\n key={pathKey(node.path)}\n node={node}\n state={state}\n depth={0}\n />\n ))}\n </div>\n ))}\n\n <DefinitionsRegion\n nodes={definitionNodes}\n state={state}\n canEdit={canEditDefs}\n />\n </div>\n );\n}\n\n// The DEFINITIONS region: a collapsible section listing $defs entries as\n// editable nodes. Collapsed by default so data-only schemas stay uncluttered.\nfunction DefinitionsRegion({\n nodes,\n state,\n canEdit,\n}: {\n nodes: PropertyNode[];\n state: DesignerState;\n canEdit: boolean;\n}): React.ReactElement | null {\n const [open, setOpen] = useState(false);\n // Compute usage counts once per schema change -- not per row render.\n const inUseDefs = useMemo(\n () =>\n buildInUseDefs(\n state.schema,\n nodes.map((n) => n.key),\n ),\n [state.schema, nodes],\n );\n // Nothing to show and nothing to add: hide the region entirely.\n if (nodes.length === 0 && !canEdit) return null;\n return (\n <div className=\"mt-3 shrink-0\">\n <div className=\"mb-2 flex items-center gap-2\">\n <button\n type=\"button\"\n className=\"flex items-center gap-1 heading-meta\"\n onClick={() => setOpen((v) => !v)}\n >\n {open ? (\n <ChevronDown className=\"h-3 w-3\" />\n ) : (\n <ChevronRight className=\"h-3 w-3\" />\n )}\n Definitions\n {nodes.length > 0 && (\n <span className=\"text-muted-foreground/60\">({nodes.length})</span>\n )}\n </button>\n {canEdit && (\n <span className=\"ml-auto flex gap-1\">\n <IconButton\n label=\"Add definition\"\n onClick={() => {\n setOpen(true);\n state.addDefinition();\n }}\n >\n <Plus />\n </IconButton>\n </span>\n )}\n </div>\n {open &&\n (nodes.length === 0 ? (\n <p className=\"text-xs text-muted-foreground\">No definitions yet.</p>\n ) : (\n <div className=\"max-h-64 overflow-auto rounded-lg border divide-y\">\n {nodes.map((node) => (\n <PropertyRow\n key={pathKey(node.path)}\n node={node}\n state={state}\n depth={0}\n inUseDefs={inUseDefs}\n />\n ))}\n </div>\n ))}\n </div>\n );\n}\n\n// Inline key editor: an input seeded with the current key, committing on Enter\n// or blur and cancelling on Escape.\nfunction NameEditor({\n initial,\n onCommit,\n onCancel,\n}: {\n initial: string;\n onCommit: (next: string) => void;\n onCancel: () => void;\n}): React.ReactElement {\n const [value, setValue] = useState(initial);\n const ref = useRef<HTMLInputElement>(null);\n useEffect(() => {\n ref.current?.focus();\n ref.current?.select();\n }, []);\n const commit = () => {\n const trimmed = value.trim();\n if (trimmed && trimmed !== initial) onCommit(trimmed);\n else onCancel();\n };\n return (\n <Input\n ref={ref}\n value={value}\n onChange={(e) => setValue(e.target.value)}\n onClick={(e) => e.stopPropagation()}\n onBlur={commit}\n onKeyDown={(e) => {\n if (e.key === \"Enter\") {\n e.preventDefault();\n commit();\n } else if (e.key === \"Escape\") {\n e.preventDefault();\n onCancel();\n }\n }}\n className=\"h-6 text-sm py-0\"\n />\n );\n}\n\n// Icon + label per property kind (scalar is resolved by primitive type below).\nconst KIND_ICONS: Partial<\n Record<PropertyNode[\"kind\"], { Icon: LucideIcon; label: string }>\n> = {\n reference: { Icon: Link2, label: \"reference\" },\n definition: { Icon: Puzzle, label: \"definition\" },\n conditional: { Icon: GitBranch, label: \"condition\" },\n object: { Icon: Braces, label: \"object\" },\n array: { Icon: Brackets, label: \"array\" },\n oneOf: { Icon: GitFork, label: \"one of\" },\n enum: { Icon: List, label: \"choice\" },\n};\n\n// The leading icon for a node, chosen by its class (kind + slot). Disambiguates\n// data vs. structure vs. logic at a glance (VS Code / Figma-layer idiom).\nfunction kindIconFor(node: PropertyNode): { Icon: LucideIcon; label: string } {\n const last = node.path[node.path.length - 1];\n if (last?.kind === \"slot\") return { Icon: CornerDownRight, label: \"branch\" };\n if (node.slotKind === \"branch\") return { Icon: GitFork, label: \"variant\" };\n return KIND_ICONS[node.kind] ?? scalarIcon(node.property.type);\n}\n\n// Scalar sub-icon by primitive type.\nfunction scalarIcon(type: string | undefined): {\n Icon: LucideIcon;\n label: string;\n} {\n if (type === \"number\" || type === \"integer\")\n return { Icon: Hash, label: \"number\" };\n if (type === \"boolean\") return { Icon: ToggleLeft, label: \"boolean\" };\n return { Icon: Type, label: \"text\" };\n}\n\nfunction KindIcon({ node }: { node: PropertyNode }): React.ReactElement {\n const { Icon, label } = kindIconFor(node);\n return (\n <Icon\n className=\"h-3.5 w-3.5 shrink-0 text-muted-foreground/60\"\n aria-label={label}\n />\n );\n}\n\n// Markers slot: icon badges for field metadata (required, visibility rule).\n// Icons (not color alone) carry meaning; hidden on hover like the type label.\nfunction Markers({ node }: { node: PropertyNode }): React.ReactElement | null {\n const rule = node.property[\"x-ui-rule\"] as UIRule | undefined;\n if (!node.required && !rule) return null;\n const scopeField = rule?.condition.scope.replace(/^\\//, \"\");\n const ruleTip = rule\n ? `${rule.effect} when ${scopeField || rule.condition.scope}`\n : \"\";\n return (\n <span className=\"shrink-0 flex items-center gap-1 group-hover/row:hidden\">\n {node.required && (\n <span\n className=\"text-destructive text-xs leading-none\"\n title=\"required\"\n aria-label=\"required\"\n >\n *\n </span>\n )}\n {rule && (\n <span title={ruleTip} aria-label={ruleTip} className=\"flex\">\n <Eye className=\"h-3 w-3 text-primary\" />\n </span>\n )}\n </span>\n );\n}\n\n// Whether a child may be added at this node. oneOf branches and then/else\n// slots are reached through non-property segments (which the JSON Pointer\n// scoping in canAddChild cannot represent), so they gate on canEditProperty\n// (the owning construct being editable) instead.\nfunction canAddChildHere(\n node: PropertyNode,\n state: DesignerState,\n isConditional: boolean,\n): boolean {\n if (!acceptsChildren(node)) return false;\n return node.kind === \"oneOf\" || isConditional\n ? state.canEditProperty(node.path)\n : state.canAddChild(node.path);\n}\n\n// A conditional's label reads as a rule (\"IF smoker\"), not a property name.\nfunction isRuleStyled(node: PropertyNode): boolean {\n const last = node.path[node.path.length - 1];\n return node.kind === \"conditional\" || last?.kind === \"slot\";\n}\n\n// The kind icon + name (rule-styled for logic nodes) + markers + type label.\nfunction RowLabel({\n node,\n editable,\n onStartRename,\n}: {\n node: PropertyNode;\n editable: boolean;\n onStartRename: (e: React.MouseEvent) => void;\n}): React.ReactElement {\n const title = editable\n ? `${node.key}${node.required ? \" (required)\" : \"\"} -- double-click to rename`\n : `${node.key} -- fixed (not editable)`;\n const ruleStyled = isRuleStyled(node);\n return (\n <>\n <KindIcon node={node} />\n <span\n className={cn(\n \"flex-1 min-w-0 truncate text-sm\",\n ruleStyled\n ? \"font-mono text-xs uppercase tracking-wide text-muted-foreground\"\n : \"font-medium\",\n )}\n onDoubleClick={onStartRename}\n title={title}\n >\n {node.key}\n </span>\n {!editable && (\n <Lock\n className=\"h-3 w-3 shrink-0 text-muted-foreground/50\"\n aria-label=\"fixed\"\n />\n )}\n <Markers node={node} />\n <span\n className=\"shrink-0 max-w-[40%] truncate font-mono text-[11px] text-muted-foreground/70 group-hover/row:hidden\"\n title={node.typeLabel}\n >\n {node.typeLabel}\n </span>\n </>\n );\n}\n\n// A conditional member (the allOf if/then/else node) -- distinct from a\n// then/else slot, which is an object-shaped container.\nfunction isConditionalMember(node: PropertyNode): boolean {\n return node.kind === \"conditional\";\n}\n\n// A then/else slot node: an object container reached through a slot segment.\nfunction isConditionalSlot(node: PropertyNode): boolean {\n const last = node.path[node.path.length - 1];\n return node.slotKind === \"conditional\" && last?.kind === \"slot\";\n}\n\n// Whether a node can hold property children (object/array, a oneOf branch, or a\n// then/else slot). oneOf holds branches; a conditional member holds then/else.\nfunction acceptsChildren(node: PropertyNode): boolean {\n return (\n node.kind === \"object\" ||\n node.kind === \"array\" ||\n node.kind === \"oneOf\" ||\n node.kind === \"definition\" ||\n node.slotKind === \"branch\" ||\n isConditionalSlot(node)\n );\n}\n\n// Whether \"Add condition\" applies: object/array containers and the root can host\n// an if/then/else (a then/else slot is itself object-like, so also qualifies).\nfunction acceptsConditions(node: PropertyNode): boolean {\n return node.kind === \"object\" || isConditionalSlot(node);\n}\n\n// A hover-revealed icon button that stops row-click propagation.\nfunction ActionButton({\n label,\n tone,\n disabled,\n onAct,\n children,\n}: {\n label: string;\n tone?: \"destructive\";\n disabled?: boolean;\n onAct: () => void;\n children: React.ReactNode;\n}): React.ReactElement {\n return (\n <IconButton\n label={label}\n tone={tone}\n disabled={disabled}\n revealOnHover\n onClick={(e) => {\n e.stopPropagation();\n onAct();\n }}\n >\n {children}\n </IconButton>\n );\n}\n\n// Move up/down buttons for a reorderable node.\nfunction MoveActions({\n node,\n state,\n}: {\n node: PropertyNode;\n state: DesignerState;\n}): React.ReactElement {\n const isBranch = node.slotKind === \"branch\";\n const move = (dir: -1 | 1) =>\n isBranch\n ? state.moveBranch(node.path, dir)\n : state.moveProperty(node.path, dir);\n return (\n <>\n <ActionButton label=\"Move up\" onAct={() => move(-1)}>\n <ChevronUp />\n </ActionButton>\n <ActionButton label=\"Move down\" onAct={() => move(1)}>\n <ChevronDown />\n </ActionButton>\n </>\n );\n}\n\n// The additive actions (add child / add condition / add else) for a row.\nfunction AddActions({\n node,\n state,\n editable,\n canAddHere,\n}: {\n node: PropertyNode;\n state: DesignerState;\n editable: boolean;\n canAddHere: boolean;\n}): React.ReactElement {\n const isOneOf = node.kind === \"oneOf\";\n const addChild = () =>\n isOneOf\n ? state.addBranch(node.path)\n : state.addProperty(node.path, \"scalar\");\n const condMember = isConditionalMember(node) && editable;\n const hasElse = !!node.property.else;\n return (\n <>\n {canAddHere && (\n <ActionButton\n label={isOneOf ? \"Add branch\" : \"Add child property\"}\n onAct={addChild}\n >\n <Plus />\n </ActionButton>\n )}\n {editable && acceptsConditions(node) && (\n <ActionButton\n label=\"Add condition\"\n onAct={() => state.addConditional(node.path)}\n >\n <GitBranch />\n </ActionButton>\n )}\n {/* Add else on the conditional; removing else is done from the else row. */}\n {condMember && !hasElse && (\n <ActionButton label=\"Add else\" onAct={() => state.addElse(node.path)}>\n <SplitSquareHorizontal />\n </ActionButton>\n )}\n </>\n );\n}\n\n// The last path segment, or undefined for the root.\nfunction lastSegment(node: PropertyNode) {\n return node.path[node.path.length - 1];\n}\n\ninterface RemoveDescriptor {\n label: string;\n disabled: boolean;\n remove: () => void;\n}\n\n// The removal label + action for a row, or null when the row is not removable\n// (the `then` slot is permanent -- a conditional always needs a then).\nfunction removeDescriptor(\n node: PropertyNode,\n state: DesignerState,\n inUseDefs: Set<string>,\n): RemoveDescriptor | null {\n const last = lastSegment(node);\n const slotName = last?.kind === \"slot\" ? last.slot : undefined;\n if (slotName === \"then\") return null; // then is not removable\n if (node.slotKind === \"branch\") {\n return simpleRemove(\"Remove branch\", () => state.removeBranch(node.path));\n }\n if (isConditionalMember(node)) {\n return simpleRemove(\"Remove condition\", () =>\n state.removeConditional(node.path),\n );\n }\n if (node.kind === \"definition\") {\n const inUse = inUseDefs.has(node.key);\n return {\n label: inUse ? \"In use -- remove references first\" : \"Delete definition\",\n disabled: inUse,\n remove: () => state.removeDefinition(node.key),\n };\n }\n if (slotName === \"else\") {\n return simpleRemove(\"Remove else\", () =>\n state.removeElse(node.path.slice(0, -1)),\n );\n }\n return simpleRemove(\"Delete property\", () => state.deleteProperty(node.path));\n}\n\n// An always-enabled remove descriptor (the common case).\nfunction simpleRemove(label: string, remove: () => void): RemoveDescriptor {\n return { label, disabled: false, remove };\n}\n\n// The destructive action for a row.\nfunction RemoveAction({\n node,\n state,\n inUseDefs,\n}: {\n node: PropertyNode;\n state: DesignerState;\n inUseDefs: Set<string>;\n}): React.ReactElement | null {\n const desc = removeDescriptor(node, state, inUseDefs);\n if (!desc) return null;\n return (\n <ActionButton\n label={desc.label}\n tone=\"destructive\"\n disabled={desc.disabled}\n onAct={desc.remove}\n >\n <Trash2 />\n </ActionButton>\n );\n}\n\n// Hover-revealed row actions (move / add / delete), gated by editability.\n// Reorder is suppressed for conditionals and then/else slots (positional).\nconst EMPTY_SET: Set<string> = new Set();\n\nfunction RowActions({\n node,\n state,\n editable,\n canAddHere,\n inUseDefs = EMPTY_SET,\n}: {\n node: PropertyNode;\n state: DesignerState;\n editable: boolean;\n canAddHere: boolean;\n inUseDefs?: Set<string>;\n}): React.ReactElement {\n const reorderable =\n editable &&\n node.slotKind !== \"conditional\" &&\n node.slotKind !== \"definition\";\n return (\n <>\n {reorderable && <MoveActions node={node} state={state} />}\n <AddActions\n node={node}\n state={state}\n editable={editable}\n canAddHere={canAddHere}\n />\n {editable && (\n <RemoveAction node={node} state={state} inUseDefs={inUseDefs} />\n )}\n </>\n );\n}\n\nfunction PropertyRow({\n node,\n state,\n depth,\n inUseDefs = EMPTY_SET,\n}: {\n node: PropertyNode;\n state: DesignerState;\n depth: number;\n inUseDefs?: Set<string>;\n}): React.ReactElement {\n const selected = samePath(state.selection, node.path);\n const [editing, setEditing] = useState(false);\n\n // Scoped/readOnly gating: a fixed property shows no edit affordances (and a\n // lock indicator); \"add child\" follows canAddChild for containers. Fields\n // inside a $ref (node.readOnly) are never editable -- flagged at build time,\n // so no per-row schema walk.\n const editable = !node.readOnly && state.canEditProperty(node.path);\n // Branches and oneOf unions accept children too: a oneOf takes branches,\n // a branch takes properties, object/array take properties.\n const isBranch = node.slotKind === \"branch\";\n const isConditional = node.slotKind === \"conditional\";\n const isDefinition = node.kind === \"definition\";\n // Definitions are document-level: editability is the lock, not path scoping.\n const editableName = isDefinition ? !state.capabilities.locked : editable;\n const canAddHere = canAddChildHere(node, state, isConditional);\n const showActions = editableName || canAddHere;\n\n const startRename = (e: React.MouseEvent) => {\n e.stopPropagation();\n // Branches and conditionals have no key to rename -- a branch's label is its\n // title (inspector); a conditional's label is derived from its `if`.\n if (editableName && !isBranch && !isConditional) setEditing(true);\n };\n\n const commitRename = (next: string) => {\n setEditing(false);\n if (isDefinition) state.renameDefinition(node.key, next);\n else state.renameProperty(node.path, next);\n };\n\n return (\n <>\n <div\n className={cn(\n \"group/row relative flex items-center gap-2 px-3 py-2 cursor-pointer\",\n selected && \"bg-accent\",\n )}\n style={{ paddingLeft: 12 + depth * 16 }}\n onClick={() => state.select(node.path)}\n >\n {editing ? (\n <NameEditor\n initial={node.key}\n onCommit={commitRename}\n onCancel={() => setEditing(false)}\n />\n ) : (\n <RowLabel\n node={node}\n editable={editableName}\n onStartRename={startRename}\n />\n )}\n {showActions && !editing && (\n // Absolutely positioned so the buttons do not reserve row width at\n // rest -- the name/type use the full row. The actions overlay the\n // right edge; each button reveals on hover via revealOnHover. The\n // background is applied only on hover so it does not cover the type\n // label at rest (accent for the selected row, background otherwise).\n <span\n className={cn(\n \"absolute right-2 flex gap-0.5 rounded-md pl-2\",\n selected\n ? \"group-hover/row:bg-accent\"\n : \"group-hover/row:bg-background\",\n )}\n >\n <RowActions\n node={node}\n state={state}\n editable={editableName}\n canAddHere={canAddHere}\n inUseDefs={inUseDefs}\n />\n </span>\n )}\n </div>\n {node.children.map((child) => (\n <PropertyRow\n key={pathKey(child.path)}\n node={child}\n state={state}\n depth={depth + 1}\n inUseDefs={inUseDefs}\n />\n ))}\n </>\n );\n}\n","/**\n * PreviewPane -- the center pane. Tabs: Form (live rendered form), JSON Schema\n * (the data model), and UI Schema (the presentation map). The form is the\n * universal sanity check; the two JSON views are read-only.\n *\n * Additional renderers (table, tree, detail) plug in as more tabs without\n * touching this contract -- each takes the same schema + uiSchema + data.\n */\n\nimport React, { useMemo, useState } from \"react\";\nimport {\n Tabs,\n TabsList,\n TabsTrigger,\n TabsContent,\n TabsSeparator,\n} from \"@petrarca/sonnet-ui\";\nimport { JsonSchemaFormRenderer } from \"@petrarca/sonnet-forms\";\nimport {\n extractSchemaDefaults,\n type JsonSchema,\n} from \"@petrarca/sonnet-core/schema\";\nimport { embedUiSchema } from \"../model/embed\";\nimport type { DesignerState } from \"../hooks/useDesignerState\";\nimport type { UiSchemaMap } from \"../model/mutate\";\nimport { TablePreview } from \"./TablePreview\";\nimport { FormLayoutDesigner } from \"../designers/FormLayoutDesigner\";\nimport { CapabilitiesPanel } from \"./CapabilitiesPanel\";\nimport { SchemaSourcePanel } from \"./SchemaSourcePanel\";\nimport type { SchemaDesignerCapabilities } from \"../capabilities\";\n\n// Validate a parsed value is a usable root JSON Schema.\nfunction validateRootSchema(parsed: unknown): string | null {\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n return \"Schema must be a JSON object.\";\n }\n const s = parsed as Record<string, unknown>;\n if (s.type !== \"object\") return 'Root schema must have type: \"object\".';\n if (typeof s.properties !== \"object\" || s.properties === null) {\n return \"Root schema must have a properties object.\";\n }\n return null;\n}\n\n// Validate a parsed value is a usable UI Schema map (object of entries).\nfunction validateUiSchema(parsed: unknown): string | null {\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n return \"UI Schema must be a JSON object.\";\n }\n return null;\n}\n\nexport interface PreviewPaneProps {\n state: DesignerState;\n /** The current (editable) capabilities profile. */\n capabilities?: SchemaDesignerCapabilities;\n /** Apply an edited profile (from the Capabilities tab). */\n onCapabilitiesChange?: (next: SchemaDesignerCapabilities) => void;\n}\n\ninterface TabFlags {\n isFull: boolean;\n showForm: boolean;\n showTable: boolean;\n showJson: boolean;\n showCapabilities: boolean;\n}\n\nfunction PreviewTabList({ flags }: { flags: TabFlags }): React.ReactElement {\n return (\n <TabsList className=\"mb-3\">\n {flags.showForm && <TabsTrigger value=\"form\">Form</TabsTrigger>}\n {flags.isFull && flags.showForm && (\n <TabsTrigger value=\"layout\">Form Layout</TabsTrigger>\n )}\n {flags.showTable && <TabsTrigger value=\"table\">Table</TabsTrigger>}\n <TabsSeparator />\n {flags.showJson && <TabsTrigger value=\"schema\">JSON Schema</TabsTrigger>}\n {flags.isFull && <TabsTrigger value=\"ui\">UI Schema</TabsTrigger>}\n {flags.isFull && <TabsTrigger value=\"combined\">Combined</TabsTrigger>}\n {flags.showCapabilities && (\n <>\n <TabsSeparator />\n <TabsTrigger value=\"capabilities\">Capabilities</TabsTrigger>\n </>\n )}\n </TabsList>\n );\n}\n\nexport function PreviewPane({\n state,\n capabilities,\n onCapabilitiesChange,\n}: PreviewPaneProps): React.ReactElement {\n const { schema, uiSchema } = state;\n const caps = state.capabilities;\n const flags: TabFlags = {\n isFull: caps.mode === \"full\",\n showForm: caps.previews.includes(\"form\"),\n showTable: caps.previews.includes(\"table\"),\n showJson: caps.previews.includes(\"json\"),\n showCapabilities: caps.showCapabilities,\n };\n\n const [data, setData] = useState<Record<string, unknown>>(() =>\n extractSchemaDefaults(schema),\n );\n\n const schemaText = useMemo(() => JSON.stringify(schema, null, 2), [schema]);\n const uiSchemaText = useMemo(\n () => JSON.stringify(uiSchema ?? {}, null, 2),\n [uiSchema],\n );\n const embeddedText = useMemo(\n () => JSON.stringify(embedUiSchema(schema, uiSchema ?? {}), null, 2),\n [schema, uiSchema],\n );\n\n // Default to the first available tab so it always resolves to something shown.\n const defaultTab = flags.showForm\n ? \"form\"\n : flags.showTable\n ? \"table\"\n : \"schema\";\n\n return (\n <Tabs defaultValue={defaultTab} className=\"flex flex-col h-full min-h-0\">\n <PreviewTabList flags={flags} />\n {flags.showForm && (\n <TabsContent value=\"form\" className=\"flex-1 min-h-0 overflow-auto\">\n <JsonSchemaFormRenderer\n schema={schema}\n data={data}\n uiSchema={uiSchema}\n onChange={setData}\n showActions={false}\n showExtraProperties={false}\n />\n </TabsContent>\n )}\n {flags.isFull && flags.showForm && (\n <TabsContent value=\"layout\" className=\"flex-1 min-h-0 overflow-hidden\">\n <FormLayoutDesigner state={state} />\n </TabsContent>\n )}\n {flags.showTable && (\n <TabsContent value=\"table\" className=\"flex-1 min-h-0 overflow-auto\">\n <TablePreview schema={schema} />\n </TabsContent>\n )}\n <SourceTabPanels\n state={state}\n flags={flags}\n schemaText={schemaText}\n uiSchemaText={uiSchemaText}\n embeddedText={embeddedText}\n capabilities={capabilities}\n onCapabilitiesChange={onCapabilitiesChange}\n />\n </Tabs>\n );\n}\n\n// The source-artifact panels (JSON Schema / UI Schema / Combined) plus the\n// optional Capabilities editor. Split out to keep PreviewPane's complexity low.\nfunction SourceTabPanels({\n state,\n flags,\n schemaText,\n uiSchemaText,\n embeddedText,\n capabilities,\n onCapabilitiesChange,\n}: {\n state: DesignerState;\n flags: TabFlags;\n schemaText: string;\n uiSchemaText: string;\n embeddedText: string;\n capabilities?: SchemaDesignerCapabilities;\n onCapabilitiesChange?: (next: SchemaDesignerCapabilities) => void;\n}): React.ReactElement {\n // Wholesale source replacement bypasses per-path scoping, so it is allowed\n // only when the profile is fully editable (neither locked nor scoped).\n const canEditSource =\n !state.capabilities.locked && !state.capabilities.scoped;\n\n return (\n <>\n {flags.showJson && (\n <TabsContent value=\"schema\" className=\"flex-1 min-h-0 relative\">\n <SchemaSourcePanel\n value={schemaText}\n editable={canEditSource}\n validate={validateRootSchema}\n onApply={(parsed) => state.replaceSchema(parsed as JsonSchema)}\n />\n </TabsContent>\n )}\n {flags.isFull && (\n <TabsContent value=\"ui\" className=\"flex-1 min-h-0 relative\">\n <SchemaSourcePanel\n value={uiSchemaText}\n editable={canEditSource}\n validate={validateUiSchema}\n onApply={(parsed) => state.replaceUiSchema(parsed as UiSchemaMap)}\n />\n </TabsContent>\n )}\n {flags.isFull && (\n <TabsContent value=\"combined\" className=\"flex-1 min-h-0 relative\">\n <SchemaSourcePanel\n value={embeddedText}\n editable={false}\n onApply={() => {}}\n />\n </TabsContent>\n )}\n {flags.showCapabilities && (\n <TabsContent value=\"capabilities\" className=\"flex-1 min-h-0 relative\">\n <CapabilitiesPanel\n capabilities={capabilities}\n onApply={onCapabilitiesChange}\n />\n </TabsContent>\n )}\n </>\n );\n}\n","/**\n * TablePreview -- renders the schema as an EntityTable using auto-generated\n * sample rows. Columns and cells come from the resolver's defaults plus any\n * x-ui-column / x-ui-cell hints embedded in the schema.\n */\n\nimport React, { useMemo } from \"react\";\nimport { EntityTable, type TableUiSchema } from \"@petrarca/sonnet-ui\";\nimport { toPageResult } from \"@petrarca/sonnet-core\";\nimport type { JsonSchema } from \"@petrarca/sonnet-core/schema\";\nimport { sampleRows } from \"./sampleRows\";\n\nexport interface TablePreviewProps {\n schema: JsonSchema;\n uiSchema?: TableUiSchema;\n}\n\nexport function TablePreview({\n schema,\n uiSchema,\n}: TablePreviewProps): React.ReactElement {\n const data = useMemo(() => toPageResult(sampleRows(schema)), [schema]);\n\n return (\n <EntityTable\n schema={schema}\n uiSchema={uiSchema}\n data={data}\n isLoading={false}\n isError={false}\n entityLabel=\"rows\"\n />\n );\n}\n","/**\n * Generate plausible sample rows from a JsonSchema, for the table preview.\n *\n * Pure. Produces a few rows with a value per top-level property, chosen by\n * type / format / enum so the table shows realistic content. Nested objects and\n * arrays get simple placeholders (tables typically show scalar columns; the\n * cell renderer decides how to display the rest).\n */\n\nimport type {\n JsonSchema,\n JsonSchemaProperty,\n} from \"@petrarca/sonnet-core/schema\";\n\ntype Row = Record<string, unknown>;\n\nfunction sampleString(\n prop: JsonSchemaProperty,\n key: string,\n i: number,\n): string {\n switch (prop.format) {\n case \"email\":\n return `user${i + 1}@example.com`;\n case \"date\":\n return `2024-0${(i % 9) + 1}-15`;\n case \"date-time\":\n return `2024-0${(i % 9) + 1}-15T09:30:00Z`;\n case \"uri\":\n case \"url\":\n return `https://example.com/${key}/${i + 1}`;\n case \"uuid\":\n return `00000000-0000-4000-8000-00000000000${i + 1}`;\n default:\n return `${titleCase(key)} ${i + 1}`;\n }\n}\n\nfunction titleCase(key: string): string {\n const s = key.replace(/[_-]+/g, \" \").trim();\n return s.charAt(0).toUpperCase() + s.slice(1);\n}\n\nfunction sampleValue(\n prop: JsonSchemaProperty,\n key: string,\n i: number,\n): unknown {\n if (Array.isArray(prop.enum) && prop.enum.length > 0) {\n return prop.enum[i % prop.enum.length];\n }\n switch (prop.type) {\n case \"string\":\n return sampleString(prop, key, i);\n case \"number\":\n return Math.round((i + 1) * 1.5 * 100) / 100;\n case \"integer\":\n return i + 1;\n case \"boolean\":\n return i % 2 === 0;\n case \"array\":\n return [];\n case \"object\":\n return {};\n default:\n return null;\n }\n}\n\n/** Build `count` sample rows for a schema's top-level properties. */\nexport function sampleRows(schema: JsonSchema, count = 3): Row[] {\n const entries = Object.entries(schema.properties);\n return Array.from({ length: count }, (_, i) => {\n const row: Row = {};\n for (const [key, prop] of entries) {\n row[key] = sampleValue(prop, key, i);\n }\n return row;\n });\n}\n","/**\n * FormLayoutDesigner -- visual editor for the form's row layout\n * (x-ui-layout.rows). Two columns: an \"Available\" pool of unassigned top-level\n * properties (left) and the row designer (right). Properties are dragged\n * (native HTML5 DnD) between the pool and rows; rows can be added, removed,\n * reordered, and given a CSS grid-template-columns value.\n *\n * This is a bespoke visual designer (not a meta-schema form) -- the first of a\n * planned family of \"*Designer\" surfaces for spatial authoring tasks.\n */\n\nimport React, { useMemo, useState } from \"react\";\nimport { cn } from \"@petrarca/sonnet-core\";\nimport { Input, IconButton, Button } from \"@petrarca/sonnet-ui\";\nimport { FormSelect, JsonSchemaFormRenderer } from \"@petrarca/sonnet-forms\";\nimport {\n Plus,\n Trash2,\n ChevronUp,\n ChevronDown,\n ChevronLeft,\n ChevronRight,\n GripVertical,\n} from \"lucide-react\";\nimport {\n buildLayoutMetaSchema,\n layoutToValues,\n valuesToLayout,\n type LayoutFormValues,\n} from \"../inspector/layoutMetaSchemas\";\nimport type {\n JsonSchema,\n JsonSchemaProperty,\n UILayoutConfig,\n UILayoutRowConfig,\n UILayoutGroupConfig,\n WidthToken,\n} from \"@petrarca/sonnet-core/schema\";\nimport type { DesignerState } from \"../hooks/useDesignerState\";\nimport { layoutScopes, type LayoutScope } from \"../model/view\";\nimport { RuleFields, type ScopeOption } from \"../inspector/RuleFields\";\nimport { VISIBILITY_EFFECT_OPTIONS } from \"../inspector/ruleEffects\";\nimport {\n getProperty,\n pathKey,\n parsePathKey,\n type PropertyPath,\n} from \"../model/paths\";\n\nexport interface FormLayoutDesignerProps {\n state: DesignerState;\n}\n\nconst DRAG_MIME = \"application/x-sonnet-property\";\n\n// Ordered keys of a properties map, honoring x-ui-order.\nfunction orderedKeysOf(\n properties: Record<string, JsonSchemaProperty>,\n order: string[] | undefined,\n): string[] {\n const keys = Object.keys(properties);\n if (!order || order.length === 0) return keys;\n const inOrder = order.filter((k) => k in properties);\n return [...inOrder, ...keys.filter((k) => !inOrder.includes(k))];\n}\n\n// Resolve a scope path to its editable keys + current rows. Root (path []) uses\n// the schema + uiSchema[\"x-ui-layout\"]; a property scope uses the object (or\n// array items) property and its x-ui-layout.\n// The container property for a scope path: the object, or an array's items.\nfunction scopeTarget(\n schema: JsonSchema,\n scopePath: PropertyPath,\n): JsonSchemaProperty | undefined {\n const prop = getProperty(schema, scopePath);\n if (!prop) return undefined;\n return prop.type === \"array\" ? prop.items : prop;\n}\n\ninterface ResolvedScope {\n keys: string[];\n /** The scope's properties, for the types a condition scope needs. */\n props: Record<string, JsonSchemaProperty>;\n rows: UILayoutRowConfig[];\n groups: UILayoutGroupConfig[];\n layout: UILayoutConfig | undefined;\n /** True when the scope is an array property (scalar options apply). */\n isArray: boolean;\n}\n\n// The container schema for a scope and the layout config attached to it.\n// Root reads the uiSchema; a nested scope reads the property (array -> items).\nfunction scopeContainer(\n schema: JsonSchema,\n uiSchema: DesignerState[\"uiSchema\"],\n scopePath: PropertyPath,\n): {\n container: JsonSchema | JsonSchemaProperty | undefined;\n layout: UILayoutConfig | undefined;\n} {\n if (scopePath.length === 0) {\n return {\n container: schema,\n layout: uiSchema[\"x-ui-layout\"] as UILayoutConfig | undefined,\n };\n }\n const container = scopeTarget(schema, scopePath);\n return {\n container,\n layout: container?.[\"x-ui-layout\"] as UILayoutConfig | undefined,\n };\n}\n\nfunction resolveScope(\n schema: JsonSchema,\n uiSchema: DesignerState[\"uiSchema\"],\n scopePath: PropertyPath,\n): ResolvedScope {\n const { container, layout } = scopeContainer(schema, uiSchema, scopePath);\n const props = container?.properties ?? {};\n return {\n keys: orderedKeysOf(props, container?.[\"x-ui-order\"]),\n props,\n rows: layout?.rows ?? [],\n groups: layout?.groups ?? [],\n layout,\n isArray: scopeIsArray(schema, scopePath),\n };\n}\n\n// The rows the designer is editing, plus every field already claimed by the\n// layout. `assigned` spans all groups so the Available pool stays correct no\n// matter which group is active.\n// Whether any of these rows already claims the property.\nfunction ownsField(rows: UILayoutRowConfig[], key: string): boolean {\n return rows.some((r) => r.fields.includes(key));\n}\n\nfunction rowTarget(\n grouped: boolean,\n groups: UILayoutGroupConfig[],\n groupIndex: number,\n flatRows: UILayoutRowConfig[],\n): { rows: UILayoutRowConfig[]; assigned: Set<string> } {\n const rows = grouped ? (groups[groupIndex]?.rows ?? []) : flatRows;\n const all = grouped ? groups.flatMap((t) => t.rows) : flatRows;\n return { rows, assigned: new Set(all.flatMap((r) => r.fields)) };\n}\n\n// Whether the scope path points at an array property.\nfunction scopeIsArray(schema: JsonSchema, scopePath: PropertyPath): boolean {\n if (scopePath.length === 0) return false;\n return getProperty(schema, scopePath)?.type === \"array\";\n}\n\n// Array item layout options (direction/gap/labels/compact), laid out on one\n// row via the renderer's own x-ui-layout so it matches form styling.\nconst SCALAR_META_SCHEMA = buildLayoutMetaSchema();\nconst SCALAR_UI_SCHEMA = {\n \"x-ui-layout\": {\n labelPlacement: \"start\" as const,\n // Flow row: controls sit left-to-right at their natural width (label hugs\n // control via horizontal labelPlacement), wrapping as needed.\n rows: [\n {\n fields: [\"direction\", \"gap\", \"labels\", \"compact\"],\n arrange: \"flow\" as const,\n gap: 16,\n },\n ],\n compact: true,\n },\n // Per-field widths for the toolbar. Top-level fields take their per-field\n // uiSchema directly under the field name. Direction (a select) gets more\n // room; the numeric Gap input stays narrow.\n direction: { \"x-ui-width\": \"lg\" as const },\n gap: { \"x-ui-width\": \"sm\" as const },\n};\n\nfunction scalarsFrom(\n values: LayoutFormValues,\n): Pick<UILayoutConfig, \"direction\" | \"gap\" | \"labels\" | \"compact\"> {\n const full = valuesToLayout(values, undefined) ?? {};\n return {\n direction: full.direction,\n gap: full.gap,\n labels: full.labels,\n compact: full.compact,\n };\n}\n\n// The array item layout options bar -- a horizontally-laid-out rendered form.\nfunction ArrayItemLayoutBar({\n layout,\n readOnly,\n onChange,\n}: {\n layout: UILayoutConfig | undefined;\n readOnly: boolean;\n onChange: (\n opts: Pick<UILayoutConfig, \"direction\" | \"gap\" | \"labels\" | \"compact\">,\n ) => void;\n}): React.ReactElement {\n return (\n <div className=\"shrink-0 rounded-lg border p-3\">\n <p className=\"heading-meta mb-2\">Array item layout</p>\n <JsonSchemaFormRenderer\n schema={SCALAR_META_SCHEMA}\n uiSchema={SCALAR_UI_SCHEMA}\n data={layoutToValues(layout) as unknown as Record<string, unknown>}\n onChange={(data) => onChange(scalarsFrom(data as LayoutFormValues))}\n showActions={false}\n showExtraProperties={false}\n readOnly={readOnly}\n />\n </div>\n );\n}\n\nexport function FormLayoutDesigner({\n state,\n}: FormLayoutDesignerProps): React.ReactElement {\n const scopes = useMemo(() => layoutScopes(state.schema), [state.schema]);\n const [scopePath, setScopePath] = useState<PropertyPath>([]);\n\n // Fall back to root if the selected scope no longer exists.\n const scopeKey = pathKey(scopePath);\n const activeScope =\n scopes.find((s) => pathKey(s.path) === scopeKey) ?? scopes[0];\n const effectivePath = activeScope.path;\n\n const {\n keys: allKeys,\n props: scopeProps,\n rows: flatRows,\n groups,\n layout,\n isArray,\n } = resolveScope(state.schema, state.uiSchema, effectivePath);\n\n // Groups mode is implied by the presence of group definitions.\n const grouped = groups.length > 0;\n const [activeGroup, setActiveGroup] = useState(0);\n // Clamp when groups shrink (or the scope changes) so the index stays valid.\n const groupIndex = grouped ? Math.min(activeGroup, groups.length - 1) : 0;\n\n // Every handler below works on this single array, in either mode.\n const { rows, assigned } = rowTarget(grouped, groups, groupIndex, flatRows);\n const available = allKeys.filter((k) => !assigned.has(k));\n // Properties held by a group other than the active one. They are offered in the\n // pool (marked) so a property can be moved between groups without first\n // navigating to the group that currently holds it.\n const inOtherGroups = grouped\n ? allKeys.filter((k) => assigned.has(k) && !ownsField(rows, k))\n : [];\n\n const [dragKey, setDragKey] = useState<string | null>(null);\n\n const commit = makeCommitRows(state, effectivePath, grouped, groupIndex);\n\n // Move a property into row `rowIndex` (or to the pool when rowIndex is null),\n // removing it from wherever it currently is. Empty rows are kept (they are\n // valid drop targets; the user removes rows explicitly).\n const place = (key: string, rowIndex: number | null) => {\n if (!key) return;\n // In groups mode a property may currently sit in a *different* group, so the\n // model op strips it across all groups before placing it here.\n if (grouped) {\n state.placeFieldInGroup(\n effectivePath,\n key,\n rowIndex === null ? null : { groupIndex, rowIndex },\n );\n return;\n }\n const next = rows.map((r) => ({\n ...r,\n fields: r.fields.filter((f) => f !== key),\n }));\n if (rowIndex !== null && next[rowIndex]) {\n next[rowIndex] = {\n ...next[rowIndex],\n fields: [...next[rowIndex].fields, key],\n };\n }\n commit(next);\n };\n\n const addRow = () => commit([...rows, { fields: [] }]);\n const removeRow = (i: number) => commit(rows.filter((_, idx) => idx !== i));\n const moveRow = (i: number, dir: -1 | 1) => {\n const j = i + dir;\n if (j < 0 || j >= rows.length) return;\n const next = [...rows];\n [next[i], next[j]] = [next[j], next[i]];\n commit(next);\n };\n const setColumns = (i: number, columns: string) => {\n const next = rows.map((r, idx) =>\n idx === i ? { ...r, columns: columns.trim() ? columns : undefined } : r,\n );\n commit(next);\n };\n const setGroup = (i: number, group: string) => {\n const next = rows.map((r, idx) =>\n idx === i ? { ...r, group: group.trim() ? group : undefined } : r,\n );\n commit(next);\n };\n const setArrange = (i: number, arrange: \"grid\" | \"flow\") => {\n const next: UILayoutRowConfig[] = rows.map((r, idx) =>\n // \"grid\" is the default -- omit it to keep the config clean.\n idx === i\n ? { ...r, arrange: arrange === \"flow\" ? (\"flow\" as const) : undefined }\n : r,\n );\n commit(next);\n };\n const setWidth = (i: number, cell: number, width: WidthToken) => {\n const next = rows.map((r, idx) => {\n if (idx !== i) return r;\n const widths = [...(r.widths ?? [])];\n while (widths.length < r.fields.length) widths.push(\"full\");\n widths[cell] = width;\n // Drop the array entirely when every cell is the default \"full\".\n const allFull = widths.every((w) => w === \"full\");\n return { ...r, widths: allFull ? undefined : widths };\n });\n commit(next);\n };\n\n // Condition scopes for a group rule: every property of this scope, with its\n // type so the comparand is written correctly (a boolean needs true, not \"true\").\n const scopeOptions = allKeys.map((k) => ({\n pointer: `/${k}`,\n type: scopeProps[k]?.type,\n }));\n\n const groupOps = makeGroupOps(\n state,\n effectivePath,\n groups.length,\n groupIndex,\n setActiveGroup,\n );\n const readOnly = state.readOnly;\n\n return (\n <div className=\"flex flex-col gap-3 h-full min-h-0\">\n <LayoutToolbar\n scopes={scopes}\n scopePath={effectivePath}\n onScope={setScopePath}\n grouped={grouped}\n variant={layout?.variant}\n readOnly={readOnly}\n onMode={groupOps.setMode}\n onVariant={(v) => state.setScopedLayoutVariant(effectivePath, v)}\n />\n\n {grouped && (\n <>\n <GroupBar\n groups={groups}\n activeIndex={groupIndex}\n readOnly={readOnly}\n onSelect={setActiveGroup}\n onAdd={groupOps.add}\n onRename={groupOps.rename}\n onRemove={groupOps.remove}\n onMove={groupOps.move}\n />\n <GroupSettings\n group={groups[groupIndex]}\n scopes={scopeOptions}\n readOnly={readOnly}\n onRule={(rule) =>\n state.setLayoutGroupRule(effectivePath, groupIndex, rule)\n }\n />\n </>\n )}\n\n {/* Array-only layout options in a single compact row. The renderer honors\n these only for array-of-object layout, so they show only when the\n scope is an array. */}\n {isArray && (\n <ArrayItemLayoutBar\n layout={layout}\n readOnly={readOnly}\n onChange={(opts) => state.setScopedLayoutOptions(effectivePath, opts)}\n />\n )}\n\n <div className=\"flex gap-4 flex-1 min-h-0\">\n <AvailablePool\n available={available}\n inOtherGroups={inOtherGroups}\n grouped={grouped}\n readOnly={readOnly}\n dragActive={!!dragKey}\n onDropToPool={(key) => place(key, null)}\n onDragStartKey={setDragKey}\n onDragEndKey={() => setDragKey(null)}\n />\n\n {/* Row designer */}\n <div className=\"flex-1 min-w-0 flex flex-col min-h-0\">\n <div className=\"mb-2 flex items-center gap-2\">\n <p className=\"heading-meta\">\n {rowsHeading(grouped, groups, groupIndex)}\n </p>\n {!readOnly && (\n <span className=\"ml-auto\">\n <Button\n size=\"sm\"\n variant=\"outline\"\n className=\"gap-1.5\"\n onClick={addRow}\n >\n <Plus className=\"h-4 w-4\" />\n Add row\n </Button>\n </span>\n )}\n </div>\n <div className=\"flex-1 min-h-0 overflow-auto space-y-3\">\n {rows.length === 0 ? (\n <p className=\"text-sm text-muted-foreground\">\n No rows yet. Add a row, then drag properties into it.\n </p>\n ) : (\n rows.map((row, i) => (\n <RowCard\n key={i}\n row={row}\n index={i}\n total={rows.length}\n readOnly={readOnly}\n dragActive={!!dragKey}\n onDropKey={(key) => place(key ?? dragKey ?? \"\", i)}\n onRemoveKey={(key) => place(key, null)}\n onDragStartKey={(key) => setDragKey(key)}\n onDragEndKey={() => setDragKey(null)}\n onMoveUp={() => moveRow(i, -1)}\n onMoveDown={() => moveRow(i, 1)}\n onDelete={() => removeRow(i)}\n onColumns={(v) => setColumns(i, v)}\n onGroup={(v) => setGroup(i, v)}\n onWidth={(cell, w) => setWidth(i, cell, w)}\n onArrange={(a) => setArrange(i, a)}\n />\n ))\n )}\n </div>\n </div>\n </div>\n </div>\n );\n}\n\n// Row writes go to the active group in groups mode, or the scope's flat list.\nfunction makeCommitRows(\n state: DesignerState,\n scopePath: PropertyPath,\n grouped: boolean,\n groupIndex: number,\n): (rows: UILayoutRowConfig[]) => void {\n if (grouped) {\n return (rows) => state.setScopedGroupRows(scopePath, groupIndex, rows);\n }\n return (rows) => state.setScopedLayoutRows(scopePath, rows);\n}\n\n// Heading for the row editor, naming the group being edited in groups mode.\nfunction rowsHeading(\n grouped: boolean,\n groups: UILayoutGroupConfig[],\n groupIndex: number,\n): string {\n if (!grouped) return \"Rows\";\n return `Rows in ${groups[groupIndex]?.label ?? \"\"}`;\n}\n\n// The group presentations offered by the designer. The renderer resolves any\n// variant to a template, so a consumer's custom presentation is authored in\n// the UI Schema source tab rather than listed here.\nconst VARIANT_OPTIONS = [\n { value: \"tabs\", label: \"Tabs\" },\n { value: \"stepper\", label: \"Stepper\" },\n { value: \"sections\", label: \"Sections\" },\n];\n\ninterface GroupOps {\n add: () => void;\n rename: (index: number, label: string) => void;\n remove: (index: number) => void;\n move: (index: number, direction: -1 | 1) => void;\n setMode: (mode: \"rows\" | \"groups\") => void;\n}\n\n// Tab-level operations: the model owns the semantics (see mutate.ts); this only\n// keeps the active index pointing somewhere sensible afterwards.\nfunction makeGroupOps(\n state: DesignerState,\n scopePath: PropertyPath,\n groupCount: number,\n activeIndex: number,\n setActiveGroup: React.Dispatch<React.SetStateAction<number>>,\n): GroupOps {\n return {\n add: () => {\n state.addLayoutGroup(scopePath);\n setActiveGroup(groupCount);\n },\n rename: (index, label) => state.renameLayoutGroup(scopePath, index, label),\n move: (index, direction) => {\n state.moveLayoutGroup(scopePath, index, direction);\n // Follow the group that moved, so the row editor keeps showing it.\n if (index === activeIndex) setActiveGroup(activeIndex + direction);\n },\n remove: (index) => {\n state.removeLayoutGroup(scopePath, index);\n // Clamp from the effective index, not raw state, so a stale-high value\n // (after a scope switch) cannot land on the wrong group.\n if (index <= activeIndex && activeIndex > 0)\n setActiveGroup(activeIndex - 1);\n },\n setMode: (mode) => {\n state.setScopedLayoutMode(scopePath, mode);\n setActiveGroup(0);\n },\n };\n}\n\n// The pool of properties not placed in the active rows. In groups mode it also\n// lists properties held by other groups, so one can be moved across without\n// first navigating to the group that owns it.\nfunction AvailablePool({\n available,\n inOtherGroups,\n grouped,\n readOnly,\n dragActive,\n onDropToPool,\n onDragStartKey,\n onDragEndKey,\n}: {\n available: string[];\n inOtherGroups: string[];\n grouped: boolean;\n readOnly: boolean;\n dragActive: boolean;\n onDropToPool: (key: string) => void;\n onDragStartKey: (key: string) => void;\n onDragEndKey: () => void;\n}): React.ReactElement {\n const empty = available.length === 0 && inOtherGroups.length === 0;\n return (\n <div className=\"w-56 shrink-0 flex flex-col min-h-0\">\n <p className=\"heading-meta mb-2\">Available</p>\n <div\n className=\"flex-1 min-h-0 overflow-auto rounded-lg border p-2 space-y-1 bg-muted/20\"\n onDragOver={(e) => {\n if (dragActive) e.preventDefault();\n }}\n onDrop={(e) => {\n const key = e.dataTransfer.getData(DRAG_MIME);\n if (key) onDropToPool(key);\n }}\n >\n {empty ? (\n <p className=\"text-xs text-muted-foreground p-1\">\n {grouped\n ? \"All properties are placed in groups.\"\n : \"All properties are placed in rows.\"}\n </p>\n ) : (\n available.map((key) => (\n <Chip\n key={key}\n label={key}\n readOnly={readOnly}\n onDragStart={() => onDragStartKey(key)}\n onDragEnd={onDragEndKey}\n />\n ))\n )}\n {inOtherGroups.length > 0 && (\n <>\n <p className=\"pt-2 pb-1 text-[11px] uppercase tracking-wide text-muted-foreground/70\">\n In other groups\n </p>\n {inOtherGroups.map((key) => (\n <Chip\n key={key}\n label={key}\n readOnly={readOnly}\n muted\n onDragStart={() => onDragStartKey(key)}\n onDragEnd={onDragEndKey}\n />\n ))}\n </>\n )}\n </div>\n <p className=\"text-xs text-muted-foreground mt-2\">\n {grouped\n ? \"Drag from \\u201cIn other groups\\u201d to move a property here. Unplaced properties render below the groups.\"\n : \"Unplaced properties render stacked below the rows.\"}\n </p>\n </div>\n );\n}\n\n// Scope selector plus the grouping controls (rows/groups and, when grouped, the\n// presentation variant).\nfunction LayoutToolbar({\n scopes,\n scopePath,\n onScope,\n grouped,\n variant,\n readOnly,\n onMode,\n onVariant,\n}: {\n scopes: LayoutScope[];\n scopePath: PropertyPath;\n onScope: (path: PropertyPath) => void;\n grouped: boolean;\n variant: UILayoutConfig[\"variant\"];\n readOnly: boolean;\n onMode: (mode: \"rows\" | \"groups\") => void;\n onVariant: (variant: UILayoutConfig[\"variant\"]) => void;\n}): React.ReactElement {\n return (\n <div className=\"flex items-center gap-2 shrink-0\">\n <label className=\"heading-meta\">Scope</label>\n <div className=\"w-64\">\n <FormSelect\n id=\"layout-scope\"\n name=\"scope\"\n value={pathKey(scopePath)}\n options={scopes.map((s) => ({\n value: pathKey(s.path),\n label: s.label,\n }))}\n onChange={(v: string | null) => onScope(v ? parsePathKey(v) : [])}\n clearable={false}\n />\n </div>\n <label className=\"heading-meta ml-4\">Group by</label>\n <ModeToggle\n mode={grouped ? \"groups\" : \"rows\"}\n readOnly={readOnly}\n onChange={onMode}\n />\n {grouped && (\n <>\n <label className=\"heading-meta ml-4\">Show as</label>\n <div className=\"w-36\">\n <FormSelect\n id=\"layout-variant\"\n name=\"variant\"\n value={variant ?? \"tabs\"}\n options={VARIANT_OPTIONS}\n onChange={(v) =>\n onVariant((v as UILayoutConfig[\"variant\"]) ?? \"tabs\")\n }\n clearable={false}\n disabled={readOnly}\n />\n </div>\n </>\n )}\n </div>\n );\n}\n\n// Rows / Tabs switch. Tabs group rows under labels; the data stays flat.\nfunction ModeToggle({\n mode,\n readOnly,\n onChange,\n}: {\n mode: \"rows\" | \"groups\";\n readOnly: boolean;\n onChange: (mode: \"rows\" | \"groups\") => void;\n}): React.ReactElement {\n return (\n <div className=\"inline-flex rounded-md border p-0.5\" aria-label=\"Group by\">\n {([\"rows\", \"groups\"] as const).map((m) => (\n <button\n key={m}\n type=\"button\"\n disabled={readOnly}\n // aria-pressed carries the active state; the visual highlight alone\n // would not reach assistive tech.\n aria-pressed={mode === m}\n onClick={() => onChange(m)}\n className={cn(\n \"rounded px-2 py-0.5 text-xs capitalize disabled:opacity-50\",\n mode === m\n ? \"bg-accent text-accent-foreground font-medium\"\n : \"text-muted-foreground hover:text-foreground\",\n )}\n >\n {m}\n </button>\n ))}\n </div>\n );\n}\n\n/**\n * Per-group settings for the active group. Currently its show/hide rule, which\n * makes a whole group conditional on another field's value -- the same\n * declarative mechanism as a field's x-ui-rule, so it reuses that editor.\n */\nfunction GroupSettings({\n group,\n scopes,\n readOnly,\n onRule,\n}: {\n group: UILayoutGroupConfig | undefined;\n scopes: ScopeOption[];\n readOnly: boolean;\n onRule: (rule: UILayoutGroupConfig[\"rule\"]) => void;\n}): React.ReactElement | null {\n const [open, setOpen] = useState(false);\n if (!group) return null;\n const hasRule = !!group.rule;\n return (\n <div className=\"shrink-0 rounded-lg border px-3 py-2\">\n <button\n type=\"button\"\n className=\"flex w-full items-center gap-1 heading-meta\"\n onClick={() => setOpen((v) => !v)}\n aria-expanded={open}\n >\n {open ? (\n <ChevronDown className=\"h-3 w-3\" />\n ) : (\n <ChevronRight className=\"h-3 w-3\" />\n )}\n Visibility of {group.label}\n <span className=\"ml-1 normal-case text-muted-foreground/70\">\n {hasRule ? \"conditional\" : \"always shown\"}\n </span>\n </button>\n {open && (\n <div className=\"mt-3 max-w-sm\">\n <RuleFields\n rule={group.rule}\n scopes={scopes}\n effects={VISIBILITY_EFFECT_OPTIONS}\n idPrefix=\"group-rule\"\n disabled={readOnly}\n onChange={(rule) =>\n onRule(rule as UILayoutGroupConfig[\"rule\"] | undefined)\n }\n />\n </div>\n )}\n </div>\n );\n}\n\n// The group strip: select a group to edit its rows, rename inline, add or remove.\nfunction GroupBar({\n groups,\n activeIndex,\n readOnly,\n onSelect,\n onAdd,\n onRename,\n onRemove,\n onMove,\n}: {\n groups: UILayoutGroupConfig[];\n activeIndex: number;\n readOnly: boolean;\n onSelect: (index: number) => void;\n onAdd: () => void;\n onRename: (index: number, label: string) => void;\n onRemove: (index: number) => void;\n onMove: (index: number, direction: -1 | 1) => void;\n}): React.ReactElement {\n return (\n <div\n role=\"tablist\"\n aria-label=\"Layout groups\"\n className=\"shrink-0 flex items-center gap-1 rounded-lg border p-1.5 overflow-x-auto\"\n >\n {groups.map((group, i) => (\n <GroupChip\n // Index alone would re-target GroupChip's in-flight rename state at a\n // different group when one is removed; include the label so identity\n // changes reset it.\n key={`${i}:${group.label}`}\n group={group}\n active={i === activeIndex}\n readOnly={readOnly}\n onSelect={() => onSelect(i)}\n onRename={(label) => onRename(i, label)}\n onRemove={() => onRemove(i)}\n onMoveLeft={i > 0 ? () => onMove(i, -1) : undefined}\n onMoveRight={i < groups.length - 1 ? () => onMove(i, 1) : undefined}\n />\n ))}\n {!readOnly && (\n <Button\n size=\"sm\"\n variant=\"outline\"\n className=\"gap-1.5 shrink-0\"\n onClick={onAdd}\n >\n <Plus className=\"h-4 w-4\" />\n Add group\n </Button>\n )}\n </div>\n );\n}\n\n// One group in the strip. Double-click the label to rename it.\nfunction GroupChip({\n group,\n active,\n readOnly,\n onSelect,\n onRename,\n onRemove,\n onMoveLeft,\n onMoveRight,\n}: {\n group: UILayoutGroupConfig;\n active: boolean;\n readOnly: boolean;\n onSelect: () => void;\n onRename: (label: string) => void;\n onRemove: () => void;\n onMoveLeft?: () => void;\n onMoveRight?: () => void;\n}): React.ReactElement {\n const [editing, setEditing] = useState(false);\n if (editing) {\n return (\n <Input\n autoFocus\n defaultValue={group.label}\n className=\"h-7 w-32 text-sm\"\n onBlur={(e) => {\n const next = e.target.value.trim();\n if (next && next !== group.label) onRename(next);\n setEditing(false);\n }}\n onKeyDown={(e) => {\n if (e.key === \"Enter\") e.currentTarget.blur();\n if (e.key === \"Escape\") setEditing(false);\n }}\n />\n );\n }\n const fieldCount = group.rows.reduce((n, r) => n + r.fields.length, 0);\n return (\n <span\n className={cn(\n \"group/group inline-flex shrink-0 items-center gap-1 rounded-md border pl-2 pr-1 py-0.5 text-sm\",\n active ? \"bg-accent border-accent-foreground/20\" : \"hover:bg-muted\",\n )}\n >\n {/* A real button so the strip is keyboard reachable; F2 renames, matching\n the platform convention (double-click also works with a mouse). */}\n <button\n type=\"button\"\n role=\"group\"\n aria-selected={active}\n className=\"inline-flex items-center gap-1 py-0.5\"\n onClick={onSelect}\n onDoubleClick={() => !readOnly && setEditing(true)}\n onKeyDown={(e) => {\n if (e.key === \"F2\" && !readOnly) {\n e.preventDefault();\n setEditing(true);\n }\n }}\n title={readOnly ? group.label : `${group.label} -- F2 to rename`}\n >\n {group.label}\n <span className=\"text-xs text-muted-foreground\">{fieldCount}</span>\n </button>\n {!readOnly && (\n <span className=\"flex items-center opacity-0 group-hover/group:opacity-100 focus-within:opacity-100\">\n {onMoveLeft && (\n <IconButton\n label={`Move ${group.label} left`}\n revealOnHover\n onClick={onMoveLeft}\n >\n <ChevronLeft />\n </IconButton>\n )}\n {onMoveRight && (\n <IconButton\n label={`Move ${group.label} right`}\n revealOnHover\n onClick={onMoveRight}\n >\n <ChevronRight />\n </IconButton>\n )}\n <IconButton\n label={`Remove ${group.label}`}\n tone=\"destructive\"\n revealOnHover\n onClick={onRemove}\n >\n <Trash2 />\n </IconButton>\n </span>\n )}\n </span>\n );\n}\n\nconst WIDTH_LABELS: Record<WidthToken, string> = {\n full: \"Full\",\n sm: \"Small\",\n md: \"Medium\",\n lg: \"Large\",\n};\n\n// Compact single-letter labels for the inline per-property width selector.\nconst WIDTH_SHORT: Record<WidthToken, string> = {\n full: \"F\",\n sm: \"S\",\n md: \"M\",\n lg: \"L\",\n};\n\nfunction Chip({\n label,\n readOnly,\n onRemove,\n onDragStart,\n onDragEnd,\n width,\n onWidth,\n widthDisabled,\n muted = false,\n}: {\n label: string;\n readOnly: boolean;\n onRemove?: () => void;\n onDragStart: () => void;\n onDragEnd: () => void;\n /** Dimmed styling for a property that currently belongs to another group. */\n muted?: boolean;\n // When provided, the chip shows an inline width selector (row members only).\n width?: WidthToken;\n onWidth?: (width: WidthToken) => void;\n widthDisabled?: boolean;\n}): React.ReactElement {\n return (\n <div\n draggable={!readOnly}\n onDragStart={(e) => {\n e.dataTransfer.setData(DRAG_MIME, label);\n e.dataTransfer.effectAllowed = \"move\";\n onDragStart();\n }}\n onDragEnd={onDragEnd}\n className={cn(\n \"group/chip flex items-center gap-1 rounded-md border bg-background px-2 py-1 text-sm cursor-grab active:cursor-grabbing\",\n muted && \"border-dashed text-muted-foreground\",\n )}\n >\n <GripVertical className=\"h-3.5 w-3.5 text-muted-foreground/60 shrink-0\" />\n <span className=\"truncate\">{label}</span>\n {onWidth && (\n <select\n value={width ?? \"full\"}\n onChange={(e) => onWidth(e.target.value as WidthToken)}\n disabled={readOnly || widthDisabled}\n title={\n widthDisabled ? \"Overridden by raw CSS columns\" : \"Column width\"\n }\n className=\"h-6 rounded border bg-background px-1 text-xs text-muted-foreground disabled:opacity-50\"\n >\n {([\"full\", \"sm\", \"md\", \"lg\"] as WidthToken[]).map((w) => (\n <option key={w} value={w} title={WIDTH_LABELS[w]}>\n {WIDTH_SHORT[w]}\n </option>\n ))}\n </select>\n )}\n {onRemove && !readOnly && (\n <IconButton label=\"Remove from row\" onClick={onRemove}>\n <Trash2 />\n </IconButton>\n )}\n </div>\n );\n}\n\nfunction RowCard({\n row,\n index,\n total,\n readOnly,\n dragActive,\n onDropKey,\n onRemoveKey,\n onDragStartKey,\n onDragEndKey,\n onMoveUp,\n onMoveDown,\n onDelete,\n onColumns,\n onGroup,\n onWidth,\n onArrange,\n}: {\n row: UILayoutRowConfig;\n index: number;\n total: number;\n readOnly: boolean;\n dragActive: boolean;\n onDropKey: (key: string | null) => void;\n onRemoveKey: (key: string) => void;\n onDragStartKey: (key: string) => void;\n onDragEndKey: () => void;\n onMoveUp: () => void;\n onMoveDown: () => void;\n onDelete: () => void;\n onColumns: (v: string) => void;\n onGroup: (v: string) => void;\n onWidth: (cell: number, width: WidthToken) => void;\n onArrange: (arrange: \"grid\" | \"flow\") => void;\n}): React.ReactElement {\n const [over, setOver] = useState(false);\n const isFlow = row.arrange === \"flow\";\n return (\n <div className=\"rounded-lg border p-3\">\n <div className=\"flex items-center gap-2 mb-2\">\n <span className=\"heading-meta\">Row {index + 1}</span>\n {!readOnly && (\n <span className=\"ml-auto flex gap-0.5\">\n <IconButton\n label=\"Move row up\"\n disabled={index === 0}\n onClick={onMoveUp}\n >\n <ChevronUp />\n </IconButton>\n <IconButton\n label=\"Move row down\"\n disabled={index === total - 1}\n onClick={onMoveDown}\n >\n <ChevronDown />\n </IconButton>\n <IconButton\n label=\"Delete row\"\n tone=\"destructive\"\n onClick={onDelete}\n >\n <Trash2 />\n </IconButton>\n </span>\n )}\n </div>\n\n <div className=\"mb-2 flex items-center gap-2\">\n <label className=\"text-xs text-muted-foreground w-16\">Group</label>\n <Input\n value={row.group ?? \"\"}\n onChange={(e) => onGroup(e.target.value)}\n placeholder=\"Section title (optional)\"\n disabled={readOnly}\n className=\"h-7 text-sm flex-1\"\n />\n </div>\n\n <div className=\"mb-2 flex items-center gap-2\">\n <label className=\"text-xs text-muted-foreground w-16\">Arrange</label>\n <select\n value={isFlow ? \"flow\" : \"grid\"}\n onChange={(e) => onArrange(e.target.value as \"grid\" | \"flow\")}\n disabled={readOnly}\n title=\"Grid: sized columns. Inline: fields at natural width, wrapping.\"\n className=\"h-7 rounded-md border bg-background px-2 text-sm text-foreground disabled:opacity-50\"\n >\n <option value=\"grid\">Grid (columns)</option>\n <option value=\"flow\">Inline (natural width)</option>\n </select>\n </div>\n\n <div\n className={`min-h-10 rounded-md border border-dashed p-2 flex flex-wrap gap-1 ${\n over && dragActive ? \"border-primary bg-accent\" : \"border-border\"\n }`}\n onDragOver={(e) => {\n if (dragActive) {\n e.preventDefault();\n setOver(true);\n }\n }}\n onDragLeave={() => setOver(false)}\n onDrop={(e) => {\n setOver(false);\n onDropKey(e.dataTransfer.getData(DRAG_MIME) || null);\n }}\n >\n {row.fields.length === 0 ? (\n <span className=\"text-xs text-muted-foreground p-1\">\n Drop properties here\n </span>\n ) : (\n row.fields.map((key, cell) => (\n <Chip\n key={key}\n label={key}\n readOnly={readOnly}\n onRemove={() => onRemoveKey(key)}\n onDragStart={() => onDragStartKey(key)}\n onDragEnd={onDragEndKey}\n width={row.widths?.[cell] ?? \"full\"}\n onWidth={isFlow ? undefined : (w) => onWidth(cell, w)}\n widthDisabled={!!row.columns}\n />\n ))\n )}\n </div>\n\n {/* Advanced: raw CSS grid columns. Grid mode only -- ignored in flow. */}\n {!isFlow && (\n <details className=\"mt-2\">\n <summary className=\"cursor-pointer text-xs text-muted-foreground\">\n Advanced: raw CSS columns\n </summary>\n <div className=\"mt-2 flex items-center gap-2\">\n <label className=\"text-xs text-muted-foreground w-16\">\n Columns\n </label>\n <Input\n value={row.columns ?? \"\"}\n onChange={(e) => onColumns(e.target.value)}\n placeholder=\"e.g. 1fr 1fr\"\n disabled={readOnly}\n className=\"h-7 text-sm flex-1\"\n />\n </div>\n <p className=\"mt-1 pl-[4.5rem] text-xs text-muted-foreground\">\n Raw <span className=\"font-mono\">grid-template-columns</span>. When\n set, it overrides the per-property widths. Blank = use widths.\n </p>\n </details>\n )}\n </div>\n );\n}\n","/**\n * RuleFields -- the presentational editor for a declarative UIRule\n * (effect + scope + operator + value).\n *\n * Purely controlled: it owns the incomplete-draft state that authoring passes\n * through (an effect chosen before a field cannot yet be a valid rule) and\n * calls `onChange` only once the rule is complete or fully cleared.\n *\n * Shared by the field-level rule editor (x-ui-rule on a property) and the\n * layout tab rule editor, which differ only in where the rule is stored and\n * which effects make sense.\n */\n\nimport React, { useEffect, useMemo, useState } from \"react\";\nimport { FormSelect } from \"@petrarca/sonnet-forms\";\nimport type { UIRule, UIRuleEffect } from \"@petrarca/sonnet-core/schema\";\nimport {\n OPERATOR_OPTIONS,\n operatorToConstraint,\n constraintToOperator,\n type ConditionOperator,\n type ScopeType,\n} from \"../model/conditions\";\nimport { OperatorValueInput } from \"./OperatorValueInput\";\nimport type { EffectOption } from \"./ruleEffects\";\n\n// A rule broken into the flat fields the form edits.\ninterface RuleForm {\n effect: \"\" | UIRuleEffect;\n scope: string;\n operator: ConditionOperator;\n value: string;\n}\n\nfunction ruleToForm(rule: UIRule | undefined): RuleForm {\n if (!rule) return { effect: \"\", scope: \"\", operator: \"=\", value: \"\" };\n const { operator, value } = constraintToOperator(rule.condition.schema);\n return { effect: rule.effect, scope: rule.condition.scope, operator, value };\n}\n\nfunction formToRule(form: RuleForm, scopeType: ScopeType): UIRule | undefined {\n if (!form.effect || !form.scope) return undefined;\n return {\n effect: form.effect,\n condition: {\n scope: form.scope,\n schema: operatorToConstraint(form.operator, form.value, scopeType),\n },\n };\n}\n\n/** True/false choices for a boolean scope; a text box cannot express them. */\nconst BOOLEAN_VALUE_OPTIONS = [\n { value: \"true\", label: \"true\" },\n { value: \"false\", label: \"false\" },\n];\n\n/** A field offered as the condition scope, with the type it holds. */\nexport interface ScopeOption {\n /** JSON Pointer into the form data, e.g. \"/gender\". */\n pointer: string;\n /** The field's declared type, used to write a correctly-typed comparand. */\n type?: ScopeType;\n}\n\nexport interface RuleFieldsProps {\n /** The stored rule, or undefined when there is none. */\n rule: UIRule | undefined;\n /** Fields offered as the condition scope. */\n scopes: ScopeOption[];\n /** Which effects to offer. */\n effects: EffectOption[];\n /** Unique prefix for the field ids (several editors can coexist). */\n idPrefix: string;\n disabled?: boolean;\n /** Called with a complete rule, or undefined when the rule is cleared. */\n onChange: (rule: UIRule | undefined) => void;\n}\n\nexport function RuleFields({\n rule,\n scopes,\n effects,\n idPrefix,\n disabled = false,\n onChange,\n}: RuleFieldsProps): React.ReactElement {\n const [form, setForm] = useState<RuleForm>(() => ruleToForm(rule));\n\n // Re-seed the draft when the stored rule changes externally (e.g. via the\n // JSON source tab). The serialized rule is the sole dependency, so this does\n // not fire on unrelated re-renders.\n const seed = JSON.stringify(rule ?? null);\n useEffect(() => {\n setForm(ruleToForm((JSON.parse(seed) as UIRule | null) ?? undefined));\n }, [seed]);\n\n // The declared type of the selected scope, so the comparand is written with\n // the type the form data actually carries (a boolean field needs `true`, not\n // the string \"true\", or the rule can never match).\n const scopeType = useMemo(\n () => scopes.find((s) => s.pointer === form.scope)?.type,\n [scopes, form.scope],\n );\n\n const commit = (next: RuleForm): void => {\n setForm(next);\n const nextType = scopes.find((s) => s.pointer === next.scope)?.type;\n const built = formToRule(next, nextType);\n // Write when complete, or clear when the effect was removed. Incomplete\n // drafts (effect set, no field yet) stay local until completed.\n if (built || next.effect === \"\") onChange(built);\n };\n\n const scopeOptions = useMemo(\n () => scopes.map((s) => ({ value: s.pointer, label: s.pointer.slice(1) })),\n [scopes],\n );\n const needsValue = form.operator !== \"exists\";\n const isBoolean = scopeType === \"boolean\";\n\n return (\n <div className=\"space-y-3\">\n <FormSelect\n id={`${idPrefix}-effect`}\n name=\"effect\"\n label=\"Effect\"\n options={effects}\n value={form.effect}\n onChange={(v) => commit({ ...form, effect: (v as UIRuleEffect) ?? \"\" })}\n clearable={false}\n disabled={disabled}\n />\n {form.effect !== \"\" && (\n <>\n <FormSelect\n id={`${idPrefix}-scope`}\n name=\"scope\"\n label=\"When field\"\n options={scopeOptions}\n value={form.scope || null}\n onChange={(v) => commit({ ...form, scope: v ?? \"\" })}\n placeholder=\"Select a field...\"\n clearable={false}\n disabled={disabled}\n />\n <FormSelect\n id={`${idPrefix}-operator`}\n name=\"operator\"\n label=\"Operator\"\n options={OPERATOR_OPTIONS}\n value={form.operator}\n onChange={(v) =>\n commit({ ...form, operator: (v as ConditionOperator) ?? \"=\" })\n }\n clearable={false}\n disabled={disabled}\n />\n {needsValue &&\n (isBoolean ? (\n <FormSelect\n id={`${idPrefix}-value`}\n name=\"value\"\n label=\"Value\"\n options={BOOLEAN_VALUE_OPTIONS}\n value={form.value === \"true\" ? \"true\" : \"false\"}\n onChange={(v) => commit({ ...form, value: v ?? \"false\" })}\n clearable={false}\n disabled={disabled || !form.scope}\n />\n ) : (\n <OperatorValueInput\n id={`${idPrefix}-value`}\n cacheKey={`${form.scope}:${form.operator}`}\n value={form.value}\n onCommit={(v) => commit({ ...form, value: v })}\n disabled={disabled || !form.scope}\n />\n ))}\n </>\n )}\n </div>\n );\n}\n","/**\n * Condition builder: the bridge between a friendly (property, operator, value)\n * triple and the JSON Schema `if` sub-schema the renderer evaluates.\n *\n * An `if` tests a sibling property. Operators map to standard schema keywords\n * (mirrors the FHIR operator table in fhir-questionnaire-adapter.md 7.1):\n *\n * = -> { properties: { field: { const: value } }, required: [field] }\n * != -> { properties: { field: { not: { const: value } } }, required: [field] }\n * > >= < <= -> exclusiveMinimum / minimum / exclusiveMaximum / maximum\n * exists -> { required: [field] }\n *\n * A value operator always adds `required: [field]` so an absent field does not\n * vacuously satisfy the condition.\n */\n\nimport type { JsonSchemaProperty } from \"@petrarca/sonnet-core/schema\";\n\nexport type ConditionOperator = \"=\" | \"!=\" | \">\" | \">=\" | \"<\" | \"<=\" | \"exists\";\n\nexport const CONDITION_OPERATORS: readonly ConditionOperator[] = [\n \"=\",\n \"!=\",\n \">\",\n \">=\",\n \"<\",\n \"<=\",\n \"exists\",\n];\n\n/** Human labels for the operator dropdown. */\nexport const CONDITION_OPERATOR_LABELS: Record<ConditionOperator, string> = {\n \"=\": \"equals\",\n \"!=\": \"not equals\",\n \">\": \"greater than\",\n \">=\": \"greater or equal\",\n \"<\": \"less than\",\n \"<=\": \"less or equal\",\n exists: \"exists\",\n};\n\n/** Shared select-option list for the operator dropdown (ConditionEditor + RuleEditor). */\nexport const OPERATOR_OPTIONS: { value: ConditionOperator; label: string }[] =\n CONDITION_OPERATORS.map((op) => ({\n value: op,\n label: CONDITION_OPERATOR_LABELS[op],\n }));\n\n/** A condition as edited in the inspector. */\nexport interface Condition {\n field: string;\n operator: ConditionOperator;\n /** Raw string value from the inspector; coerced to number where numeric. */\n value: string;\n}\n\n// Numeric operators need a numeric comparand.\nconst NUMERIC_OPS: ReadonlySet<ConditionOperator> = new Set([\n \">\",\n \">=\",\n \"<\",\n \"<=\",\n]);\n\n/** The JSON Schema type of the field a condition targets, when known. */\nexport type ScopeType = JsonSchemaProperty[\"type\"];\n\n// Coerce a string value to number when it is a finite numeric literal.\nfunction coerceValue(value: string): string | number {\n if (value.trim() === \"\") return value;\n const n = Number(value);\n return Number.isFinite(n) ? n : value;\n}\n\n/**\n * Coerce the editor's string value to the type the target field actually\n * holds. Without this a boolean field compared with the *string* \"true\" can\n * never match the boolean `true` the form produces -- the rule would be\n * authorable but silently dead.\n *\n * Numeric operators always compare numerically, whatever the declared type.\n */\nfunction coerceForScope(\n value: string,\n operator: ConditionOperator,\n type: ScopeType,\n): string | number | boolean {\n if (NUMERIC_OPS.has(operator)) return coerceValue(value);\n if (type === \"boolean\") return value === \"true\";\n if (type === \"number\" || type === \"integer\") return coerceValue(value);\n return value;\n}\n\n/**\n * The per-value constraint schema for an operator + value (e.g. \"=\" + \"female\"\n * -> { const: \"female\" }). This is the value-level building block shared by the\n * conditional `if` builder and the x-ui-rule builder. `exists` yields an empty\n * schema (presence is expressed by `required` at the caller).\n *\n * Pass the target field's `type` so the comparand is written with the type the\n * form data actually carries.\n */\nexport function operatorToConstraint(\n operator: ConditionOperator,\n value: string,\n type?: ScopeType,\n): JsonSchemaProperty {\n const v = coerceForScope(value, operator, type);\n switch (operator) {\n case \"=\":\n return { const: v };\n case \"!=\":\n return { not: { const: v } };\n case \">\":\n return { exclusiveMinimum: v as number };\n case \">=\":\n return { minimum: v as number };\n case \"<\":\n return { exclusiveMaximum: v as number };\n case \"<=\":\n return { maximum: v as number };\n case \"exists\":\n return {};\n }\n}\n\n/**\n * Build the `if` sub-schema for a condition. Returns undefined for no field.\n * Pass the field's `type` so the comparand matches the form data's type.\n */\nexport function conditionToIf(\n condition: Condition,\n type?: ScopeType,\n): JsonSchemaProperty | undefined {\n const { field, operator } = condition;\n if (!field) return undefined;\n if (operator === \"exists\") {\n return { required: [field] };\n }\n return {\n properties: {\n [field]: operatorToConstraint(operator, condition.value, type),\n },\n required: [field],\n };\n}\n\n/** Recover the operator + value from a per-value constraint schema. */\nexport function constraintToOperator(c: JsonSchemaProperty): {\n operator: ConditionOperator;\n value: string;\n} {\n if (c.not && \"const\" in c.not)\n return { operator: \"!=\", value: String(c.not.const) };\n if (c.exclusiveMinimum !== undefined)\n return { operator: \">\", value: String(c.exclusiveMinimum) };\n if (c.minimum !== undefined)\n return { operator: \">=\", value: String(c.minimum) };\n if (c.exclusiveMaximum !== undefined)\n return { operator: \"<\", value: String(c.exclusiveMaximum) };\n if (c.maximum !== undefined)\n return { operator: \"<=\", value: String(c.maximum) };\n if (\"const\" in c) return { operator: \"=\", value: String(c.const) };\n return { operator: \"exists\", value: \"\" };\n}\n\n/** Recover a Condition from an `if` sub-schema (inverse of conditionToIf). */\nexport function ifToCondition(\n ifSchema: JsonSchemaProperty | undefined,\n): Condition {\n const empty: Condition = { field: \"\", operator: \"=\", value: \"\" };\n if (!ifSchema) return empty;\n const props = ifSchema.properties ?? {};\n const field = Object.keys(props)[0] ?? ifSchema.required?.[0] ?? \"\";\n if (!field) return empty;\n const constraint = props[field];\n if (!constraint) return { field, operator: \"exists\", value: \"\" };\n const { operator, value } = constraintToOperator(constraint);\n return { field, operator, value };\n}\n","/**\n * Shared operator + value input used by both ConditionEditor and RuleEditor.\n * Renders a labelled Input that commits on blur via the provided callback.\n */\n\nimport React from \"react\";\nimport { Input } from \"@petrarca/sonnet-ui\";\n\nexport interface OperatorValueInputProps {\n id: string;\n /** A key that remounts the input when the operator or field changes. */\n cacheKey: string;\n value: string;\n onCommit: (value: string) => void;\n disabled: boolean;\n}\n\nexport function OperatorValueInput({\n id,\n cacheKey,\n value,\n onCommit,\n disabled,\n}: OperatorValueInputProps): React.ReactElement {\n return (\n <div className=\"space-y-1\">\n <label htmlFor={id} className=\"text-sm font-medium\">\n Value\n </label>\n <Input\n id={id}\n key={cacheKey}\n defaultValue={value}\n onBlur={(e) => onCommit(e.target.value)}\n disabled={disabled}\n placeholder=\"Value to compare\"\n />\n </div>\n );\n}\n","/**\n * Effect choices offered by the rule editors. Kept apart from the components\n * so a fast-refresh boundary is not broken by a non-component export.\n */\n\n/** One effect choice; \"\" clears the rule entirely. */\nexport interface EffectOption {\n value: string;\n label: string;\n}\n\n/** Visibility-only effects (a layout group cannot be \"disabled\"). */\nexport const VISIBILITY_EFFECT_OPTIONS: EffectOption[] = [\n { value: \"\", label: \"None (always shown)\" },\n { value: \"show\", label: \"Show when\" },\n { value: \"hide\", label: \"Hide when\" },\n];\n\n/** Visibility plus enablement, for a field. */\nexport const FIELD_EFFECT_OPTIONS: EffectOption[] = [\n { value: \"\", label: \"None (always visible)\" },\n { value: \"show\", label: \"Show when\" },\n { value: \"hide\", label: \"Hide when\" },\n { value: \"enable\", label: \"Enable when\" },\n { value: \"disable\", label: \"Disable when\" },\n];\n","/**\n * CapabilitiesPanel -- edits the SchemaDesignerCapabilities profile as JSON and\n * applies it live. A dev / power-user affordance shown only when the profile\n * lists \"capabilities\" in previews. Validates via `validateCapabilities` before\n * applying; invalid JSON or an invalid profile surfaces an inline error.\n *\n * Reuses SchemaSourcePanel for the editor + corner Copy/Apply chrome, keeping\n * the source tabs consistent.\n */\n\nimport React, { useMemo } from \"react\";\nimport {\n validateCapabilities,\n type SchemaDesignerCapabilities,\n} from \"../capabilities\";\nimport { SchemaSourcePanel } from \"./SchemaSourcePanel\";\n\nexport interface CapabilitiesPanelProps {\n capabilities?: SchemaDesignerCapabilities;\n onApply?: (next: SchemaDesignerCapabilities) => void;\n}\n\nexport function CapabilitiesPanel({\n capabilities,\n onApply,\n}: CapabilitiesPanelProps): React.ReactElement {\n const value = useMemo(\n () => JSON.stringify(capabilities ?? {}, null, 2),\n [capabilities],\n );\n\n return (\n <SchemaSourcePanel\n value={value}\n editable\n validate={(parsed) => {\n const result = validateCapabilities(parsed);\n return result.ok ? null : result.errors.join(\"; \");\n }}\n onApply={(parsed) => {\n const result = validateCapabilities(parsed);\n if (result.ok) onApply?.(result.value);\n }}\n />\n );\n}\n","/**\n * SchemaSourcePanel -- JSON source view for a designer artifact (the JSON\n * Schema or the UI Schema map), read-only or editable.\n *\n * When editable, the editor holds transient text; nothing is committed until\n * Apply. On Apply the text is parsed and, if valid JSON, passed to `onApply`\n * which replaces the corresponding artifact in the model. Subsequent visual\n * edits are surgical, so hand-authored constructs (oneOf, if/then/else, const,\n * $ref, ...) survive.\n *\n * Copy and Apply are corner-overlay buttons, consistent with the read-only JSON\n * views. The \"Combined\" view is intentionally not editable: it is a derived\n * projection (schema + embedded UI hints) that cannot be un-merged unambiguously.\n */\n\nimport React, { useEffect, useRef, useState } from \"react\";\nimport { Check, Copy } from \"lucide-react\";\nimport { Button } from \"@petrarca/sonnet-ui\";\nimport { JsonEditor } from \"@petrarca/sonnet-ui/json-editor\";\nimport { copyTextToClipboard } from \"@petrarca/sonnet-core\";\n\nexport interface SchemaSourcePanelProps {\n /** Serialized current value of the artifact. */\n value: string;\n /** Whether editing is allowed (false renders read-only). */\n editable: boolean;\n /** Called with the parsed object when the user applies a valid edit. */\n onApply: (parsed: unknown) => void;\n /** Optional validation returning an error string, or null when valid. */\n validate?: (parsed: unknown) => string | null;\n}\n\nexport function SchemaSourcePanel({\n value,\n editable,\n onApply,\n validate,\n}: SchemaSourcePanelProps): React.ReactElement {\n const [text, setText] = useState(value);\n const [error, setError] = useState<string | null>(null);\n const [copied, setCopied] = useState(false);\n // Dirty means the USER edited the text since we last adopted a model value.\n // It must NOT be derived from `text !== value`: when the model changes\n // underneath (e.g. a visual tree/inspector edit while this tab is open),\n // `text` lags `value` for one render, which `text !== value` would wrongly\n // read as a user edit -- staling the view and falsely enabling Apply.\n const [dirty, setDirty] = useState(false);\n\n // The last model value this panel has adopted into `text`. Compared against\n // incoming `value` to detect genuine external model changes.\n const lastValueRef = useRef(value);\n useEffect(() => {\n if (value === lastValueRef.current) return;\n // A model change always wins over a clean editor. It only yields to the\n // user when they have an unapplied edit (dirty) -- then we keep their text\n // and let them Apply or discard, rather than clobbering silently.\n // lastValueRef tracks only adopted values so a repeated model emission of\n // the same string (e.g. two normalizations to the same JSON) is not missed.\n if (!dirty) {\n lastValueRef.current = value;\n setText(value);\n setError(null);\n }\n }, [value, dirty]);\n\n // User typed in the editor: adopt the text and mark dirty. When the text\n // matches the current model again, the edit has been reverted -- clear dirty.\n const handleEditorChange = (next: string): void => {\n setText(next);\n setDirty(next !== value);\n };\n\n const handleCopy = (): void => {\n void copyTextToClipboard(editable ? text : value).then(() => {\n setCopied(true);\n setTimeout(() => setCopied(false), 1500);\n });\n };\n\n const handleApply = (): void => {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text || \"{}\");\n } catch {\n setError(\"Invalid JSON.\");\n return;\n }\n const validationError = validate?.(parsed);\n if (validationError) {\n setError(validationError);\n return;\n }\n setError(null);\n // The edit is applied; the model will re-serialize and flow back as a new\n // `value`, which the (now clean) effect adopts. Clear dirty and snap\n // lastValueRef so that incoming value is taken even if it equals prior text.\n setDirty(false);\n onApply(parsed);\n };\n\n return (\n <div className=\"absolute inset-0 rounded-md border overflow-hidden\">\n <div className=\"absolute right-2 top-2 z-10 flex items-center gap-2\">\n {error && (\n <span className=\"rounded bg-destructive px-2 py-1 text-xs font-medium text-destructive-foreground\">\n {error}\n </span>\n )}\n {editable && (\n <Button\n type=\"button\"\n size=\"sm\"\n onClick={handleApply}\n disabled={!dirty}\n >\n Apply\n </Button>\n )}\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n onClick={handleCopy}\n className=\"gap-1.5\"\n >\n {copied ? (\n <Check className=\"h-3.5 w-3.5\" />\n ) : (\n <Copy className=\"h-3.5 w-3.5\" />\n )}\n {copied ? \"Copied\" : \"Copy\"}\n </Button>\n </div>\n {editable ? (\n <JsonEditor\n value={text}\n editablePaths={[\"/\"]}\n fillContainer\n onChange={handleEditorChange}\n />\n ) : (\n <JsonEditor\n key={value}\n value={value}\n editablePaths={[]}\n fillContainer\n />\n )}\n </div>\n );\n}\n","/**\n * Inspector -- the right pane. Resolves the selected property and hosts the tabbed\n * editors (Data now; UI and Layout added incrementally). Empty state when no\n * property is selected.\n */\n\nimport React, { useEffect, useMemo, useRef, useState } from \"react\";\nimport {\n Tabs,\n TabsList,\n TabsTrigger,\n TabsContent,\n Input,\n IconButton,\n} from \"@petrarca/sonnet-ui\";\nimport { Pencil, Check, X } from \"lucide-react\";\nimport type { WidgetOptionDef } from \"@petrarca/sonnet-forms/widget-options\";\nimport type { DesignerState } from \"../hooks/useDesignerState\";\nimport { buildPropertyTree, type PropertyNode } from \"../model/view\";\nimport { samePath, pathKey, type PropertyPath } from \"../model/paths\";\nimport { DataTab } from \"./DataTab\";\nimport { UITab } from \"./UITab\";\nimport { EnumEditor } from \"./EnumEditor\";\nimport { TableHintsTab } from \"./TableHintsTab\";\nimport { ConditionEditor } from \"./ConditionEditor\";\nimport { RuleEditor } from \"./RuleEditor\";\nimport { ReferenceTab } from \"./ReferenceTab\";\n\n// Property types for which a fixed enum makes sense.\nconst ENUM_CAPABLE_TYPES = new Set([\"string\", \"number\", \"integer\"]);\n\nexport interface InspectorProps {\n state: DesignerState;\n /** Option descriptors for custom widgets (merged over built-ins). */\n widgetOptions?: Record<string, WidgetOptionDef[]>;\n}\n\n// Property key display + explicit edit affordance. Shows the key as static text\n// with a small pencil button (matching the graph-model rename pattern). Clicking\n// edit reveals an input with confirm/cancel; commit routes to renameProperty.\nfunction KeyField({\n fieldKey,\n onRename,\n readOnly,\n}: {\n fieldKey: string;\n onRename: (next: string) => void;\n readOnly: boolean;\n}): React.ReactElement {\n const [editing, setEditing] = useState(false);\n const [value, setValue] = useState(fieldKey);\n const ref = useRef<HTMLInputElement>(null);\n\n // Re-seed and exit edit mode when the selected property changes.\n useEffect(() => {\n setValue(fieldKey);\n setEditing(false);\n }, [fieldKey]);\n\n useEffect(() => {\n if (editing) {\n ref.current?.focus();\n ref.current?.select();\n }\n }, [editing]);\n\n const commit = () => {\n const trimmed = value.trim();\n if (trimmed && trimmed !== fieldKey) onRename(trimmed);\n setEditing(false);\n };\n const cancel = () => {\n setValue(fieldKey);\n setEditing(false);\n };\n\n if (!editing) {\n return (\n <div className=\"flex items-center gap-1\">\n <span className=\"text-sm font-semibold truncate\">{fieldKey}</span>\n {!readOnly && (\n <IconButton label=\"Rename property\" onClick={() => setEditing(true)}>\n <Pencil />\n </IconButton>\n )}\n </div>\n );\n }\n\n return (\n <div className=\"flex items-center gap-1\">\n <Input\n ref={ref}\n value={value}\n onChange={(e) => setValue(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === \"Enter\") {\n e.preventDefault();\n commit();\n } else if (e.key === \"Escape\") {\n e.preventDefault();\n cancel();\n }\n }}\n className=\"h-7 text-sm font-medium\"\n />\n <IconButton label=\"Confirm rename\" onClick={commit}>\n <Check />\n </IconButton>\n <IconButton label=\"Cancel rename\" onClick={cancel}>\n <X />\n </IconButton>\n </div>\n );\n}\n\n// Find the node for a path in the built tree.\nfunction findNode(\n nodes: PropertyNode[],\n path: PropertyPath,\n): PropertyNode | undefined {\n for (const node of nodes) {\n if (samePath(node.path, path)) return node;\n const inChild = findNode(node.children, path);\n if (inChild) return inChild;\n }\n return undefined;\n}\n\n// Header: the (maybe-renamable) key + the type label.\nfunction InspectorHeader({\n node,\n state,\n}: {\n node: PropertyNode;\n state: DesignerState;\n}): React.ReactElement {\n const isDefinition = node.kind === \"definition\";\n // Branches and conditionals have no renamable key. A definition renames via\n // renameDefinition (rewriting $refs); it is gated by the lock, not scoping.\n const noRename = isDefinition\n ? state.capabilities.locked\n : state.readOnly ||\n node.slotKind === \"branch\" ||\n node.slotKind === \"conditional\";\n const onRename = (next: string) =>\n isDefinition\n ? state.renameDefinition(node.key, next)\n : state.renameProperty(node.path, next);\n return (\n <div className=\"mb-3 space-y-1\">\n <KeyField\n key={pathKey(node.path)}\n fieldKey={node.key}\n readOnly={noRename}\n onRename={onRename}\n />\n <p className=\"font-mono text-xs text-muted-foreground\">\n {isDefinition ? \"definition\" : node.typeLabel}\n </p>\n </div>\n );\n}\n\n// The standard property editor: Data / Enum / UI / Table tabs.\nfunction PropertyTabs({\n node,\n state,\n widgetOptions,\n}: {\n node: PropertyNode;\n state: DesignerState;\n widgetOptions?: Record<string, WidgetOptionDef[]>;\n}): React.ReactElement {\n const enumCapable = ENUM_CAPABLE_TYPES.has(node.property.type ?? \"\");\n // Rule tab: x-ui-rule operates on a JSON Pointer into the root form data, so\n // it is not applicable inside branch/condition/slot paths. Def-field paths\n // cross a def segment but are otherwise normal properties -- allow Rule there.\n const ruleUnsupported = node.path.some(\n (s) => s.kind === \"branch\" || s.kind === \"condition\" || s.kind === \"slot\",\n );\n // UI tab: the uiSchema map is keyed by top-level property name; fields inside\n // any non-prop segment (branch, condition, slot, or def) cannot be addressed\n // without colliding with same-named properties at other paths.\n const uiUnsupported = node.path.some((s) => s.kind !== \"prop\");\n return (\n <Tabs key={`${pathKey(node.path)}:${enumCapable}`} defaultValue=\"data\">\n <TabsList className=\"mb-3\">\n <TabsTrigger value=\"data\">Data</TabsTrigger>\n {enumCapable && <TabsTrigger value=\"enum\">Enum</TabsTrigger>}\n <TabsTrigger value=\"ui\">UI</TabsTrigger>\n {!ruleUnsupported && <TabsTrigger value=\"rule\">Rule</TabsTrigger>}\n <TabsTrigger value=\"table\">Table</TabsTrigger>\n </TabsList>\n <TabsContent value=\"data\">\n <DataTab node={node} state={state} />\n </TabsContent>\n {enumCapable && (\n <TabsContent value=\"enum\">\n <EnumEditor node={node} state={state} />\n </TabsContent>\n )}\n {!ruleUnsupported && (\n <TabsContent value=\"rule\">\n <RuleEditor node={node} state={state} />\n </TabsContent>\n )}\n <TabsContent value=\"ui\">\n {/* uiSchema has no branch-index or def concept; widget hints for\n non-root-prop paths cannot be addressed without key collisions.\n Author them in the JSON Schema or UI Schema source tab instead. */}\n {uiUnsupported ? (\n <p className=\"text-sm text-muted-foreground p-2\">\n Widget hints for properties inside a variant branch or definition\n are not yet editable here. Author them in the JSON Schema or UI\n Schema tab.\n </p>\n ) : (\n <UITab node={node} state={state} widgetOptions={widgetOptions} />\n )}\n </TabsContent>\n <TabsContent value=\"table\">\n <TableHintsTab node={node} state={state} />\n </TabsContent>\n </Tabs>\n );\n}\n\n// The body for a node: a construct-specific panel, else the standard tabs.\nfunction InspectorBody({\n node,\n state,\n widgetOptions,\n}: {\n node: PropertyNode;\n state: DesignerState;\n widgetOptions?: Record<string, WidgetOptionDef[]>;\n}): React.ReactElement {\n const lastSeg = node.path[node.path.length - 1];\n // A $ref node: its referenced fields are read-only (edit the definition), but\n // 2020-12 allows local annotation overrides (title/description/default) at the\n // referencing site, plus a \"stop referencing\" action -- see ReferenceTab.\n if (node.kind === \"reference\") {\n return <ReferenceTab node={node} state={state} />;\n }\n // A field inside a referenced definition: read-only (edit it at the source).\n if (node.readOnly) {\n return (\n <p className=\"text-sm text-muted-foreground p-2\">\n This field comes from a shared definition and is read-only here. Edit\n the definition in the JSON Schema tab to change it.\n </p>\n );\n }\n // A definition ($defs entry): a reusable object schema. Rename it in the\n // header; edit its fields in the tree. Its scalar/type keys are not edited\n // at the definition level in v1 (author advanced shapes in the source tab).\n if (node.kind === \"definition\") {\n return (\n <p className=\"text-sm text-muted-foreground p-2\">\n Reusable definition <span className=\"font-medium\">{node.key}</span>. Add\n or edit its fields in the tree; reference it from a property to reuse\n its shape. Renaming it here updates every reference.\n </p>\n );\n }\n // A conditional member: edit its `if` in the condition builder.\n if (node.kind === \"conditional\") {\n return <ConditionEditor node={node} state={state} />;\n }\n // A then/else slot: an object container whose fields are edited in the tree.\n if (node.slotKind === \"conditional\" && lastSeg?.kind === \"slot\") {\n return (\n <p className=\"text-sm text-muted-foreground p-2\">\n Add fields to this <span className=\"font-medium\">{node.key}</span>{\" \"}\n branch from the tree. They apply when the condition{\" \"}\n {node.key === \"then\" ? \"holds\" : \"does not hold\"}.\n </p>\n );\n }\n return (\n <PropertyTabs node={node} state={state} widgetOptions={widgetOptions} />\n );\n}\n\nexport function Inspector({\n state,\n widgetOptions,\n}: InspectorProps): React.ReactElement {\n const tree = useMemo(\n () => buildPropertyTree(state.schema, state.refResolver),\n [state.schema, state.refResolver],\n );\n const node = state.selection ? findNode(tree, state.selection) : undefined;\n\n if (!node) {\n return (\n <p className=\"text-sm text-muted-foreground\">\n Select a property to edit.\n </p>\n );\n }\n\n return (\n <div>\n <InspectorHeader node={node} state={state} />\n <InspectorBody node={node} state={state} widgetOptions={widgetOptions} />\n </div>\n );\n}\n","/**\n * DataTab -- edits a property's data definition (type, title, description,\n * default, required, validation) via a meta-schema rendered with\n * JsonSchemaFormRenderer. Type and required are routed to dedicated mutations\n * (they reshape structure / live on the parent); the rest is a property patch.\n */\n\nimport React, { useMemo, useRef } from \"react\";\nimport { JsonSchemaFormRenderer } from \"@petrarca/sonnet-forms\";\nimport {\n Select,\n SelectTrigger,\n SelectValue,\n SelectContent,\n SelectItem,\n} from \"@petrarca/sonnet-ui\";\nimport type { DesignerState } from \"../hooks/useDesignerState\";\nimport type { PropertyNode } from \"../model/view\";\nimport { pathKey } from \"../model/paths\";\nimport type { PropertyTypeChoice } from \"../model/mutate\";\nimport {\n BRANCH_META_TYPE,\n buildDataMetaSchema,\n dataValuesToPatch,\n propertyToDataValues,\n type DataFormValues,\n} from \"./metaSchemas\";\n\nexport interface DataTabProps {\n node: PropertyNode;\n state: DesignerState;\n}\n\nexport function DataTab({ node, state }: DataTabProps): React.ReactElement {\n const isBranch = node.slotKind === \"branch\";\n // A branch is an anonymous object; its editable data is just its title.\n const type = isBranch\n ? BRANCH_META_TYPE\n : node.property.oneOf\n ? \"oneOf\"\n : (node.property.type ?? \"string\");\n const schema = useMemo(() => buildDataMetaSchema(type), [type]);\n const values = useMemo(\n () => propertyToDataValues(node.property, node.required),\n [node.property, node.required],\n );\n\n // Track previous values to detect which attribute changed.\n const prevRef = useRef<DataFormValues>(values);\n prevRef.current = values;\n\n const handleChange = (data: Record<string, unknown>) => {\n const next = data as unknown as DataFormValues;\n const prev = prevRef.current;\n\n // Each renderer onChange reflects a single attribute edit; route it to exactly\n // one mutation. Firing two mutations here would double-commit against the\n // same (pre-render) model and the second would clobber the first.\n\n // Type change reshapes the property (not applicable to a branch).\n if (!isBranch && next.type !== prev.type) {\n state.changePropertyType(node.path, next.type as PropertyTypeChoice);\n return;\n }\n // Required lives on the parent's required[], not on the property.\n if (next.required !== prev.required) {\n state.setRequired(node.path, !!next.required);\n return;\n }\n // Otherwise it is a property attribute change.\n state.updateProperty(node.path, dataValuesToPatch(next));\n };\n\n return (\n <div className=\"space-y-3\">\n {!isBranch && (\n <ReferencePicker node={node} state={state} disabled={state.readOnly} />\n )}\n <JsonSchemaFormRenderer\n key={pathKey(node.path) + \":\" + type}\n schema={schema}\n data={values as unknown as Record<string, unknown>}\n onChange={handleChange}\n deferStateUpdates\n showActions={false}\n showExtraProperties={false}\n readOnly={state.readOnly}\n />\n </div>\n );\n}\n\n// The definition names available to reference (2020-12 $defs or Draft-7\n// definitions). Excludes the definition currently being edited, if any.\nfunction availableDefinitions(\n state: DesignerState,\n node: PropertyNode,\n): string[] {\n const defs = state.schema.$defs ?? state.schema.definitions;\n if (!defs) return [];\n const selfName =\n node.path.length === 1 && node.path[0].kind === \"def\"\n ? node.path[0].name\n : undefined;\n return Object.keys(defs).filter((name) => name !== selfName);\n}\n\n// A picker that turns the property into a reference to a shared definition.\n// Only shown when definitions exist; choosing one writes a local $ref.\nfunction ReferencePicker({\n node,\n state,\n disabled,\n}: {\n node: PropertyNode;\n state: DesignerState;\n disabled: boolean;\n}): React.ReactElement | null {\n const names = availableDefinitions(state, node);\n if (names.length === 0) return null;\n // For an array the reference applies to its items (\"array of <def>\").\n const isArray = node.property.type === \"array\";\n const label = isArray\n ? \"Reference a definition (array items)\"\n : \"Reference a definition\";\n const placeholder = isArray\n ? \"Make items reuse a shared definition...\"\n : \"Reuse a shared definition...\";\n return (\n <div className=\"space-y-1\">\n <label className=\"text-xs font-medium text-muted-foreground\">\n {label}\n </label>\n <Select\n value=\"\"\n onValueChange={(name) => state.setReference(node.path, name)}\n disabled={disabled}\n >\n <SelectTrigger className=\"h-8 text-sm\">\n <SelectValue placeholder={placeholder} />\n </SelectTrigger>\n <SelectContent>\n {names.map((name) => (\n <SelectItem key={name} value={name}>\n {name}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n );\n}\n","/**\n * Meta-schemas -- JsonSchemas that describe a property definition, rendered by\n * JsonSchemaFormRenderer to produce the inspector's Data tab. Recomputed per\n * property type so only relevant validation constraints appear.\n *\n * This is the property-definition meta-schema (cf.\n * graph-model/PropertyFormSheet's buildSchema), kept in the designer for now.\n */\n\nimport type {\n JsonSchema,\n JsonSchemaProperty,\n} from \"@petrarca/sonnet-core/schema\";\n\nexport const PROPERTY_TYPES = [\n \"string\",\n \"number\",\n \"integer\",\n \"boolean\",\n \"object\",\n \"array\",\n \"null\",\n] as const;\n\n// The kind choices offered by the type dropdown. Extends the JSON Schema types\n// with logic constructs (\"oneOf\"). Values are PropertyTypeChoice (see mutate).\nexport const PROPERTY_TYPE_CHOICES = [...PROPERTY_TYPES, \"oneOf\"] as const;\n\n// Friendly labels for the type dropdown (null is a display-only text block).\nconst PROPERTY_TYPE_NAMES: Record<string, string> = {\n string: \"String\",\n number: \"Number\",\n integer: \"Integer\",\n boolean: \"Boolean\",\n object: \"Object\",\n array: \"Array\",\n null: \"Display (text only)\",\n oneOf: \"One of (variant)\",\n};\n\n/** The editable data-attributes of a property, as flat form data. */\nexport interface DataFormValues {\n type: string;\n title?: string;\n description?: string;\n default?: unknown;\n const?: string;\n required: boolean;\n // validation\n minLength?: number;\n maxLength?: number;\n pattern?: string;\n format?: string;\n minimum?: number;\n maximum?: number;\n minItems?: number;\n maxItems?: number;\n // oneOf\n discriminator?: string;\n}\n\nconst STRING_FORMATS = [\n \"\",\n \"email\",\n \"uri\",\n \"url\",\n \"date\",\n \"date-time\",\n \"time\",\n \"uuid\",\n];\n\n// Validation properties available per type.\nfunction validationProps(type: string): Record<string, JsonSchemaProperty> {\n switch (type) {\n case \"string\":\n return {\n format: { type: \"string\", title: \"Format\", enum: STRING_FORMATS },\n minLength: { type: \"integer\", title: \"Min length\", minimum: 0 },\n maxLength: { type: \"integer\", title: \"Max length\", minimum: 0 },\n pattern: { type: \"string\", title: \"Pattern (regex)\" },\n };\n case \"number\":\n case \"integer\":\n return {\n minimum: { type: \"number\", title: \"Minimum\" },\n maximum: { type: \"number\", title: \"Maximum\" },\n };\n case \"array\":\n return {\n minItems: { type: \"integer\", title: \"Min items\", minimum: 0 },\n maxItems: { type: \"integer\", title: \"Max items\", minimum: 0 },\n };\n default:\n return {};\n }\n}\n\n/**\n * Build the Data-tab meta-schema for a property of the given type. `isContainer`\n * (object/array) hides `default`, which is not meaningful there.\n */\n// Synthetic meta-type used for oneOf branches in the Data tab. Not a real JSON\n// Schema type -- used only within the inspector to select the branch sub-schema.\nexport const BRANCH_META_TYPE = \"branch\" as const;\n\n// Which meta-fields apply to a given property type.\ninterface TypeTraits {\n isDisplay: boolean;\n noDefault: boolean;\n noRequired: boolean;\n isScalar: boolean;\n isOneOf: boolean;\n}\n\nfunction typeTraits(type: string): TypeTraits {\n const isDisplay = type === \"null\";\n const isOneOf = type === \"oneOf\";\n const isContainer = type === \"object\" || type === \"array\";\n return {\n isDisplay,\n isOneOf,\n // Containers, display (null), and oneOf have no meaningful default value.\n noDefault: isContainer || isDisplay || isOneOf,\n // Display notes and oneOf unions are never \"required\" on their own.\n noRequired: isDisplay || isOneOf,\n // A fixed value (const) is only meaningful on scalar properties.\n isScalar:\n type === \"string\" ||\n type === \"number\" ||\n type === \"integer\" ||\n type === \"boolean\",\n };\n}\n\n/**\n * The Data-tab meta-schema for a `$ref` (reference) node. In JSON Schema\n * 2020-12, keywords alongside `$ref` are applied at the referencing site (they\n * are NOT ignored, unlike Draft 7). Only annotation overrides are meaningful\n * here -- structural type/validation belongs to the referenced definition, so\n * this exposes just title/description/default/required as local overrides.\n */\nexport function buildReferenceMetaSchema(): JsonSchema {\n return {\n title: \"\",\n type: \"object\",\n properties: {\n title: { type: \"string\", title: \"Label (title)\" },\n description: {\n type: \"string\",\n title: \"Description\",\n \"x-ui-widget\": \"textarea\",\n },\n required: { type: \"boolean\", title: \"Required\" },\n default: { type: \"string\", title: \"Default\" },\n },\n };\n}\n\nexport function buildDataMetaSchema(type: string): JsonSchema {\n // A oneOf branch: only its title (the branch label) is editable here; its\n // fields are edited as child properties in the tree.\n if (type === BRANCH_META_TYPE) {\n return {\n title: \"\",\n type: \"object\",\n properties: {\n title: { type: \"string\", title: \"Branch label (title)\" },\n },\n };\n }\n const { isDisplay, noDefault, noRequired, isScalar, isOneOf } =\n typeTraits(type);\n const properties: Record<string, JsonSchemaProperty> = {\n type: {\n type: \"string\",\n title: \"Type\",\n enum: [...PROPERTY_TYPE_CHOICES],\n \"x-ui-options\": { enumNames: PROPERTY_TYPE_NAMES },\n },\n title: { type: \"string\", title: isDisplay ? \"Text\" : \"Label (title)\" },\n description: {\n type: \"string\",\n title: \"Description\",\n \"x-ui-widget\": \"textarea\",\n },\n ...(isOneOf\n ? {\n discriminator: {\n type: \"string\",\n title: \"Discriminator property\",\n \"x-ui-description\":\n \"Shared property whose const value tags each branch. Auto-detected when blank.\",\n },\n }\n : {}),\n ...(noRequired ? {} : { required: { type: \"boolean\", title: \"Required\" } }),\n ...(noDefault ? {} : { default: { type: \"string\", title: \"Default\" } }),\n ...(isScalar\n ? {\n const: {\n type: \"string\",\n title: \"Const (fixed value)\",\n \"x-ui-description\":\n \"Fixed value this property must equal. Leave blank for none.\",\n },\n }\n : {}),\n ...validationProps(type),\n };\n return { title: \"\", type: \"object\", properties };\n}\n\n/** Extract flat Data-tab form values from a property + its required flag. */\nexport function propertyToDataValues(\n prop: JsonSchemaProperty,\n required: boolean,\n): DataFormValues {\n return {\n type: prop.oneOf ? \"oneOf\" : (prop.type ?? \"string\"),\n title: prop.title,\n description: prop.description,\n default: prop.default,\n // const may be any JSON type; the Data-tab field edits it as a string.\n const: prop.const == null ? undefined : String(prop.const),\n required,\n minLength: prop.minLength,\n maxLength: prop.maxLength,\n pattern: prop.pattern,\n format: prop.format,\n minimum: prop.minimum,\n maximum: prop.maximum,\n minItems: prop.minItems,\n maxItems: prop.maxItems,\n discriminator: prop.discriminator?.propertyName,\n };\n}\n\n/**\n * Produce the property patch (excluding `type` and `required`, which are\n * handled separately) from Data-tab form values. Empty strings/undefined clear\n * the corresponding key.\n */\nexport function dataValuesToPatch(\n values: DataFormValues,\n): Partial<JsonSchemaProperty> {\n const patch: Partial<JsonSchemaProperty> = {};\n const setStr = (k: keyof JsonSchemaProperty, v: unknown) => {\n if (typeof v === \"string\" && v.length > 0)\n (patch as Record<string, unknown>)[k] = v;\n else (patch as Record<string, unknown>)[k] = undefined;\n };\n const setNum = (k: keyof JsonSchemaProperty, v: unknown) => {\n if (typeof v === \"number\" && !Number.isNaN(v))\n (patch as Record<string, unknown>)[k] = v;\n else (patch as Record<string, unknown>)[k] = undefined;\n };\n setStr(\"title\", values.title);\n setStr(\"description\", values.description);\n setStr(\"default\", values.default);\n setStr(\"const\", values.const);\n setStr(\"format\", values.format);\n setStr(\"pattern\", values.pattern);\n setNum(\"minLength\", values.minLength);\n setNum(\"maxLength\", values.maxLength);\n setNum(\"minimum\", values.minimum);\n setNum(\"maximum\", values.maximum);\n setNum(\"minItems\", values.minItems);\n setNum(\"maxItems\", values.maxItems);\n // Discriminator: write discriminator.propertyName, or clear when blank.\n if (typeof values.discriminator === \"string\" && values.discriminator.length) {\n patch.discriminator = { propertyName: values.discriminator };\n } else {\n patch.discriminator = undefined;\n }\n return patch;\n}\n","/**\n * UITab -- edits a property's form presentation hints: the widget (x-ui-widget)\n * and its options (x-ui-options).\n *\n * The widget dropdown offers widgets compatible with the property's type (Auto\n * clears the override). The options editor is a JsonSchemaFormRenderer over a\n * schema derived from the selected widget's WidgetOptionDef[] (from the\n * design-time @petrarca/sonnet-forms/widget-options layer). Widgets with no\n * descriptor fall back to a raw JSON editor for x-ui-options.\n */\n\nimport React, { useMemo } from \"react\";\nimport { JsonSchemaFormRenderer } from \"@petrarca/sonnet-forms\";\nimport { JsonEditor } from \"@petrarca/sonnet-ui/json-editor\";\nimport {\n WIDGET_OPTION_DEFS,\n optionDefsToSchema,\n type WidgetOptionDef,\n} from \"@petrarca/sonnet-forms/widget-options\";\nimport { FormSelect } from \"@petrarca/sonnet-forms\";\nimport type {\n JsonSchema,\n UISchema,\n UISchemaOptions,\n UILayoutConfig,\n} from \"@petrarca/sonnet-core/schema\";\nimport type { DesignerState } from \"../hooks/useDesignerState\";\nimport type { PropertyNode } from \"../model/view\";\nimport { compatibleWidgets } from \"../model/compatibleWidgets\";\nimport { getUiEntryAtPath } from \"../model/mutate\";\nimport { pathKey } from \"../model/paths\";\n\nexport interface UITabProps {\n node: PropertyNode;\n state: DesignerState;\n /** Consumer-supplied option descriptors for custom widgets (merged over built-ins). */\n widgetOptions?: Record<string, WidgetOptionDef[]>;\n}\n\n// Meta-schema for the form presentation-text overrides. Keys are the actual\n// x-ui-* uiSchema keys so form data maps 1:1 to the entry.\nconst PRESENTATION_META_SCHEMA: JsonSchema = {\n title: \"\",\n type: \"object\",\n properties: {\n \"x-ui-title\": {\n type: \"string\",\n title: \"Label override\",\n description: \"Overrides the property title in the form.\",\n },\n \"x-ui-placeholder\": { type: \"string\", title: \"Placeholder\" },\n \"x-ui-description\": {\n type: \"string\",\n title: \"Help text\",\n \"x-ui-widget\": \"textarea\",\n },\n \"x-ui-width\": {\n type: \"string\",\n title: \"Field width\",\n description: \"Constrain the field's slot width in the form.\",\n enum: [\"full\", \"sm\", \"md\", \"lg\"],\n \"x-ui-options\": {\n enumNames: {\n full: \"Full width\",\n sm: \"Small\",\n md: \"Medium\",\n lg: \"Large\",\n },\n },\n },\n },\n};\n\n// Form presentation-text overrides (x-ui-title / x-ui-placeholder /\n// x-ui-description), written into the property's uiSchema entry.\nfunction PresentationEditor({\n fieldName,\n uiEntry,\n readOnly,\n onChange,\n}: {\n fieldName: string;\n uiEntry: UISchema;\n readOnly: boolean;\n onChange: (entry: UISchema) => void;\n}): React.ReactElement {\n const values = {\n \"x-ui-title\":\n typeof uiEntry[\"x-ui-title\"] === \"string\" ? uiEntry[\"x-ui-title\"] : \"\",\n \"x-ui-placeholder\": uiEntry[\"x-ui-placeholder\"] ?? \"\",\n \"x-ui-description\": uiEntry[\"x-ui-description\"] ?? \"\",\n \"x-ui-width\": uiEntry[\"x-ui-width\"] ?? \"full\",\n };\n\n const handleChange = (data: Record<string, unknown>) => {\n const next: UISchema = { ...uiEntry };\n for (const key of [\n \"x-ui-title\",\n \"x-ui-placeholder\",\n \"x-ui-description\",\n ] as const) {\n const v = data[key];\n if (typeof v === \"string\" && v.length > 0) next[key] = v;\n else delete next[key];\n }\n // Width: \"full\" is the default -- omit it to keep the uiSchema clean.\n const width = data[\"x-ui-width\"];\n if (width === \"sm\" || width === \"md\" || width === \"lg\") {\n next[\"x-ui-width\"] = width;\n } else {\n delete next[\"x-ui-width\"];\n }\n onChange(next);\n };\n\n return (\n <div>\n <p className=\"heading-meta mb-2\">Presentation (form overrides)</p>\n <JsonSchemaFormRenderer\n key={`${fieldName}:text`}\n schema={PRESENTATION_META_SCHEMA}\n data={values as Record<string, unknown>}\n onChange={handleChange}\n deferStateUpdates\n showActions={false}\n showExtraProperties={false}\n readOnly={readOnly}\n />\n </div>\n );\n}\n\n// Options editor: a generated form when the widget has descriptors, else a raw\n// JSON fallback. Kept separate to bound UITab's complexity.\nfunction OptionsEditor({\n widget,\n optionsSchema,\n currentOptions,\n readOnly,\n onChange,\n}: {\n widget: string;\n optionsSchema: JsonSchema | null;\n currentOptions: UISchemaOptions;\n readOnly: boolean;\n onChange: (opts: Record<string, unknown>) => void;\n}): React.ReactElement {\n if (optionsSchema) {\n return (\n <div>\n <p className=\"heading-meta mb-2\">Options</p>\n <JsonSchemaFormRenderer\n key={widget}\n schema={optionsSchema}\n data={currentOptions as Record<string, unknown>}\n onChange={onChange}\n deferStateUpdates\n showActions={false}\n showExtraProperties={false}\n readOnly={readOnly}\n />\n </div>\n );\n }\n return (\n <div>\n <p className=\"heading-meta mb-2\">Options (raw JSON)</p>\n <JsonEditor\n value={JSON.stringify(currentOptions ?? {}, null, 2)}\n editablePaths={readOnly ? [] : [\"/\"]}\n height=\"180px\"\n className=\"rounded-md border overflow-hidden\"\n onChange={(text) => {\n try {\n onChange(JSON.parse(text) as Record<string, unknown>);\n } catch {\n // ignore invalid JSON while typing\n }\n }}\n />\n </div>\n );\n}\n\nexport function UITab({\n node,\n state,\n widgetOptions,\n}: UITabProps): React.ReactElement {\n const idBase = pathKey(node.path);\n const uiEntry: UISchema = getUiEntryAtPath(state.uiSchema, node.path) ?? {};\n const currentWidget =\n typeof uiEntry[\"x-ui-widget\"] === \"string\"\n ? (uiEntry[\"x-ui-widget\"] as string)\n : null;\n const currentOptions = (uiEntry[\"x-ui-options\"] as UISchemaOptions) ?? {};\n\n // The form-level default this field inherits when it has no own override.\n const rootLayout = state.uiSchema[\"x-ui-layout\"] as\n | UILayoutConfig\n | undefined;\n const inheritedLabelPlacement = rootLayout?.labelPlacement ?? \"top\";\n\n const widgetChoices = useMemo(\n () => compatibleWidgets(node.property),\n [node.property],\n );\n\n const optionsSchema: JsonSchema | null = useMemo(() => {\n if (!currentWidget) return null;\n const merged = { ...WIDGET_OPTION_DEFS, ...(widgetOptions ?? {}) };\n const descriptors = merged[currentWidget];\n return descriptors && descriptors.length\n ? optionDefsToSchema(descriptors)\n : null;\n }, [currentWidget, widgetOptions]);\n\n const setWidget = (value: string | null) => {\n const next: UISchema = { ...uiEntry };\n if (value) next[\"x-ui-widget\"] = value;\n else delete next[\"x-ui-widget\"];\n state.setUiEntry(node.path, next);\n };\n\n const setOptions = (opts: Record<string, unknown>) => {\n const next: UISchema = { ...uiEntry };\n const cleaned = Object.fromEntries(\n Object.entries(opts).filter(([, v]) => v !== undefined && v !== \"\"),\n );\n if (Object.keys(cleaned).length) next[\"x-ui-options\"] = cleaned;\n else delete next[\"x-ui-options\"];\n state.setUiEntry(node.path, next);\n };\n\n // Label placement lives on x-ui-options. Three states in the UI:\n // \"__inherit__\" -> no key set; the field inherits the form-level default.\n // \"top\" / \"start\" -> an explicit per-field override.\n // Only an explicit value writes the key (and prunes an emptied x-ui-options).\n const setLabelPlacement = (value: string) => {\n const opts: UISchemaOptions = { ...currentOptions };\n if (value === \"top\" || value === \"start\") {\n opts.labelPlacement = value;\n } else {\n delete opts.labelPlacement;\n }\n const next: UISchema = { ...uiEntry };\n if (Object.keys(opts).length) next[\"x-ui-options\"] = opts;\n else delete next[\"x-ui-options\"];\n state.setUiEntry(node.path, next);\n };\n\n return (\n <div className=\"space-y-4\">\n <FormSelect\n id={`${idBase}-widget`}\n name=\"widget\"\n label=\"Widget\"\n value={currentWidget ?? \"__auto__\"}\n options={widgetChoices.map((c) => ({\n value: c.value ?? \"__auto__\",\n label: c.label,\n }))}\n onChange={(v) => setWidget(v === \"__auto__\" ? null : (v ?? null))}\n disabled={state.readOnly}\n clearable={false}\n />\n\n {currentWidget && (\n <OptionsEditor\n widget={`${idBase}:${currentWidget}`}\n optionsSchema={optionsSchema}\n currentOptions={currentOptions}\n readOnly={state.readOnly}\n onChange={setOptions}\n />\n )}\n\n <PresentationEditor\n fieldName={idBase}\n uiEntry={uiEntry}\n readOnly={state.readOnly}\n onChange={(entry) => state.setUiEntry(node.path, entry)}\n />\n\n <FormSelect\n id={`${idBase}-labelPlacement`}\n name=\"labelPlacement\"\n label=\"Label placement\"\n value={currentOptions.labelPlacement ?? \"__inherit__\"}\n options={[\n {\n value: \"__inherit__\",\n label: `Inherit (${inheritedLabelPlacement === \"start\" ? \"inline\" : \"above\"})`,\n },\n { value: \"top\", label: \"Above\" },\n { value: \"start\", label: \"Inline (start)\" },\n ]}\n onChange={(v) => setLabelPlacement(v ?? \"__inherit__\")}\n disabled={state.readOnly}\n clearable={false}\n />\n </div>\n );\n}\n","/**\n * EnumEditor -- edits a scalar property's allowed values (enum) and optional\n * display labels, as a row list.\n *\n * Each choice is a row: [value] [label] [remove]. An Add button appends a row.\n * Values write to property.enum; labels write to x-ui-options.enumNames (only\n * for top-level properties). All changes route through setEnum, which normalizes,\n * dedupes, and clears when empty.\n */\n\nimport React, { useEffect, useState } from \"react\";\nimport { Input, IconButton, Button } from \"@petrarca/sonnet-ui\";\nimport { Plus, Trash2 } from \"lucide-react\";\nimport type { DesignerState } from \"../hooks/useDesignerState\";\nimport type { PropertyNode } from \"../model/view\";\nimport { pathKey } from \"../model/paths\";\nimport {\n readEnumChoices,\n getUiEntryAtPath,\n type EnumChoice,\n} from \"../model/mutate\";\n\nexport interface EnumEditorProps {\n node: PropertyNode;\n state: DesignerState;\n}\n\nexport function EnumEditor({\n node,\n state,\n}: EnumEditorProps): React.ReactElement {\n // Local draft so typing an empty/duplicate value mid-edit is not dropped by\n // the normalizing mutation. Re-seed when the selected property changes.\n const [rows, setRows] = useState<EnumChoice[]>(() =>\n readEnumChoices(node.property, getUiEntryAtPath(state.uiSchema, node.path)),\n );\n useEffect(() => {\n setRows(\n readEnumChoices(\n node.property,\n getUiEntryAtPath(state.uiSchema, node.path),\n ),\n );\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [pathKey(node.path)]);\n\n const canEditLabels = true;\n\n const commit = (next: EnumChoice[]) => {\n setRows(next);\n state.setEnum(node.path, next);\n };\n\n const updateRow = (i: number, patch: Partial<EnumChoice>) => {\n commit(rows.map((r, idx) => (idx === i ? { ...r, ...patch } : r)));\n };\n const removeRow = (i: number) => commit(rows.filter((_, idx) => idx !== i));\n const addRow = () => setRows([...rows, { value: \"\", label: \"\" }]);\n\n return (\n <div className=\"space-y-3\">\n <div>\n <p className=\"text-sm font-medium\">Allowed values</p>\n <p className=\"text-xs text-muted-foreground\">\n Define a fixed set of choices. Leave empty for free input.\n </p>\n </div>\n\n {rows.length === 0 ? (\n <p className=\"text-xs text-muted-foreground\">No choices yet.</p>\n ) : (\n <div className=\"space-y-2\">\n {canEditLabels && (\n <div className=\"flex items-center gap-2 px-1\">\n <span className=\"heading-meta flex-1\">Value</span>\n <span className=\"heading-meta flex-1\">Label (optional)</span>\n <span className=\"w-7\" />\n </div>\n )}\n {rows.map((row, i) => (\n <div key={i} className=\"flex items-center gap-2\">\n <Input\n value={row.value}\n onChange={(e) => updateRow(i, { value: e.target.value })}\n placeholder=\"value\"\n disabled={state.readOnly}\n className=\"h-8 text-sm flex-1\"\n />\n {canEditLabels && (\n <Input\n value={row.label ?? \"\"}\n onChange={(e) => updateRow(i, { label: e.target.value })}\n placeholder={row.value || \"label\"}\n disabled={state.readOnly}\n className=\"h-8 text-sm flex-1\"\n />\n )}\n {!state.readOnly && (\n <IconButton\n label=\"Remove value\"\n tone=\"destructive\"\n onClick={() => removeRow(i)}\n >\n <Trash2 />\n </IconButton>\n )}\n </div>\n ))}\n </div>\n )}\n\n {!state.readOnly && (\n <Button\n variant=\"outline\"\n size=\"sm\"\n className=\"gap-1.5\"\n onClick={addRow}\n >\n <Plus className=\"h-4 w-4\" />\n Add value\n </Button>\n )}\n </div>\n );\n}\n","/**\n * TableHintsTab -- edits a property's table presentation hints (x-ui-cell,\n * x-ui-column, x-ui-cell-options), which EntityTable reads. These are embedded\n * on the schema property (not the uiSchema map). Live in the Table preview.\n *\n * The cell renderer list is derived from sonnet-ui's exported CELL_RENDERERS,\n * so it stays in sync with the actual table renderers. Cell options are edited\n * as raw JSON (varies per renderer).\n */\n\nimport React, { useMemo } from \"react\";\nimport { CELL_RENDERERS } from \"@petrarca/sonnet-ui\";\nimport { JsonEditor } from \"@petrarca/sonnet-ui/json-editor\";\nimport { FormSelect, JsonSchemaFormRenderer } from \"@petrarca/sonnet-forms\";\nimport type { JsonSchema } from \"@petrarca/sonnet-core/schema\";\nimport type { DesignerState } from \"../hooks/useDesignerState\";\nimport type { PropertyNode } from \"../model/view\";\nimport { readTableHints, type TableHints } from \"../model/mutate\";\nimport { pathKey } from \"../model/paths\";\n\nexport interface TableHintsTabProps {\n node: PropertyNode;\n state: DesignerState;\n}\n\nconst CELL_NAMES = Object.keys(CELL_RENDERERS);\n\n// Column meta-schema (flat fields; recomposed into x-ui-column on write).\nconst COLUMN_META_SCHEMA: JsonSchema = {\n title: \"\",\n type: \"object\",\n properties: {\n hidden: { type: \"boolean\", title: \"Hide column\" },\n order: { type: \"integer\", title: \"Column order\" },\n width: { type: \"integer\", title: \"Width (px)\", minimum: 0 },\n minWidth: { type: \"integer\", title: \"Min width (px)\", minimum: 0 },\n },\n};\n\ninterface ColumnFormValues {\n hidden?: boolean;\n order?: number;\n width?: number;\n minWidth?: number;\n}\n\nexport function TableHintsTab({\n node,\n state,\n}: TableHintsTabProps): React.ReactElement {\n const hints = readTableHints(node.property);\n\n const cellOptions = useMemo(\n () => JSON.stringify(hints.cellOptions ?? {}, null, 2),\n [hints.cellOptions],\n );\n\n const commit = (patch: Partial<TableHints>) =>\n state.setTableHints(node.path, { ...hints, ...patch });\n\n const columnValues: ColumnFormValues = {\n hidden: hints.column?.hidden,\n order: hints.column?.order,\n width: hints.column?.width,\n minWidth: hints.column?.minWidth,\n };\n\n const onColumnChange = (data: Record<string, unknown>) => {\n const v = data as ColumnFormValues;\n const column: NonNullable<TableHints[\"column\"]> = {};\n if (typeof v.hidden === \"boolean\") column.hidden = v.hidden;\n if (typeof v.order === \"number\" && !Number.isNaN(v.order))\n column.order = v.order;\n if (typeof v.width === \"number\" && !Number.isNaN(v.width))\n column.width = v.width;\n if (typeof v.minWidth === \"number\" && !Number.isNaN(v.minWidth))\n column.minWidth = v.minWidth;\n commit({ column });\n };\n\n return (\n <div className=\"space-y-4\">\n <FormSelect\n id={`${node.key}-cell`}\n name=\"cell\"\n label=\"Cell renderer\"\n value={hints.cell ?? \"__auto__\"}\n options={[\n { value: \"__auto__\", label: \"Auto (infer from type)\" },\n ...CELL_NAMES.map((n) => ({ value: n, label: n })),\n ]}\n onChange={(v: string | null) =>\n commit({ cell: !v || v === \"__auto__\" ? undefined : v })\n }\n disabled={state.readOnly}\n clearable={false}\n />\n\n <div>\n <p className=\"heading-meta mb-2\">Column</p>\n <JsonSchemaFormRenderer\n key={pathKey(node.path)}\n schema={COLUMN_META_SCHEMA}\n data={columnValues as Record<string, unknown>}\n onChange={onColumnChange}\n deferStateUpdates\n showActions={false}\n showExtraProperties={false}\n readOnly={state.readOnly}\n />\n </div>\n\n <div>\n <p className=\"heading-meta mb-2\">Cell options (JSON)</p>\n <JsonEditor\n value={cellOptions}\n editablePaths={state.readOnly ? [] : [\"/\"]}\n height=\"160px\"\n className=\"rounded-md border overflow-hidden\"\n onChange={(text) => {\n try {\n commit({\n cellOptions: JSON.parse(text) as Record<string, unknown>,\n });\n } catch {\n // ignore invalid JSON while typing\n }\n }}\n />\n </div>\n </div>\n );\n}\n","/**\n * ConditionEditor -- edits the `if` of a conditional (if/then/else) member.\n *\n * A condition tests a sibling property of the object that owns the conditional:\n * pick the property, an operator, and a value. The three combine into the `if`\n * sub-schema via conditionToIf; the renderer evaluates it live. then/else fields\n * are edited as child nodes in the tree, not here.\n */\n\nimport React, { useMemo } from \"react\";\nimport { FormSelect } from \"@petrarca/sonnet-forms\";\nimport type { JsonSchemaProperty } from \"@petrarca/sonnet-core/schema\";\nimport type { DesignerState } from \"../hooks/useDesignerState\";\nimport type { PropertyNode } from \"../model/view\";\nimport { getProperty } from \"../model/paths\";\nimport {\n conditionToIf,\n ifToCondition,\n OPERATOR_OPTIONS,\n type Condition,\n type ConditionOperator,\n} from \"../model/conditions\";\nimport { OperatorValueInput } from \"./OperatorValueInput\";\n\nexport interface ConditionEditorProps {\n node: PropertyNode;\n state: DesignerState;\n}\n\n// Sibling property names of the object that owns this conditional (the path\n// minus the trailing condition segment).\nfunction siblingFields(\n state: DesignerState,\n node: PropertyNode,\n): Record<string, JsonSchemaProperty> {\n const objectPath = node.path.slice(0, -1);\n const owner =\n objectPath.length === 0\n ? { properties: state.schema.properties }\n : getProperty(state.schema, objectPath);\n return owner?.properties ?? {};\n}\n\nexport function ConditionEditor({\n node,\n state,\n}: ConditionEditorProps): React.ReactElement {\n const condition = useMemo(\n () => ifToCondition(node.property.if),\n [node.property.if],\n );\n const fieldProps = useMemo(() => siblingFields(state, node), [state, node]);\n const fields = useMemo(() => Object.keys(fieldProps), [fieldProps]);\n const disabled = state.readOnly;\n\n // The combinator (AND/OR) is carried by the condition segment; it applies to\n // every condition on the owning object. Switching it migrates all of them.\n const lastSeg = node.path[node.path.length - 1];\n const combinator =\n lastSeg?.kind === \"condition\" ? lastSeg.combinator : \"allOf\";\n const objectPath = node.path.slice(0, -1);\n\n const commit = (next: Condition): void => {\n // Pass the target field's type so a boolean comparand is written as a\n // boolean, not the string \"true\" (which could never match).\n const ifSchema = conditionToIf(next, fieldProps[next.field]?.type);\n if (ifSchema) state.setCondition(node.path, ifSchema);\n };\n\n const fieldOptions = fields.map((f) => ({ value: f, label: f }));\n const needsValue = condition.operator !== \"exists\";\n\n return (\n <div className=\"space-y-3\">\n <p className=\"text-xs text-muted-foreground\">\n Show the <span className=\"font-medium\">then</span> fields when this\n condition holds (otherwise the <span className=\"font-medium\">else</span>{\" \"}\n fields, if any).\n </p>\n\n <FormSelect\n id=\"condition-match\"\n name=\"match\"\n label=\"Match (all conditions on this object)\"\n options={[\n { value: \"allOf\", label: \"All (AND)\" },\n { value: \"anyOf\", label: \"Any (OR)\" },\n ]}\n value={combinator}\n onChange={(v) =>\n state.setConditionalBehavior(\n objectPath,\n v === \"anyOf\" ? \"anyOf\" : \"allOf\",\n )\n }\n clearable={false}\n disabled={disabled}\n />\n\n <FormSelect\n id=\"condition-field\"\n name=\"field\"\n label=\"When property\"\n options={fieldOptions}\n value={condition.field || null}\n onChange={(v) => commit({ ...condition, field: v ?? \"\" })}\n placeholder=\"Select a property...\"\n clearable={false}\n disabled={disabled}\n />\n\n <FormSelect\n id=\"condition-operator\"\n name=\"operator\"\n label=\"Operator\"\n options={OPERATOR_OPTIONS}\n value={condition.operator}\n onChange={(v) =>\n commit({ ...condition, operator: (v as ConditionOperator) ?? \"=\" })\n }\n clearable={false}\n disabled={disabled}\n />\n\n {needsValue && (\n <OperatorValueInput\n id=\"condition-value\"\n cacheKey={`${node.path.length}:${condition.field}:${condition.operator}`}\n value={condition.value}\n onCommit={(v) => commit({ ...condition, value: v })}\n disabled={disabled || !condition.field}\n />\n )}\n </div>\n );\n}\n","/**\n * RuleEditor -- authors a field's declarative presentation rule (x-ui-rule):\n * show / hide / enable / disable this field based on another field's value.\n *\n * Unlike if/then/else, the field stays declared at its own position; the rule\n * only toggles presentation. The condition references another field by JSON\n * Pointer (scope) and an operator + value. The rule is stored on the property\n * and evaluated live by the renderer (evaluateUiRule).\n */\n\nimport React, { useMemo } from \"react\";\nimport type { DesignerState } from \"../hooks/useDesignerState\";\nimport type { PropertyNode } from \"../model/view\";\nimport { RuleFields } from \"./RuleFields\";\nimport { FIELD_EFFECT_OPTIONS } from \"./ruleEffects\";\nimport { scopePointers } from \"./ruleScopes\";\n\nexport interface RuleEditorProps {\n node: PropertyNode;\n state: DesignerState;\n}\n\nexport function RuleEditor({\n node,\n state,\n}: RuleEditorProps): React.ReactElement {\n const scopes = useMemo(() => scopePointers(state, node), [state, node]);\n return (\n <div className=\"space-y-3\">\n <p className=\"text-xs text-muted-foreground\">\n Toggle this field's visibility (or enabled state) based on another\n field's value. The field keeps its position in the form.\n </p>\n <RuleFields\n rule={node.property[\"x-ui-rule\"]}\n scopes={scopes}\n effects={FIELD_EFFECT_OPTIONS}\n idPrefix=\"rule\"\n disabled={state.readOnly}\n onChange={(rule) =>\n state.updateProperty(node.path, { \"x-ui-rule\": rule })\n }\n />\n </div>\n );\n}\n","/**\n * Scope candidates for the Rule tab.\n *\n * Pure helpers, kept out of the component file so they can be tested directly\n * (and so the component module only exports a component).\n */\nimport type { JsonSchemaProperty } from \"@petrarca/sonnet-core/schema\";\nimport type { PropertyNode } from \"../model/view\";\nimport type { DesignerState } from \"../hooks/useDesignerState\";\nimport type { ScopeOption } from \"./RuleFields\";\n\n/**\n * The node's own location in the form data as a JSON Pointer prefix, or\n * undefined when it has no stable one.\n *\n * Only `prop` segments correspond to data. A `def` node lives in `$defs` and is\n * placed wherever a `$ref` embeds it, so it has no fixed data location -- and a\n * `branch`/`condition`/`slot` crossing is a schema construct, not a data step.\n */\nfunction dataPointerPrefix(node: PropertyNode): string | undefined {\n let prefix = \"\";\n // Exclude the last segment: that is the node itself, not its container.\n for (let i = 0; i < node.path.length - 1; i++) {\n const seg = node.path[i];\n if (seg.kind !== \"prop\") return undefined;\n prefix += `/${seg.key}`;\n }\n return prefix;\n}\n\n/**\n * Scope candidates as root-anchored JSON Pointers.\n *\n * x-ui-rule scopes are read from the top of the form at every depth, so a\n * candidate must carry its full path -- a nested field's sibling is\n * `/address/city`, not `/city`. Top-level fields are always offered, since a\n * rule anywhere may reference them; the node's own siblings are added when it\n * has a stable data location.\n *\n * Deeper or cross-branch pointers can still be hand-authored in the source tab.\n */\nexport function scopePointers(\n state: DesignerState,\n node: PropertyNode,\n): ScopeOption[] {\n const options = new Map<string, ScopeOption>();\n const prefix = dataPointerPrefix(node);\n const selfPointer =\n prefix === undefined ? undefined : `${prefix}/${node.key}`;\n\n const add = (pointer: string, prop: JsonSchemaProperty) => {\n if (pointer === selfPointer) return; // a rule cannot depend on itself\n if (!options.has(pointer))\n options.set(pointer, { pointer, type: prop.type });\n };\n\n for (const [k, prop] of Object.entries(state.schema.properties ?? {})) {\n add(`/${k}`, prop);\n }\n\n if (prefix) {\n const siblings = findParentProperties(state, node);\n for (const [k, prop] of Object.entries(siblings ?? {})) {\n add(`${prefix}/${k}`, prop);\n }\n }\n\n return [...options.values()];\n}\n\n// The properties map of the node's parent container (best-effort; root when top).\nfunction findParentProperties(\n state: DesignerState,\n node: PropertyNode,\n): Record<string, JsonSchemaProperty> | undefined {\n // Walk the schema following prop segments up to (but excluding) the last.\n let props: Record<string, JsonSchemaProperty> | undefined =\n state.schema.properties;\n for (let i = 0; i < node.path.length - 1; i++) {\n const seg = node.path[i];\n if (seg.kind !== \"prop\" || !props) return undefined;\n const next: JsonSchemaProperty | undefined = props[seg.key];\n props = next?.type === \"array\" ? next.items?.properties : next?.properties;\n if (!props) return undefined;\n }\n return props;\n}\n","/**\n * ReferenceTab -- the Data tab for a `$ref` node. In JSON Schema 2020-12,\n * annotation keywords alongside `$ref` apply at the referencing site, so a\n * reference may carry local overrides (title, description, default, required)\n * on top of the shared definition. Structural type/validation belongs to the\n * definition and is edited there; here we offer only the overrides plus a\n * \"Stop referencing\" action that converts the property back to a concrete type.\n */\n\nimport React, { useMemo, useRef } from \"react\";\nimport { JsonSchemaFormRenderer } from \"@petrarca/sonnet-forms\";\nimport { Button } from \"@petrarca/sonnet-ui\";\nimport type { JsonSchemaProperty } from \"@petrarca/sonnet-core/schema\";\nimport type { DesignerState } from \"../hooks/useDesignerState\";\nimport type { PropertyNode } from \"../model/view\";\nimport { pathKey } from \"../model/paths\";\nimport { buildReferenceMetaSchema } from \"./metaSchemas\";\n\nexport interface ReferenceTabProps {\n node: PropertyNode;\n state: DesignerState;\n}\n\n// The override values a reference carries at its use site.\ninterface RefOverrides {\n title?: string;\n description?: string;\n default?: string;\n required: boolean;\n}\n\n// The reference's own overrides (from node.property, which keeps the $ref +\n// sibling keys -- not the resolved target).\nfunction toOverrides(\n prop: JsonSchemaProperty,\n required: boolean,\n): RefOverrides {\n return {\n title: prop.title,\n description: prop.description,\n // Coerce to string for the text field; non-string defaults (number, boolean)\n // are serialised and written back as strings -- v1 limitation.\n default: prop.default == null ? undefined : String(prop.default),\n required,\n };\n}\n\n// The property patch for changed override values; empty strings clear the key.\nfunction toPatch(values: RefOverrides): Partial<JsonSchemaProperty> {\n const str = (v: unknown) =>\n typeof v === \"string\" && v.length > 0 ? v : undefined;\n return {\n title: str(values.title),\n description: str(values.description),\n default: str(values.default),\n };\n}\n\nexport function ReferenceTab({\n node,\n state,\n}: ReferenceTabProps): React.ReactElement {\n const schema = useMemo(() => buildReferenceMetaSchema(), []);\n const values = useMemo(\n () => toOverrides(node.property, node.required),\n [node.property, node.required],\n );\n const prevRef = useRef<RefOverrides>(values);\n prevRef.current = values;\n\n const handleChange = (data: Record<string, unknown>) => {\n const next = data as unknown as RefOverrides;\n const prev = prevRef.current;\n // Required lives on the parent's required[], not on the property.\n if (next.required !== prev.required) {\n state.setRequired(node.path, !!next.required);\n return;\n }\n state.updateProperty(node.path, toPatch(next));\n };\n\n return (\n <div className=\"space-y-4\">\n <p className=\"text-sm text-muted-foreground\">\n References <span className=\"font-medium\">{node.reference}</span>. Its\n fields come from a shared definition (read-only here -- edit the\n definition to change all usages). The values below override the label,\n help text, and default for this usage only.\n </p>\n <JsonSchemaFormRenderer\n key={pathKey(node.path)}\n schema={schema}\n data={values as unknown as Record<string, unknown>}\n onChange={handleChange}\n deferStateUpdates\n showActions={false}\n showExtraProperties={false}\n readOnly={state.readOnly}\n />\n {!state.readOnly && state.canEditProperty(node.path) && (\n <div className=\"border-t pt-3\">\n <Button\n variant=\"outline\"\n size=\"sm\"\n onClick={() => state.changePropertyType(node.path, \"string\")}\n >\n Stop referencing\n </Button>\n <p className=\"mt-1 text-xs text-muted-foreground\">\n Removes the reference and turns this into an editable property.\n </p>\n </div>\n )}\n </div>\n );\n}\n"],"mappings":";AAoBA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AA2BA,SAAS,cAAc,KAAsB;AAClD,SAAO,iCAAiC,KAAK,GAAG;AAClD;AAGO,SAAS,KAAK,KAA0B;AAC7C,SAAO,EAAE,MAAM,QAAQ,IAAI;AAC7B;AAGO,SAAS,OAAO,OAA4B;AACjD,SAAO,EAAE,MAAM,UAAU,MAAM;AACjC;AAGO,SAAS,UACd,OACA,aAAkC,SACrB;AACb,SAAO,EAAE,MAAM,aAAa,YAAY,MAAM;AAChD;AAGO,SAAS,KAAK,MAA6B;AAChD,SAAO,EAAE,MAAM,QAAQ,MAAM,KAAK;AACpC;AAGO,SAAS,IAAI,MAA2B;AAC7C,SAAO,EAAE,MAAM,OAAO,KAAK;AAC7B;AAOA,IAAM,M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AAAA;AAAA,IACF;AAAA,KACF;AAEJ;","names":["prop","isOneOf","prop","slot","prop","row","prop","prop","escapeToken","prop","useEffect","useState","IconButton","useMemo","useRef","useState","jsx","jsxs","useMemo","useState","useRef","isConditionalMember","isOneOf","useMemo","useState","JsonSchemaFormRenderer","useMemo","prop","jsx","useMemo","useMemo","useState","cn","Input","IconButton","FormSelect","JsonSchemaFormRenderer","Plus","Trash2","ChevronUp","ChevronDown","ChevronRight","useEffect","useMemo","useState","FormSelect","condition","Input","jsx","jsxs","Fragment","jsx","jsxs","useState","useEffect","useMemo","FormSelect","Fragment","jsx","jsxs","prop","JsonSchemaFormRenderer","useMemo","useState","Plus","FormSelect","cn","ChevronDown","ChevronRight","Input","IconButton","Trash2","ChevronUp","useMemo","useEffect","useRef","useState","Button","jsx","jsxs","jsx","useMemo","Fragment","jsx","jsxs","useState","useMemo","JsonSchemaFormRenderer","useEffect","useMemo","useRef","useState","Tabs","TabsList","TabsTrigger","TabsContent","Input","IconButton","Check","useMemo","useRef","JsonSchemaFormRenderer","isOneOf","isContainer","prop","jsx","jsxs","useMemo","useRef","JsonSchemaFormRenderer","useMemo","JsonSchemaFormRenderer","JsonEditor","FormSelect","jsx","jsxs","JsonSchemaFormRenderer","JsonEditor","useMemo","FormSelect","useEffect","useState","Input","IconButton","Button","Plus","Trash2","jsx","jsxs","useState","useEffect","Input","IconButton","Trash2","Button","Plus","useMemo","JsonEditor","FormSelect","JsonSchemaFormRenderer","jsx","jsxs","useMemo","FormSelect","JsonSchemaFormRenderer","JsonEditor","useMemo","FormSelect","jsx","jsxs","condition","useMemo","FormSelect","useMemo","prop","jsx","jsxs","useMemo","useMemo","useRef","JsonSchemaFormRenderer","Button","jsx","jsxs","prop","useMemo","useRef","JsonSchemaFormRenderer","Button","jsx","jsxs","useState","useRef","useEffect","IconButton","Input","Check","Tabs","TabsList","TabsTrigger","TabsContent","useMemo","Fragment","jsx","jsxs","useState","useEffect","IconButton"]}
|