@aglyn/besigner-ui 1.23.1 → 1.25.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.
@@ -76,6 +76,12 @@ export interface PropertyBindingOptions {
76
76
  tokenLabelContext?: TokenLabelContext;
77
77
  /** Whose properties these are, for what an empty picker says. */
78
78
  owner?: 'component' | 'layout';
79
+ /**
80
+ * Record fields this field can follow inside a repeat (AGL-4190): an Icon
81
+ * picker, a record's icon field. Offered beside any properties, and on
82
+ * their own outside a component editor.
83
+ */
84
+ recordBindings?: readonly BindingOption[];
79
85
  }
80
86
  /**
81
87
  * The field, wrapped to take a property binding when it can, or unchanged.
@@ -106,6 +112,8 @@ export interface PropertyBindingFieldProps {
106
112
  /** Those props' kinds in the panel's words, e.g. `Choice`. */
107
113
  bindingKinds?: string;
108
114
  bindingEmptyText?: string;
115
+ /** Whether record fields are among the options (AGL-4190). */
116
+ bindingRecordFields?: boolean;
109
117
  tokenLabelContext?: TokenLabelContext;
110
118
  FormFieldGridProps?: FormFieldGridProps;
111
119
  }
@@ -16,7 +16,7 @@
16
16
  */ import { _ as _extends } from "@swc/helpers/_/_extends";
17
17
  import { _ as _object_without_properties_loose } from "@swc/helpers/_/_object_without_properties_loose";
18
18
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
19
- import { attributeFieldValueShape, matchComponentPropToken, REUSABLE_PROP_KINDS, reusablePropBindsToField, unofferedChoiceValues } from "@aglyn/aglyn";
19
+ import { attributeFieldValueShape, matchComponentPropToken, matchWholeItemToken, REUSABLE_PROP_KINDS, reusablePropBindsToField, unofferedChoiceValues } from "@aglyn/aglyn";
20
20
  import { FormFieldGrid, useFieldApi } from "@aglyn/shared-ui-jsx-forms";
21
21
  import { Box, ButtonBase, TextField } from "@mui/material";
22
22
  import { forwardRef, useMemo, useState } from "react";
@@ -94,22 +94,26 @@ import { TokenPillPopover, tokenPillContainerSx } from "./token-pill.component.j
94
94
  * control to fall back to is unknown, since a wrapper with nothing to render
95
95
  * would blank the field.
96
96
  */ export function withPropertyBinding(field, options) {
97
- const { declaredComponent, declaredField, componentProps, control, tokenLabelContext, owner = 'component' } = options;
98
- if (!componentProps || !control) return field;
97
+ const { declaredComponent, declaredField, componentProps, control, tokenLabelContext, owner = 'component', recordBindings = [] } = options;
98
+ if (!componentProps && !recordBindings.length || !control) return field;
99
99
  const declared = _extends({}, declaredField != null ? declaredField : field, {
100
100
  component: declaredComponent
101
101
  });
102
102
  if (attributeFieldValueShape(declared) === undefined) return field;
103
103
  if (field['isReadOnly'] || field['isDisabled']) return field;
104
- const bindable = componentProps.filter((prop)=>reusablePropBindsToField(prop, declared));
104
+ const bindable = (componentProps != null ? componentProps : []).filter((prop)=>reusablePropBindsToField(prop, declared));
105
105
  const kinds = propertyKindsBindableTo(declared);
106
106
  return _extends({}, field, {
107
107
  component: PROPERTY_BINDING_FIELD_COMPONENT,
108
108
  bindingControl: control,
109
- bindingOptions: componentPropBindingOptions(bindable, owner),
109
+ bindingOptions: [
110
+ ...componentPropBindingOptions(bindable, owner),
111
+ ...recordBindings
112
+ ],
110
113
  bindingProps: bindable,
111
114
  bindingKinds: kinds,
112
- bindingEmptyText: `This ${owner} has no ${kinds || 'matching'} properties yet. Add one ` + 'under File ▸ Properties…, then bind it here.',
115
+ bindingRecordFields: recordBindings.length > 0,
116
+ bindingEmptyText: componentProps ? `This ${owner} has no ${kinds || 'matching'} properties yet. Add one ` + 'under File ▸ Properties…, then bind it here.' : 'The repeated records have no field of this kind.',
113
117
  tokenLabelContext
114
118
  });
115
119
  }
@@ -177,6 +181,16 @@ import { TokenPillPopover, tokenPillContainerSx } from "./token-pill.component.j
177
181
  * some of the property's choices are values the dropdown does not offer.
178
182
  */ export function describePropertyBinding(options) {
179
183
  const { token, resolved, bindingProps, bindingKinds, fieldOptions } = options;
184
+ if (matchWholeItemToken(token) != null) {
185
+ // A record field (AGL-4190): each copy of the repeat follows its own record.
186
+ return resolved.known ? {
187
+ text: `Each copy shows its own record's ${resolved.label}.`,
188
+ error: false
189
+ } : {
190
+ text: 'The repeated records have no field by that name, so this shows ' + 'nothing. Bind a field they have, or remove the binding.',
191
+ error: true
192
+ };
193
+ }
180
194
  const name = matchComponentPropToken(token);
181
195
  const prop = (bindingProps != null ? bindingProps : []).find((entry)=>(entry == null ? void 0 : entry.name) === name);
182
196
  if (!prop) {
@@ -212,12 +226,13 @@ import { TokenPillPopover, tokenPillContainerSx } from "./token-pill.component.j
212
226
  * autosave commits a binding exactly as it commits a tick.
213
227
  */ export function PropertyBindingField(props) {
214
228
  var _fieldProps_FormFieldGridProps;
215
- const { bindingControl, bindingOptions = [], bindingProps, bindingKinds, bindingEmptyText, tokenLabelContext = {} } = props, fieldProps = _object_without_properties_loose(props, [
229
+ const { bindingControl, bindingOptions = [], bindingProps, bindingKinds, bindingEmptyText, bindingRecordFields, tokenLabelContext = {} } = props, fieldProps = _object_without_properties_loose(props, [
216
230
  "bindingControl",
217
231
  "bindingOptions",
218
232
  "bindingProps",
219
233
  "bindingKinds",
220
234
  "bindingEmptyText",
235
+ "bindingRecordFields",
221
236
  "tokenLabelContext"
222
237
  ]);
223
238
  const { input } = useFieldApi({
@@ -225,14 +240,15 @@ import { TokenPillPopover, tokenPillContainerSx } from "./token-pill.component.j
225
240
  });
226
241
  const [menuAnchor, setMenuAnchor] = useState(null);
227
242
  const [pillAnchor, setPillAnchor] = useState(null);
228
- const bound = matchComponentPropToken(input.value) != null ? String(input.value).trim() : null;
243
+ const bound = matchComponentPropToken(input.value) != null || matchWholeItemToken(input.value) != null ? String(input.value).trim() : null;
229
244
  const resolved = useMemo(()=>bound ? resolveTokenLabel(bound, tokenLabelContext) : undefined, [
230
245
  bound,
231
246
  tokenLabelContext
232
247
  ]);
233
248
  const labelText = typeof fieldProps.label === 'string' && fieldProps.label ? fieldProps.label : undefined;
249
+ const target = bindingRecordFields ? (bindingProps == null ? void 0 : bindingProps.length) ? 'property or record field' : 'record field' : 'property';
234
250
  const bind = {
235
- label: bound ? `Change the property ${labelText != null ? labelText : 'this field'} is bound to` : `Bind ${labelText != null ? labelText : 'this field'} to a property`,
251
+ label: bound ? `Change the ${target} ${labelText != null ? labelText : 'this field'} is bound to` : `Bind ${labelText != null ? labelText : 'this field'} to a ${target}`,
236
252
  onOpen: setMenuAnchor
237
253
  };
238
254
  const gridProps = _extends({}, (_fieldProps_FormFieldGridProps = fieldProps.FormFieldGridProps) != null ? _fieldProps_FormFieldGridProps : {}, {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/besigner/feature/designer/src/lib/components/property-binding-field.component.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type * as Aglyn from '@aglyn/aglyn'\nimport {\n attributeFieldValueShape,\n type BindableAttributeField,\n matchComponentPropToken,\n REUSABLE_PROP_KINDS,\n reusablePropBindsToField,\n unofferedChoiceValues,\n} from '@aglyn/aglyn'\nimport {\n type FieldBindAction,\n FormFieldGrid,\n type FormFieldGridProps,\n useFieldApi,\n} from '@aglyn/shared-ui-jsx-forms'\nimport { Box, ButtonBase, TextField } from '@mui/material'\nimport {\n type ComponentType,\n type FocusEvent,\n forwardRef,\n type MouseEvent,\n type ReactNode,\n useMemo,\n useState,\n} from 'react'\n\nimport type { BindingOption } from '../contexts/binding-picker-context'\nimport { componentPropBindingOptions } from '../hooks/use-insert-token-options'\nimport {\n TOKEN_PILL_ATTR,\n TOKEN_PILL_GROUP_ATTR,\n} from '../utils/token-editable-dom'\nimport {\n type ResolvedTokenLabel,\n resolveTokenLabel,\n type TokenLabelContext,\n} from '../utils/token-segments'\nimport { InsertTokenMenu } from './insert-token-menu.component'\nimport { TokenPillPopover, tokenPillContainerSx } from './token-pill.component'\n\n/**\n * Binding a field that has no text to type a token into.\n *\n * A free-text attribute has always taken `{{prop.headline}}`: the token is\n * typed, or picked with the `{}` in the box, and substitution does the rest.\n * A switch, a checkbox, a dropdown or an icon picker has no text to type into,\n * so inside a reusable component it could only ever hold the component's own\n * value — and a property of the matching kind had nothing to drive.\n *\n * This wraps such a field, inside a component editor only. Unbound, it is the\n * field exactly as before, with a `{}` among its corner controls. Bound, the\n * control gives way to the property it is bound to, drawn as the pill a text\n * field would draw — because the control would otherwise go on showing a\n * value the page no longer uses.\n *\n * The stored value is the same exact `{{prop.<name>}}` token a text field\n * holds, so the graft needs nothing new to find it, and a binding to a\n * property of the wrong kind is simply never offered.\n */\n\n/** Mapper key for {@link PropertyBindingField} (editor-internal, never persisted). */\nexport const PROPERTY_BINDING_FIELD_COMPONENT = 'aglyn-property-binding-field'\n\n/**\n * The names of the property kinds a declared field can be bound to, in the\n * panel's own words — `Yes / no or Checkbox` for a switch, `Color` for a color\n * picker — for the sentences that tell an author what to add.\n *\n * Every kind is tried as it can be declared (bare, with answers, taking\n * several), so a list-holding dropdown names the kinds that hold lists.\n */\nexport function propertyKindsBindableTo(\n declared: BindableAttributeField,\n): string {\n const labels = (Object.keys(REUSABLE_PROP_KINDS) as Aglyn.ReusableComponentPropType[])\n .filter((type) =>\n [\n { type },\n { type, options: [{ value: 'a' }] },\n { type, options: [{ value: 'a' }], settings: { isMulti: true } },\n ].some((candidate) => reusablePropBindsToField(candidate, declared)),\n )\n .map((type) => REUSABLE_PROP_KINDS[type].label)\n if (labels.length <= 1) return labels[0] ?? ''\n return `${labels.slice(0, -1).join(', ')} or ${labels[labels.length - 1]}`\n}\n\n/** A component-mapper entry: a component, or `{ component, ...defaults }`. */\nexport type PropertyBindingControl =\n | ComponentType<any>\n | { component: ComponentType<any>; [key: string]: unknown }\n\nexport interface PropertyBindingOptions {\n /** The attribute type the component schema declares for this field. */\n declaredComponent: unknown\n /**\n * The attribute as the schema declares it, for whether it holds one value\n * or several (`isMulti`, a checkbox's `options`). The field itself is read\n * when this is absent.\n */\n declaredField?: BindableAttributeField\n /**\n * The props the edited component declares, or `undefined` outside a\n * component editor — where `{{prop.*}}` resolves to nothing, so there is\n * nothing to bind to.\n */\n componentProps: readonly Aglyn.ReusableComponentProp[] | null | undefined\n /** The mapper entry this field renders with while unbound. */\n control: PropertyBindingControl | undefined\n /** Display-name inputs for the bound pill. */\n tokenLabelContext?: TokenLabelContext\n /** Whose properties these are, for what an empty picker says. */\n owner?: 'component' | 'layout'\n}\n\n/**\n * The field, wrapped to take a property binding when it can, or unchanged.\n *\n * Every field kind that holds a value can be bound (AGL-2893), to the\n * properties that hold the same shape of value (`reusablePropBindsToField`):\n * a switch to a Yes / no, a color picker to a Color, a dropdown that takes\n * several answers to a property that holds several.\n *\n * Unchanged outside a component or layout editor, for a free-text field — it\n * takes any property's token typed into it — for a read-only or disabled\n * field (a control that writes an unwritable field is a lie), and whenever the\n * control to fall back to is unknown, since a wrapper with nothing to render\n * would blank the field.\n */\nexport function withPropertyBinding<T extends Record<string, unknown>>(\n field: T,\n options: PropertyBindingOptions,\n): T {\n const {\n declaredComponent,\n declaredField,\n componentProps,\n control,\n tokenLabelContext,\n owner = 'component',\n } = options\n if (!componentProps || !control) return field\n const declared: BindableAttributeField = {\n ...(declaredField ?? field),\n component: declaredComponent,\n }\n if (attributeFieldValueShape(declared) === undefined) return field\n if (field['isReadOnly'] || field['isDisabled']) return field\n const bindable = componentProps.filter((prop) =>\n reusablePropBindsToField(prop, declared),\n )\n const kinds = propertyKindsBindableTo(declared)\n return {\n ...field,\n component: PROPERTY_BINDING_FIELD_COMPONENT,\n bindingControl: control,\n bindingOptions: componentPropBindingOptions(bindable, owner),\n bindingProps: bindable,\n bindingKinds: kinds,\n bindingEmptyText:\n `This ${owner} has no ${kinds || 'matching'} properties yet. Add one ` +\n 'under File ▸ Properties…, then bind it here.',\n tokenLabelContext,\n }\n}\n\n/** The mapper entry split into the component and the defaults it carries. */\nfunction splitControl(control: PropertyBindingControl | undefined): {\n Control: ComponentType<any> | undefined\n defaults: Record<string, unknown>\n} {\n if (!control) return { Control: undefined, defaults: {} }\n if (typeof control === 'object' && 'component' in control) {\n const { component, ...defaults } = control\n return { Control: component, defaults }\n }\n return { Control: control as ComponentType<any>, defaults: {} }\n}\n\ninterface BoundPropertyInputProps {\n token: string\n resolved: ResolvedTokenLabel\n onOpen: (anchor: HTMLElement) => void\n /** The field's own label, so the button says what it changes. */\n fieldLabel?: string\n // Injected by MUI InputBase:\n className?: string\n disabled?: boolean\n id?: string\n onFocus?: (event: FocusEvent<HTMLElement>) => void\n onBlur?: (event: FocusEvent<HTMLElement>) => void\n 'aria-describedby'?: string\n}\n\n/**\n * The bound property, drawn INSIDE a real outlined field so the label, notch,\n * helper text and focus ring are the ones every other attribute has.\n *\n * The pill is a button rather than the passive span a text field draws: here\n * it is the whole value, so it has to be reachable by keyboard, and pressing\n * it is how the binding is changed or removed.\n */\nconst BoundPropertyInput = forwardRef<HTMLButtonElement, BoundPropertyInputProps>(\n function BoundPropertyInput(props, ref) {\n const {\n token,\n resolved,\n onOpen,\n fieldLabel,\n className,\n disabled,\n id,\n onFocus,\n onBlur,\n 'aria-describedby': describedBy,\n } = props\n const pillAttributes = {\n [TOKEN_PILL_ATTR]: token,\n [TOKEN_PILL_GROUP_ATTR]: resolved.known ? resolved.group : 'unknown',\n }\n return (\n <Box\n className={className}\n sx={{ ...tokenPillContainerSx, display: 'flex', alignItems: 'center' }}\n >\n <ButtonBase\n ref={ref}\n id={id}\n disabled={disabled}\n aria-describedby={describedBy}\n aria-label={`${fieldLabel ? `${fieldLabel}: ` : ''}bound to ${resolved.label}. Change or remove the binding`}\n title={token}\n onFocus={onFocus}\n onBlur={onBlur}\n onClick={(event: MouseEvent<HTMLElement>) =>\n onOpen(event.currentTarget)\n }\n {...pillAttributes}\n >\n {resolved.label}\n </ButtonBase>\n </Box>\n )\n },\n)\n\nexport interface PropertyBindingFieldProps {\n [key: string]: unknown\n name: string\n label?: ReactNode\n help?: unknown\n description?: ReactNode\n helperText?: ReactNode\n bindingControl?: PropertyBindingControl\n bindingOptions?: BindingOption[]\n /** The declared props this field can be bound to. */\n bindingProps?: readonly Aglyn.ReusableComponentProp[]\n /** Those props' kinds in the panel's words, e.g. `Choice`. */\n bindingKinds?: string\n bindingEmptyText?: string\n tokenLabelContext?: TokenLabelContext\n FormFieldGridProps?: FormFieldGridProps\n}\n\n/**\n * What a bound field says under the property it follows, and whether that is\n * a problem.\n *\n * Three ways a binding can be wrong while still looking bound, each named in\n * words an author can act on: the property is gone (it was renamed or\n * removed, so nothing substitutes), the property is the wrong kind (a token\n * written some other way than this field's picker), or — for a dropdown —\n * some of the property's choices are values the dropdown does not offer.\n */\nexport function describePropertyBinding(options: {\n token: string\n resolved: ResolvedTokenLabel\n bindingProps?: readonly Aglyn.ReusableComponentProp[]\n bindingKinds?: string\n fieldOptions?: unknown\n}): { text: string; error: boolean } {\n const { token, resolved, bindingProps, bindingKinds, fieldOptions } = options\n const name = matchComponentPropToken(token)\n const prop = (bindingProps ?? []).find((entry) => entry?.name === name)\n if (!prop) {\n return resolved.known\n ? {\n text:\n `${resolved.label} is not a ${bindingKinds || 'matching'} ` +\n 'property, so it cannot set this field. Bind one that is, or ' +\n 'remove the binding.',\n error: true,\n }\n : {\n text:\n 'This component declares no property by that name, so pages ' +\n 'cannot set it. Bind a property it declares, or remove the ' +\n 'binding.',\n error: true,\n }\n }\n const unoffered = unofferedChoiceValues(prop, fieldOptions)\n if (unoffered.length) {\n const offered = (Array.isArray(fieldOptions) ? fieldOptions : [])\n .map((option) => {\n const { value, label } = (option ?? {}) as {\n value?: unknown\n label?: unknown\n }\n const text = String(value ?? '')\n return label != null && String(label) !== text\n ? `${String(label)} (${text})`\n : text\n })\n .filter(Boolean)\n return {\n text:\n `This field does not offer ${unoffered.join(', ')}, so a page that ` +\n `chooses ${unoffered.length === 1 ? 'it' : 'one of those'} gets the ` +\n `field's own default. Give ${resolved.label} values from: ` +\n `${offered.join(', ')}.`,\n error: true,\n }\n }\n return {\n text: `Each page sets this with the ${resolved.label} property.`,\n error: false,\n }\n}\n\n/**\n * The data-driven-forms field registered as\n * {@link PROPERTY_BINDING_FIELD_COMPONENT}. The token flows through\n * react-final-form like any other value, so the Attributes panel's debounced\n * autosave commits a binding exactly as it commits a tick.\n */\nexport function PropertyBindingField(props: PropertyBindingFieldProps) {\n const {\n bindingControl,\n bindingOptions = [],\n bindingProps,\n bindingKinds,\n bindingEmptyText,\n tokenLabelContext = {},\n ...fieldProps\n } = props\n const { input } = useFieldApi({ name: fieldProps.name } as never) as {\n input: { value: unknown; onChange: (value: unknown) => void }\n }\n const [menuAnchor, setMenuAnchor] = useState<HTMLElement | null>(null)\n const [pillAnchor, setPillAnchor] = useState<HTMLElement | null>(null)\n\n const bound =\n matchComponentPropToken(input.value) != null\n ? String(input.value).trim()\n : null\n const resolved = useMemo(\n () => (bound ? resolveTokenLabel(bound, tokenLabelContext) : undefined),\n [bound, tokenLabelContext],\n )\n const labelText =\n typeof fieldProps.label === 'string' && fieldProps.label\n ? fieldProps.label\n : undefined\n const bind: FieldBindAction = {\n label: bound\n ? `Change the property ${labelText ?? 'this field'} is bound to`\n : `Bind ${labelText ?? 'this field'} to a property`,\n onOpen: setMenuAnchor,\n }\n const gridProps: FormFieldGridProps = {\n ...(fieldProps.FormFieldGridProps ?? {}),\n bind,\n }\n\n const { Control, defaults } = splitControl(bindingControl)\n\n const menus = (\n <>\n <InsertTokenMenu\n anchorEl={menuAnchor}\n open={Boolean(menuAnchor)}\n onClose={() => setMenuAnchor(null)}\n options={bindingOptions}\n emptyText={bindingEmptyText}\n onInsert={(token) => {\n setMenuAnchor(null)\n input.onChange(token)\n }}\n />\n <TokenPillPopover\n anchorEl={pillAnchor}\n token={bound ?? ''}\n onClose={() => setPillAnchor(null)}\n onReplace={() => {\n setMenuAnchor(pillAnchor)\n setPillAnchor(null)\n }}\n onRemove={() => {\n setPillAnchor(null)\n // Unset rather than `false` or `''`: the element goes back to its\n // own default, which is what it rendered before it was bound.\n input.onChange(undefined)\n }}\n />\n </>\n )\n\n if (bound && resolved) {\n const described = describePropertyBinding({\n token: bound,\n resolved,\n bindingProps,\n bindingKinds,\n fieldOptions: fieldProps['options'],\n })\n return (\n <>\n <FormFieldGrid\n help={fieldProps.help as FormFieldGridProps['help']}\n {...gridProps}\n >\n <TextField\n fullWidth\n label={fieldProps.label}\n value=\"\"\n helperText={described.text}\n error={described.error}\n slotProps={{\n inputLabel: { shrink: true },\n input: {\n readOnly: true,\n inputComponent: BoundPropertyInput as never,\n inputProps: {\n token: bound,\n resolved,\n fieldLabel: labelText,\n onOpen: setPillAnchor,\n },\n },\n }}\n />\n </FormFieldGrid>\n {menus}\n </>\n )\n }\n\n if (!Control) return null\n return (\n <>\n <Control {...defaults} {...fieldProps} FormFieldGridProps={gridProps} />\n {menus}\n </>\n )\n}\nPropertyBindingField.displayName = 'PropertyBindingField'\n\nexport default PropertyBindingField\n"],"names":["attributeFieldValueShape","matchComponentPropToken","REUSABLE_PROP_KINDS","reusablePropBindsToField","unofferedChoiceValues","FormFieldGrid","useFieldApi","Box","ButtonBase","TextField","forwardRef","useMemo","useState","componentPropBindingOptions","TOKEN_PILL_ATTR","TOKEN_PILL_GROUP_ATTR","resolveTokenLabel","InsertTokenMenu","TokenPillPopover","tokenPillContainerSx","PROPERTY_BINDING_FIELD_COMPONENT","propertyKindsBindableTo","declared","labels","Object","keys","filter","type","options","value","settings","isMulti","some","candidate","map","label","length","slice","join","withPropertyBinding","field","declaredComponent","declaredField","componentProps","control","tokenLabelContext","owner","component","undefined","bindable","prop","kinds","bindingControl","bindingOptions","bindingProps","bindingKinds","bindingEmptyText","splitControl","Control","defaults","BoundPropertyInput","props","ref","token","resolved","onOpen","fieldLabel","className","disabled","id","onFocus","onBlur","describedBy","pillAttributes","known","group","sx","display","alignItems","aria-describedby","aria-label","title","onClick","event","currentTarget","describePropertyBinding","fieldOptions","name","find","entry","text","error","unoffered","offered","Array","isArray","option","String","Boolean","PropertyBindingField","fieldProps","input","menuAnchor","setMenuAnchor","pillAnchor","setPillAnchor","bound","trim","labelText","bind","gridProps","FormFieldGridProps","menus","anchorEl","open","onClose","emptyText","onInsert","onChange","onReplace","onRemove","described","help","fullWidth","helperText","slotProps","inputLabel","shrink","readOnly","inputComponent","inputProps","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;;;AAGD,SACEA,wBAAwB,EAExBC,uBAAuB,EACvBC,mBAAmB,EACnBC,wBAAwB,EACxBC,qBAAqB,QAChB,eAAc;AACrB,SAEEC,aAAa,EAEbC,WAAW,QACN,6BAA4B;AACnC,SAASC,GAAG,EAAEC,UAAU,EAAEC,SAAS,QAAQ,gBAAe;AAC1D,SAGEC,UAAU,EAGVC,OAAO,EACPC,QAAQ,QACH,QAAO;AAGd,SAASC,2BAA2B,QAAQ,uCAAmC;AAC/E,SACEC,eAAe,EACfC,qBAAqB,QAChB,iCAA6B;AACpC,SAEEC,iBAAiB,QAEZ,6BAAyB;AAChC,SAASC,eAAe,QAAQ,mCAA+B;AAC/D,SAASC,gBAAgB,EAAEC,oBAAoB,QAAQ,4BAAwB;AAE/E;;;;;;;;;;;;;;;;;;CAkBC,GAED,oFAAoF,GACpF,OAAO,MAAMC,mCAAmC,+BAA8B;AAE9E;;;;;;;CAOC,GACD,OAAO,SAASC,wBACdC,QAAgC;QAWDC;IAT/B,MAAMA,SAAS,AAACC,OAAOC,IAAI,CAACvB,qBACzBwB,MAAM,CAAC,CAACC,OACP;YACE;gBAAEA;YAAK;YACP;gBAAEA;gBAAMC,SAAS;oBAAC;wBAAEC,OAAO;oBAAI;iBAAE;YAAC;YAClC;gBAAEF;gBAAMC,SAAS;oBAAC;wBAAEC,OAAO;oBAAI;iBAAE;gBAAEC,UAAU;oBAAEC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,cAAcC;oBACdC,cAAc;gBAChB;gBACAe,UAAU;oBACRf,cAAc;oBACd,kEAAkE;oBAClE,8DAA8D;oBAC9DJ,MAAMiB,QAAQ,CAACtE;gBACjB;;;;IAKN,IAAI0D,SAAS1C,UAAU;QACrB,MAAMyD,YAAYpC,wBAAwB;YACxCtB,OAAO2C;YACP1C;YACAV;YACAC;YACA+B,cAAcc,UAAU,CAAC,UAAU;QACrC;QACA,qBACE;;8BACE,KAAC/F;oBACCqH,MAAMtB,WAAWsB,IAAI;mBACjBZ;8BAEJ,cAAA,KAACrG;wBACCkH,SAAS;wBACTxF,OAAOiE,WAAWjE,KAAK;wBACvBN,OAAM;wBACN+F,YAAYH,UAAU/B,IAAI;wBAC1BC,OAAO8B,UAAU9B,KAAK;wBACtBkC,WAAW;4BACTC,YAAY;gCAAEC,QAAQ;4BAAK;4BAC3B1B,OAAO;gCACL2B,UAAU;gCACVC,gBAAgBrE;gCAChBsE,YAAY;oCACVnE,OAAO2C;oCACP1C;oCACAE,YAAY0C;oCACZ3C,QAAQwC;gCACV;4BACF;wBACF;;;gBAGHO;;;IAGP;IAEA,IAAI,CAACtD,SAAS,OAAO;IACrB,qBACE;;0BACE,KAACA,sBAAYC,UAAcyC;gBAAYW,oBAAoBD;;YAC1DE;;;AAGP;AACAb,qBAAqBgC,WAAW,GAAG;AAEnC,eAAehC,qBAAoB"}
1
+ {"version":3,"sources":["../../../../../../../../libs/besigner/feature/designer/src/lib/components/property-binding-field.component.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type * as Aglyn from '@aglyn/aglyn'\nimport {\n attributeFieldValueShape,\n type BindableAttributeField,\n matchComponentPropToken,\n matchWholeItemToken,\n REUSABLE_PROP_KINDS,\n reusablePropBindsToField,\n unofferedChoiceValues,\n} from '@aglyn/aglyn'\nimport {\n type FieldBindAction,\n FormFieldGrid,\n type FormFieldGridProps,\n useFieldApi,\n} from '@aglyn/shared-ui-jsx-forms'\nimport { Box, ButtonBase, TextField } from '@mui/material'\nimport {\n type ComponentType,\n type FocusEvent,\n forwardRef,\n type MouseEvent,\n type ReactNode,\n useMemo,\n useState,\n} from 'react'\n\nimport type { BindingOption } from '../contexts/binding-picker-context'\nimport { componentPropBindingOptions } from '../hooks/use-insert-token-options'\nimport {\n TOKEN_PILL_ATTR,\n TOKEN_PILL_GROUP_ATTR,\n} from '../utils/token-editable-dom'\nimport {\n type ResolvedTokenLabel,\n resolveTokenLabel,\n type TokenLabelContext,\n} from '../utils/token-segments'\nimport { InsertTokenMenu } from './insert-token-menu.component'\nimport { TokenPillPopover, tokenPillContainerSx } from './token-pill.component'\n\n/**\n * Binding a field that has no text to type a token into.\n *\n * A free-text attribute has always taken `{{prop.headline}}`: the token is\n * typed, or picked with the `{}` in the box, and substitution does the rest.\n * A switch, a checkbox, a dropdown or an icon picker has no text to type into,\n * so inside a reusable component it could only ever hold the component's own\n * value — and a property of the matching kind had nothing to drive.\n *\n * This wraps such a field, inside a component editor only. Unbound, it is the\n * field exactly as before, with a `{}` among its corner controls. Bound, the\n * control gives way to the property it is bound to, drawn as the pill a text\n * field would draw — because the control would otherwise go on showing a\n * value the page no longer uses.\n *\n * The stored value is the same exact `{{prop.<name>}}` token a text field\n * holds, so the graft needs nothing new to find it, and a binding to a\n * property of the wrong kind is simply never offered.\n */\n\n/** Mapper key for {@link PropertyBindingField} (editor-internal, never persisted). */\nexport const PROPERTY_BINDING_FIELD_COMPONENT = 'aglyn-property-binding-field'\n\n/**\n * The names of the property kinds a declared field can be bound to, in the\n * panel's own words — `Yes / no or Checkbox` for a switch, `Color` for a color\n * picker — for the sentences that tell an author what to add.\n *\n * Every kind is tried as it can be declared (bare, with answers, taking\n * several), so a list-holding dropdown names the kinds that hold lists.\n */\nexport function propertyKindsBindableTo(\n declared: BindableAttributeField,\n): string {\n const labels = (Object.keys(REUSABLE_PROP_KINDS) as Aglyn.ReusableComponentPropType[])\n .filter((type) =>\n [\n { type },\n { type, options: [{ value: 'a' }] },\n { type, options: [{ value: 'a' }], settings: { isMulti: true } },\n ].some((candidate) => reusablePropBindsToField(candidate, declared)),\n )\n .map((type) => REUSABLE_PROP_KINDS[type].label)\n if (labels.length <= 1) return labels[0] ?? ''\n return `${labels.slice(0, -1).join(', ')} or ${labels[labels.length - 1]}`\n}\n\n/** A component-mapper entry: a component, or `{ component, ...defaults }`. */\nexport type PropertyBindingControl =\n | ComponentType<any>\n | { component: ComponentType<any>; [key: string]: unknown }\n\nexport interface PropertyBindingOptions {\n /** The attribute type the component schema declares for this field. */\n declaredComponent: unknown\n /**\n * The attribute as the schema declares it, for whether it holds one value\n * or several (`isMulti`, a checkbox's `options`). The field itself is read\n * when this is absent.\n */\n declaredField?: BindableAttributeField\n /**\n * The props the edited component declares, or `undefined` outside a\n * component editor — where `{{prop.*}}` resolves to nothing, so there is\n * nothing to bind to.\n */\n componentProps: readonly Aglyn.ReusableComponentProp[] | null | undefined\n /** The mapper entry this field renders with while unbound. */\n control: PropertyBindingControl | undefined\n /** Display-name inputs for the bound pill. */\n tokenLabelContext?: TokenLabelContext\n /** Whose properties these are, for what an empty picker says. */\n owner?: 'component' | 'layout'\n /**\n * Record fields this field can follow inside a repeat (AGL-4190): an Icon\n * picker, a record's icon field. Offered beside any properties, and on\n * their own outside a component editor.\n */\n recordBindings?: readonly BindingOption[]\n}\n\n/**\n * The field, wrapped to take a property binding when it can, or unchanged.\n *\n * Every field kind that holds a value can be bound (AGL-2893), to the\n * properties that hold the same shape of value (`reusablePropBindsToField`):\n * a switch to a Yes / no, a color picker to a Color, a dropdown that takes\n * several answers to a property that holds several.\n *\n * Unchanged outside a component or layout editor, for a free-text field — it\n * takes any property's token typed into it — for a read-only or disabled\n * field (a control that writes an unwritable field is a lie), and whenever the\n * control to fall back to is unknown, since a wrapper with nothing to render\n * would blank the field.\n */\nexport function withPropertyBinding<T extends Record<string, unknown>>(\n field: T,\n options: PropertyBindingOptions,\n): T {\n const {\n declaredComponent,\n declaredField,\n componentProps,\n control,\n tokenLabelContext,\n owner = 'component',\n recordBindings = [],\n } = options\n if ((!componentProps && !recordBindings.length) || !control) return field\n const declared: BindableAttributeField = {\n ...(declaredField ?? field),\n component: declaredComponent,\n }\n if (attributeFieldValueShape(declared) === undefined) return field\n if (field['isReadOnly'] || field['isDisabled']) return field\n const bindable = (componentProps ?? []).filter((prop) =>\n reusablePropBindsToField(prop, declared),\n )\n const kinds = propertyKindsBindableTo(declared)\n return {\n ...field,\n component: PROPERTY_BINDING_FIELD_COMPONENT,\n bindingControl: control,\n bindingOptions: [\n ...componentPropBindingOptions(bindable, owner),\n ...recordBindings,\n ],\n bindingProps: bindable,\n bindingKinds: kinds,\n bindingRecordFields: recordBindings.length > 0,\n bindingEmptyText: componentProps\n ? `This ${owner} has no ${kinds || 'matching'} properties yet. Add one ` +\n 'under File ▸ Properties…, then bind it here.'\n : 'The repeated records have no field of this kind.',\n tokenLabelContext,\n }\n}\n\n/** The mapper entry split into the component and the defaults it carries. */\nfunction splitControl(control: PropertyBindingControl | undefined): {\n Control: ComponentType<any> | undefined\n defaults: Record<string, unknown>\n} {\n if (!control) return { Control: undefined, defaults: {} }\n if (typeof control === 'object' && 'component' in control) {\n const { component, ...defaults } = control\n return { Control: component, defaults }\n }\n return { Control: control as ComponentType<any>, defaults: {} }\n}\n\ninterface BoundPropertyInputProps {\n token: string\n resolved: ResolvedTokenLabel\n onOpen: (anchor: HTMLElement) => void\n /** The field's own label, so the button says what it changes. */\n fieldLabel?: string\n // Injected by MUI InputBase:\n className?: string\n disabled?: boolean\n id?: string\n onFocus?: (event: FocusEvent<HTMLElement>) => void\n onBlur?: (event: FocusEvent<HTMLElement>) => void\n 'aria-describedby'?: string\n}\n\n/**\n * The bound property, drawn INSIDE a real outlined field so the label, notch,\n * helper text and focus ring are the ones every other attribute has.\n *\n * The pill is a button rather than the passive span a text field draws: here\n * it is the whole value, so it has to be reachable by keyboard, and pressing\n * it is how the binding is changed or removed.\n */\nconst BoundPropertyInput = forwardRef<HTMLButtonElement, BoundPropertyInputProps>(\n function BoundPropertyInput(props, ref) {\n const {\n token,\n resolved,\n onOpen,\n fieldLabel,\n className,\n disabled,\n id,\n onFocus,\n onBlur,\n 'aria-describedby': describedBy,\n } = props\n const pillAttributes = {\n [TOKEN_PILL_ATTR]: token,\n [TOKEN_PILL_GROUP_ATTR]: resolved.known ? resolved.group : 'unknown',\n }\n return (\n <Box\n className={className}\n sx={{ ...tokenPillContainerSx, display: 'flex', alignItems: 'center' }}\n >\n <ButtonBase\n ref={ref}\n id={id}\n disabled={disabled}\n aria-describedby={describedBy}\n aria-label={`${fieldLabel ? `${fieldLabel}: ` : ''}bound to ${resolved.label}. Change or remove the binding`}\n title={token}\n onFocus={onFocus}\n onBlur={onBlur}\n onClick={(event: MouseEvent<HTMLElement>) =>\n onOpen(event.currentTarget)\n }\n {...pillAttributes}\n >\n {resolved.label}\n </ButtonBase>\n </Box>\n )\n },\n)\n\nexport interface PropertyBindingFieldProps {\n [key: string]: unknown\n name: string\n label?: ReactNode\n help?: unknown\n description?: ReactNode\n helperText?: ReactNode\n bindingControl?: PropertyBindingControl\n bindingOptions?: BindingOption[]\n /** The declared props this field can be bound to. */\n bindingProps?: readonly Aglyn.ReusableComponentProp[]\n /** Those props' kinds in the panel's words, e.g. `Choice`. */\n bindingKinds?: string\n bindingEmptyText?: string\n /** Whether record fields are among the options (AGL-4190). */\n bindingRecordFields?: boolean\n tokenLabelContext?: TokenLabelContext\n FormFieldGridProps?: FormFieldGridProps\n}\n\n/**\n * What a bound field says under the property it follows, and whether that is\n * a problem.\n *\n * Three ways a binding can be wrong while still looking bound, each named in\n * words an author can act on: the property is gone (it was renamed or\n * removed, so nothing substitutes), the property is the wrong kind (a token\n * written some other way than this field's picker), or — for a dropdown —\n * some of the property's choices are values the dropdown does not offer.\n */\nexport function describePropertyBinding(options: {\n token: string\n resolved: ResolvedTokenLabel\n bindingProps?: readonly Aglyn.ReusableComponentProp[]\n bindingKinds?: string\n fieldOptions?: unknown\n}): { text: string; error: boolean } {\n const { token, resolved, bindingProps, bindingKinds, fieldOptions } = options\n if (matchWholeItemToken(token) != null) {\n // A record field (AGL-4190): each copy of the repeat follows its own record.\n return resolved.known\n ? {\n text: `Each copy shows its own record's ${resolved.label}.`,\n error: false,\n }\n : {\n text:\n 'The repeated records have no field by that name, so this shows ' +\n 'nothing. Bind a field they have, or remove the binding.',\n error: true,\n }\n }\n const name = matchComponentPropToken(token)\n const prop = (bindingProps ?? []).find((entry) => entry?.name === name)\n if (!prop) {\n return resolved.known\n ? {\n text:\n `${resolved.label} is not a ${bindingKinds || 'matching'} ` +\n 'property, so it cannot set this field. Bind one that is, or ' +\n 'remove the binding.',\n error: true,\n }\n : {\n text:\n 'This component declares no property by that name, so pages ' +\n 'cannot set it. Bind a property it declares, or remove the ' +\n 'binding.',\n error: true,\n }\n }\n const unoffered = unofferedChoiceValues(prop, fieldOptions)\n if (unoffered.length) {\n const offered = (Array.isArray(fieldOptions) ? fieldOptions : [])\n .map((option) => {\n const { value, label } = (option ?? {}) as {\n value?: unknown\n label?: unknown\n }\n const text = String(value ?? '')\n return label != null && String(label) !== text\n ? `${String(label)} (${text})`\n : text\n })\n .filter(Boolean)\n return {\n text:\n `This field does not offer ${unoffered.join(', ')}, so a page that ` +\n `chooses ${unoffered.length === 1 ? 'it' : 'one of those'} gets the ` +\n `field's own default. Give ${resolved.label} values from: ` +\n `${offered.join(', ')}.`,\n error: true,\n }\n }\n return {\n text: `Each page sets this with the ${resolved.label} property.`,\n error: false,\n }\n}\n\n/**\n * The data-driven-forms field registered as\n * {@link PROPERTY_BINDING_FIELD_COMPONENT}. The token flows through\n * react-final-form like any other value, so the Attributes panel's debounced\n * autosave commits a binding exactly as it commits a tick.\n */\nexport function PropertyBindingField(props: PropertyBindingFieldProps) {\n const {\n bindingControl,\n bindingOptions = [],\n bindingProps,\n bindingKinds,\n bindingEmptyText,\n bindingRecordFields,\n tokenLabelContext = {},\n ...fieldProps\n } = props\n const { input } = useFieldApi({ name: fieldProps.name } as never) as {\n input: { value: unknown; onChange: (value: unknown) => void }\n }\n const [menuAnchor, setMenuAnchor] = useState<HTMLElement | null>(null)\n const [pillAnchor, setPillAnchor] = useState<HTMLElement | null>(null)\n\n const bound =\n matchComponentPropToken(input.value) != null ||\n matchWholeItemToken(input.value) != null\n ? String(input.value).trim()\n : null\n const resolved = useMemo(\n () => (bound ? resolveTokenLabel(bound, tokenLabelContext) : undefined),\n [bound, tokenLabelContext],\n )\n const labelText =\n typeof fieldProps.label === 'string' && fieldProps.label\n ? fieldProps.label\n : undefined\n const target = bindingRecordFields\n ? bindingProps?.length\n ? 'property or record field'\n : 'record field'\n : 'property'\n const bind: FieldBindAction = {\n label: bound\n ? `Change the ${target} ${labelText ?? 'this field'} is bound to`\n : `Bind ${labelText ?? 'this field'} to a ${target}`,\n onOpen: setMenuAnchor,\n }\n const gridProps: FormFieldGridProps = {\n ...(fieldProps.FormFieldGridProps ?? {}),\n bind,\n }\n\n const { Control, defaults } = splitControl(bindingControl)\n\n const menus = (\n <>\n <InsertTokenMenu\n anchorEl={menuAnchor}\n open={Boolean(menuAnchor)}\n onClose={() => setMenuAnchor(null)}\n options={bindingOptions}\n emptyText={bindingEmptyText}\n onInsert={(token) => {\n setMenuAnchor(null)\n input.onChange(token)\n }}\n />\n <TokenPillPopover\n anchorEl={pillAnchor}\n token={bound ?? ''}\n onClose={() => setPillAnchor(null)}\n onReplace={() => {\n setMenuAnchor(pillAnchor)\n setPillAnchor(null)\n }}\n onRemove={() => {\n setPillAnchor(null)\n // Unset rather than `false` or `''`: the element goes back to its\n // own default, which is what it rendered before it was bound.\n input.onChange(undefined)\n }}\n />\n </>\n )\n\n if (bound && resolved) {\n const described = describePropertyBinding({\n token: bound,\n resolved,\n bindingProps,\n bindingKinds,\n fieldOptions: fieldProps['options'],\n })\n return (\n <>\n <FormFieldGrid\n help={fieldProps.help as FormFieldGridProps['help']}\n {...gridProps}\n >\n <TextField\n fullWidth\n label={fieldProps.label}\n value=\"\"\n helperText={described.text}\n error={described.error}\n slotProps={{\n inputLabel: { shrink: true },\n input: {\n readOnly: true,\n inputComponent: BoundPropertyInput as never,\n inputProps: {\n token: bound,\n resolved,\n fieldLabel: labelText,\n onOpen: setPillAnchor,\n },\n },\n }}\n />\n </FormFieldGrid>\n {menus}\n </>\n )\n }\n\n if (!Control) return null\n return (\n <>\n <Control {...defaults} {...fieldProps} FormFieldGridProps={gridProps} />\n {menus}\n </>\n )\n}\nPropertyBindingField.displayName = 'PropertyBindingField'\n\nexport default PropertyBindingField\n"],"names":["attributeFieldValueShape","matchComponentPropToken","matchWholeItemToken","REUSABLE_PROP_KINDS","reusablePropBindsToField","unofferedChoiceValues","FormFieldGrid","useFieldApi","Box","ButtonBase","TextField","forwardRef","useMemo","useState","componentPropBindingOptions","TOKEN_PILL_ATTR","TOKEN_PILL_GROUP_ATTR","resolveTokenLabel","InsertTokenMenu","TokenPillPopover","tokenPillContainerSx","PROPERTY_BINDING_FIELD_COMPONENT","propertyKindsBindableTo","declared","labels","Object","keys","filter","type","options","value","settings","isMulti","some","candidate","map","label","length","slice","join","withPropertyBinding","field","declaredComponent","declaredField","componentProps","control","tokenLabelContext","owner","recordBindings","component","undefined","bindable","prop","kinds","bindingControl","bindingOptions","bindingProps","bindingKinds","bindingRecordFields","bindingEmptyText","splitControl","Control","defaults","BoundPropertyInput","props","ref","token","resolved","onOpen","fieldLabel","className","disabled","id","onFocus","onBlur","describedBy","pillAttributes","known","group","sx","display","alignItems","aria-describedby","aria-label","title","onClick","event","currentTarget","describePropertyBinding","fieldOptions","text","error","name","find","entry","unoffered","offered","Array","isArray","option","String","Boolean","PropertyBindingField","fieldProps","input","menuAnchor","setMenuAnchor","pillAnchor","setPillAnchor","bound","trim","labelText","target","bind","gridProps","FormFieldGridProps","menus","anchorEl","open","onClose","emptyText","onInsert","onChange","onReplace","onRemove","described","help","fullWidth","helperText","slotProps","inputLabel","shrink","readOnly","inputComponent","inputProps","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;;;AAGD,SACEA,wBAAwB,EAExBC,uBAAuB,EACvBC,mBAAmB,EACnBC,mBAAmB,EACnBC,wBAAwB,EACxBC,qBAAqB,QAChB,eAAc;AACrB,SAEEC,aAAa,EAEbC,WAAW,QACN,6BAA4B;AACnC,SAASC,GAAG,EAAEC,UAAU,EAAEC,SAAS,QAAQ,gBAAe;AAC1D,SAGEC,UAAU,EAGVC,OAAO,EACPC,QAAQ,QACH,QAAO;AAGd,SAASC,2BAA2B,QAAQ,uCAAmC;AAC/E,SACEC,eAAe,EACfC,qBAAqB,QAChB,iCAA6B;AACpC,SAEEC,iBAAiB,QAEZ,6BAAyB;AAChC,SAASC,eAAe,QAAQ,mCAA+B;AAC/D,SAASC,gBAAgB,EAAEC,oBAAoB,QAAQ,4BAAwB;AAE/E;;;;;;;;;;;;;;;;;;CAkBC,GAED,oFAAoF,GACpF,OAAO,MAAMC,mCAAmC,+BAA8B;AAE9E;;;;;;;CAOC,GACD,OAAO,SAASC,wBACdC,QAAgC;QAWDC;IAT/B,MAAMA,SAAS,AAACC,OAAOC,IAAI,CAACvB,qBACzBwB,MAAM,CAAC,CAACC,OACP;YACE;gBAAEA;YAAK;YACP;gBAAEA;gBAAMC,SAAS;oBAAC;wBAAEC,OAAO;oBAAI;iBAAE;YAAC;YAClC;gBAAEF;gBAAMC,SAAS;oBAAC;wBAAEC,OAAO;oBAAI;iBAAE;gBAAEC,UAAU;oBAAEC,SAAS;gBAAK;YAAE;SAChE,CAACC,IAAI,CAAC,CAACC,YAAc9B,yBAAyB8B,WAA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;gBAAYY,oBAAoBD;;YAC1DE;;;AAGP;AACAd,qBAAqBiC,WAAW,GAAG;AAEnC,eAAejC,qBAAoB"}
@@ -32,7 +32,29 @@ export interface InsertTokenOptionsResult {
32
32
  * `{{item.*}}` token has a record to read (AGL-4212).
33
33
  */
34
34
  inRepeat: boolean;
35
+ /**
36
+ * The record fields an `{{item.*}}` token can name here, with each one's
37
+ * named type where it has one (AGL-4190) — so a field that takes only one
38
+ * kind of value, an Icon picker, can offer only the fields that hold it.
39
+ */
40
+ itemFields: readonly ItemFieldOption[];
41
+ /** What the repeat's items are called, for the menu's group heading. */
42
+ itemNoun?: string;
43
+ /** The repeated entity's name, for the menu's group hint. */
44
+ entityLabel?: string;
45
+ }
46
+ /** One record field a repeat's `{{item.*}}` token can name. */
47
+ export interface ItemFieldOption {
48
+ id: string;
49
+ label: string;
50
+ /** The field's named type (`icon`, `image`…), where it has one. */
51
+ customType?: string;
35
52
  }
53
+ /**
54
+ * The repeat's record fields of one named type as binding options (AGL-4190),
55
+ * in the same group and words the `{}` menu uses for every record field.
56
+ */
57
+ export declare function itemFieldBindingOptions(context: Pick<InsertTokenOptionsResult, 'itemFields' | 'itemNoun' | 'entityLabel'>, customType: string): BindingOption[];
36
58
  /**
37
59
  * A component's or layout's own declared props as picker options (AGL-1335).
38
60
  * A free-text field offers every one; a field with no text box is handed only
@@ -18,6 +18,21 @@ import { AUTHOR_TOKEN_CATALOG, canvas, COLLECTION_ENTRIES_COMPONENT_ID, COLLECTI
18
18
  import { getRepeatSourcesVersion, repeatKeyOptionLabel, repeatSourceOf, subscribeRepeatSources } from "@aglyn/aglyn/app-utils/repeat-sources";
19
19
  import { useContext, useEffect, useMemo, useSyncExternalStore } from "react";
20
20
  import { BindingPickerContext } from "../contexts/binding-picker-context.js";
21
+ /**
22
+ * The repeat's record fields of one named type as binding options (AGL-4190),
23
+ * in the same group and words the `{}` menu uses for every record field.
24
+ */ export function itemFieldBindingOptions(context, customType) {
25
+ return context.itemFields.filter((field)=>field.customType === customType).map((field)=>{
26
+ var _context_itemNoun, _context_itemNoun1;
27
+ return _extends({
28
+ group: `${(_context_itemNoun = context.itemNoun) != null ? _context_itemNoun : 'Repeat'} item`,
29
+ label: field.label,
30
+ token: repeatItemToken(field.id)
31
+ }, context.entityLabel ? {
32
+ groupHint: `From ${((_context_itemNoun1 = context.itemNoun) != null ? _context_itemNoun1 : 'repeat').toLowerCase()} "${context.entityLabel}"`
33
+ } : {});
34
+ });
35
+ }
21
36
  /**
22
37
  * A component's or layout's own declared props as picker options (AGL-1335).
23
38
  * A free-text field offers every one; a field with no text box is handed only
@@ -242,15 +257,21 @@ import { BindingPickerContext } from "../contexts/binding-picker-context.js";
242
257
  bindingFunctions,
243
258
  insertContext.itemFields
244
259
  ]);
245
- const inRepeat = insertContext.inRepeat;
260
+ const { inRepeat, itemFields, itemNoun, entityLabel } = insertContext;
246
261
  return useMemo(()=>({
247
262
  options,
248
263
  labelContext,
249
- inRepeat
264
+ inRepeat,
265
+ itemFields,
266
+ itemNoun,
267
+ entityLabel
250
268
  }), [
251
269
  options,
252
270
  labelContext,
253
- inRepeat
271
+ inRepeat,
272
+ itemFields,
273
+ itemNoun,
274
+ entityLabel
254
275
  ]);
255
276
  }
256
277
  export default useInsertTokenOptions;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/besigner/feature/designer/src/lib/hooks/use-insert-token-options.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type * as Aglyn from '@aglyn/aglyn'\nimport {\n AUTHOR_TOKEN_CATALOG,\n canvas,\n COLLECTION_ENTRIES_COMPONENT_ID,\n COLLECTION_TOKEN_CATALOG,\n COMPONENT_PROP_NAME_PATTERN,\n COMPONENT_PROP_TOKEN_PREFIX,\n EntityPickerContext,\n entityValueNeedsResolution,\n ENTRY_TOKEN_CATALOG,\n readYesNoValue,\n repeatItemToken,\n reusablePropDefaultValue,\n reusablePropHasAnswers,\n reusablePropValueClass,\n} from '@aglyn/aglyn'\nimport {\n getRepeatSourcesVersion,\n repeatKeyOptionLabel,\n repeatSourceOf,\n subscribeRepeatSources,\n} from '@aglyn/aglyn/app-utils/repeat-sources'\nimport { useContext, useEffect, useMemo, useSyncExternalStore } from 'react'\n\nimport {\n BindingPickerContext,\n type BindingOption,\n} from '../contexts/binding-picker-context'\nimport type { TokenLabelContext } from '../utils/token-segments'\n\nexport interface InsertTokenOptionsResult {\n /**\n * The full grouped picker list (AGL-583): host bindings first (AGL-100),\n * then the data-placeholder catalogs. Entry/Collection stay browsable\n * even out of context — with a hint saying where they resolve — while\n * the item group only appears inside a repeat whose entity resolves.\n */\n options: BindingOption[]\n /** Display-name resolution inputs for pill rendering (AGL-586). */\n labelContext: TokenLabelContext\n /**\n * Whether the node is inside a repeat (or repeats itself), where an\n * `{{item.*}}` token has a record to read (AGL-4212).\n */\n inRepeat: boolean\n}\n\n/**\n * A component's or layout's own declared props as picker options (AGL-1335).\n * A free-text field offers every one; a field with no text box is handed only\n * the properties it can be bound to (see `withPropertyBinding`).\n *\n * Names are filtered by the SAME pattern the graft requires, so a picker can\n * never offer a token that would not substitute.\n */\nexport function componentPropBindingOptions(\n componentProps: readonly Aglyn.ReusableComponentProp[] | undefined | null,\n owner: 'component' | 'layout' = 'component',\n): BindingOption[] {\n const options: BindingOption[] = []\n for (const prop of componentProps ?? []) {\n if (!COMPONENT_PROP_NAME_PATTERN.test(prop?.name ?? '')) continue\n options.push({\n group: 'Properties',\n groupHint:\n owner === 'layout'\n ? 'Set per page in the Page Properties of each page using this layout'\n : // Pages and emails alike: an email block is a component too\n // (AGL-3287), and its values are set in each email it is in.\n 'Set in the Attributes panel wherever this component is used',\n label: prop.label || prop.name,\n token: `{{${COMPONENT_PROP_TOKEN_PREFIX}${prop.name}}}`,\n preview: componentPropDefaultPreview(prop),\n })\n }\n return options\n}\n\n/** The picker's second line for a property: what a page that sets nothing gets. */\nexport function componentPropDefaultPreview(\n prop: Aglyn.ReusableComponentProp,\n): string {\n const valueClass = reusablePropValueClass(prop)\n if (valueClass === 'boolean') {\n // A yes/no has no \"nothing\": unset with no default substitutes `''`,\n // which every Yes / no reader takes for a no.\n return readYesNoValue(prop.defaultValue) === true\n ? 'Defaults to Yes'\n : 'Defaults to No'\n }\n if (valueClass === 'icon') {\n // An icon id is not something to read out; the picker shows the icon.\n return prop.defaultValue\n ? 'Defaults to the icon picked in Properties'\n : 'No default — shows no icon until a page picks one'\n }\n const fallback = reusablePropDefaultValue(prop)\n if (reusablePropHasAnswers(prop)) {\n // Named by the label a page author picks, not the value a field gets.\n const chosen = (Array.isArray(fallback) ? fallback : [fallback])\n .map((value) => {\n const answer = (prop.options ?? []).find(\n (option) => option?.value && option.value === value,\n )\n return answer ? answer.label || answer.value : undefined\n })\n .filter(Boolean)\n return chosen.length\n ? `Defaults to ${chosen.join(', ')}`\n : 'No default — the field keeps its own until a page chooses'\n }\n if (fallback === undefined) {\n return valueClass === 'text'\n ? 'No default — renders as nothing until a page sets it'\n : 'No default — the field keeps its own until a page sets it'\n }\n return `Defaults to \"${Array.isArray(fallback) ? fallback.join(', ') : String(fallback)}\"`\n}\n\n/**\n * Assembles the insert-picker options for a canvas node from ITS context\n * (AGL-583, extracted for AGL-586 so the attributes panel and the inline\n * text editor share one walk): the ancestor chain is scanned for the\n * nearest repeat (its item tokens need the fields of the entity it repeats\n * over) and for a Collection entries block (entry tokens resolve right\n * there, not only on entry pages).\n *\n * A repeat is found through the registered repeat sources, never by a prop\n * name: the source says which prop holds its key and which entity picker\n * kind the key names (`RepeatSource.entityKind`). A key may be an entity id\n * OR a legacy display name — either resolves against the picker's options.\n * A source whose keys are no entity lists its fields itself\n * (`RepeatSource.fields`, AGL-4212).\n */\nexport function useInsertTokenOptions(\n node?: Aglyn.NodeSchema<any> | null,\n): InsertTokenOptionsResult {\n const {\n options: bindingOptions,\n variables: bindingVariables,\n functions: bindingFunctions,\n componentProps,\n componentPropsOwner,\n } = useContext(BindingPickerContext)\n const entityOptions = useContext(EntityPickerContext)\n // A plugin registers its repeat source when its console bundle loads,\n // which can be after this node was selected; the walk is redone then.\n const repeatSourcesVersion = useSyncExternalStore(\n subscribeRepeatSources,\n getRepeatSourcesVersion,\n getRepeatSourcesVersion,\n )\n\n const insertContext = useMemo(() => {\n const nodes = (canvas.toJSON().nodes ?? {}) as Record<string, any>\n let repeat: ReturnType<typeof repeatSourceOf> = undefined\n let inCollectionEntries = false\n let current = node?.$id ? nodes[node.$id] : undefined\n for (let hops = 0; current && hops < 100; hops += 1) {\n repeat ??= repeatSourceOf(current)\n if (current.componentId === COLLECTION_ENTRIES_COMPONENT_ID) {\n inCollectionEntries = true\n }\n current = current.parentId ? nodes[current.parentId] : undefined\n }\n const kind = repeat?.source.entityKind\n const key = kind ? repeat?.key : undefined\n const listed = kind ? entityOptions.options?.[kind] ?? [] : []\n /*\n * The browse window is a PAGE of the site's entities, so a repeat bound to\n * one outside it matches nothing here — and this is where the token menu\n * would silently stop offering that entity's fields on exactly the sites\n * with enough of them to need them. A resolution counts as a match, which\n * is the same keyed read the attributes panel already spends on a\n * picker's stored value.\n */\n const entity =\n kind && key\n ? listed.find((candidate) => candidate.id === key) ??\n listed.find((candidate) => candidate.label === key) ??\n entityOptions.resolved?.[kind]?.[key] ??\n undefined\n : undefined\n /*\n * A source whose keys are no entity (a plugin connection's record,\n * AGL-4212) names its fields itself, and its picker names the key.\n */\n const named =\n !kind && repeat?.source.fields\n ? {\n label: repeatKeyOptionLabel(repeat.source, repeat.key),\n fields: repeat.source.fields(repeat.key) ?? [],\n }\n : undefined\n return {\n inCollectionEntries,\n inRepeat: Boolean(repeat),\n // What the repeat's items are called in the menu — the source's own\n // name for what it repeats over.\n itemNoun: repeat?.source.label,\n entityLabel: named ? named.label : entity?.label,\n itemFields: named\n ? named.fields.map((field) => ({ id: field.id, label: field.label }))\n : kind && entity\n ? entityOptions.entityFields?.[kind]?.[entity.id] ?? []\n : [],\n // Carried out of the walk so the effect below can ask for the entity\n // list without repeating it.\n entityKind: kind,\n entityKey: key,\n }\n // `repeatSourcesVersion` is read by `repeatSourceOf` through the registry.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [node, entityOptions, repeatSourcesVersion])\n\n /**\n * Ask for the repeated entity's list, and only when this node is inside a\n * repeat whose source names one (AGL-703).\n *\n * This hook runs on every selection — the props form and the inline text\n * editor both call it — so requesting unconditionally would put the\n * provider back to reading a list on every click. The repeat's key is the\n * precise condition: without it there is no entity to name and the token\n * menu offers no item tokens.\n */\n const requestEntities = entityOptions.request\n const resolveEntity = entityOptions.resolve\n useEffect(() => {\n const { entityKind: kind, entityKey: key } = insertContext\n if (!kind || !key) return\n requestEntities?.(kind)\n // Nothing to look up once the entity is named. A key may be a legacy\n // DISPLAY NAME, which the label match above answers from the window —\n // reading a document at that name as though it were an id would be a\n // read that could only ever miss.\n if (insertContext.entityLabel) return\n const id = entityValueNeedsResolution(entityOptions, kind, key)\n if (id) resolveEntity?.(kind, id)\n }, [requestEntities, resolveEntity, entityOptions, insertContext])\n\n const options = useMemo(() => {\n const assembled: BindingOption[] = [...(bindingOptions ?? [])]\n /**\n * The component's own declared props (AGL-1335), first because they are\n * the nearest scope — inside a component definition, `{{prop.x}}` is\n * what the author reaches for most.\n *\n * They were absent from this picker entirely, so binding one meant\n * typing `{{prop.name}}` by hand while a `{}` button sat next to the\n * field implying otherwise.\n */\n assembled.push(\n ...componentPropBindingOptions(componentProps, componentPropsOwner),\n )\n const entryHint = insertContext.inCollectionEntries\n ? undefined\n : 'Resolves in Collection entries blocks and on entry pages'\n for (const entry of ENTRY_TOKEN_CATALOG) {\n assembled.push({\n group: 'Entry',\n label: entry.label,\n token: entry.token,\n preview: entry.description,\n ...(entryHint ? { groupHint: entryHint } : {}),\n })\n }\n for (const entry of COLLECTION_TOKEN_CATALOG) {\n assembled.push({\n group: 'Collection',\n label: entry.label,\n token: entry.token,\n preview: entry.description,\n groupHint: 'Resolves on collection pages',\n })\n }\n for (const entry of AUTHOR_TOKEN_CATALOG) {\n assembled.push({\n group: 'Author',\n label: entry.label,\n token: entry.token,\n preview: entry.description,\n groupHint: 'Resolves on author pages',\n })\n }\n for (const field of insertContext.itemFields) {\n assembled.push({\n group: `${insertContext.itemNoun ?? 'Repeat'} item`,\n label: field.label,\n token: repeatItemToken(field.id),\n ...(insertContext.entityLabel\n ? {\n groupHint: `From ${(insertContext.itemNoun ?? 'repeat').toLowerCase()} \"${insertContext.entityLabel}\"`,\n }\n : {}),\n })\n }\n return assembled\n }, [bindingOptions, componentProps, componentPropsOwner, insertContext])\n\n const labelContext = useMemo<TokenLabelContext>(\n () => ({\n options,\n variables: bindingVariables as TokenLabelContext['variables'],\n functions: bindingFunctions as TokenLabelContext['functions'],\n itemFields: insertContext.itemFields,\n }),\n [options, bindingVariables, bindingFunctions, insertContext.itemFields],\n )\n\n const inRepeat = insertContext.inRepeat\n return useMemo(\n () => ({ options, labelContext, inRepeat }),\n [options, labelContext, inRepeat],\n )\n}\n\nexport default useInsertTokenOptions\n"],"names":["AUTHOR_TOKEN_CATALOG","canvas","COLLECTION_ENTRIES_COMPONENT_ID","COLLECTION_TOKEN_CATALOG","COMPONENT_PROP_NAME_PATTERN","COMPONENT_PROP_TOKEN_PREFIX","EntityPickerContext","entityValueNeedsResolution","ENTRY_TOKEN_CATALOG","readYesNoValue","repeatItemToken","reusablePropDefaultValue","reusablePropHasAnswers","reusablePropValueClass","getRepeatSourcesVersion","repeatKeyOptionLabel","repeatSourceOf","subscribeRepeatSources","useContext","useEffect","useMemo","useSyncExternalStore","BindingPickerContext","componentPropBindingOptions","componentProps","owner","options","prop","test","name","push","group","groupHint","label","token","preview","componentPropDefaultPreview","valueClass","defaultValue","fallback","chosen","Array","isArray","map","value","answer","find","option","undefined","filter","Boolean","length","join","String","useInsertTokenOptions","node","bindingOptions","variables","bindingVariables","functions","bindingFunctions","componentPropsOwner","entityOptions","repeatSourcesVersion","insertContext","listed","repeat","nodes","toJSON","inCollectionEntries","current","$id","hops","componentId","parentId","kind","source","entityKind","key","entity","candidate","id","resolved","named","fields","inRepeat","itemNoun","entityLabel","itemFields","field","entityFields","entityKey","requestEntities","request","resolveEntity","resolve","assembled","entryHint","entry","description","toLowerCase","labelContext"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SACEA,oBAAoB,EACpBC,MAAM,EACNC,+BAA+B,EAC/BC,wBAAwB,EACxBC,2BAA2B,EAC3BC,2BAA2B,EAC3BC,mBAAmB,EACnBC,0BAA0B,EAC1BC,mBAAmB,EACnBC,cAAc,EACdC,eAAe,EACfC,wBAAwB,EACxBC,sBAAsB,EACtBC,sBAAsB,QACjB,eAAc;AACrB,SACEC,uBAAuB,EACvBC,oBAAoB,EACpBC,cAAc,EACdC,sBAAsB,QACjB,wCAAuC;AAC9C,SAASC,UAAU,EAAEC,SAAS,EAAEC,OAAO,EAAEC,oBAAoB,QAAQ,QAAO;AAE5E,SACEC,oBAAoB,QAEf,wCAAoC;AAoB3C;;;;;;;CAOC,GACD,OAAO,SAASC,4BACdC,cAAyE,EACzEC,QAAgC,WAAW;IAE3C,MAAMC,UAA2B,EAAE;IACnC,KAAK,MAAMC,QAAQH,yBAAAA,iBAAkB,EAAE,CAAE;;QACvC,IAAI,CAACpB,4BAA4BwB,IAAI,SAACD,wBAAAA,KAAME,IAAI,mBAAI,KAAK;QACzDH,QAAQI,IAAI,CAAC;YACXC,OAAO;YACPC,WACEP,UAAU,WACN,uEAEA,6DAA6D;YAC7D;YACNQ,OAAON,KAAKM,KAAK,IAAIN,KAAKE,IAAI;YAC9BK,OAAO,CAAC,EAAE,EA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,SAAS,KAAK,CAAC;gBACnD/B,OAAOwD,MAAMxD,KAAK;gBAClBC,OAAOxB,gBAAgB+E,MAAMR,EAAE;eAC3BjB,cAAcuB,WAAW,GACzB;gBACEvD,WAAW,CAAC,KAAK,EAAE,EAACgC,2BAAAA,cAAcsB,QAAQ,YAAtBtB,2BAA0B,UAAUoC,WAAW,GAAG,EAAE,EAAEpC,cAAcuB,WAAW,CAAC,CAAC,CAAC;YACxG,IACA,CAAC;QAET;QACA,OAAOS;IACT,GAAG;QAACxC;QAAgBhC;QAAgBqC;QAAqBG;KAAc;IAEvE,MAAMqC,eAAejF,QACnB,IAAO,CAAA;YACLM;YACA+B,WAAWC;YACXC,WAAWC;YACX4B,YAAYxB,cAAcwB,UAAU;QACtC,CAAA,GACA;QAAC9D;QAASgC;QAAkBE;QAAkBI,cAAcwB,UAAU;KAAC;IAGzE,MAAMH,WAAWrB,cAAcqB,QAAQ;IACvC,OAAOjE,QACL,IAAO,CAAA;YAAEM;YAAS2E;YAAchB;QAAS,CAAA,GACzC;QAAC3D;QAAS2E;QAAchB;KAAS;AAErC;AAEA,eAAe/B,sBAAqB"}
1
+ {"version":3,"sources":["../../../../../../../../libs/besigner/feature/designer/src/lib/hooks/use-insert-token-options.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type * as Aglyn from '@aglyn/aglyn'\nimport {\n AUTHOR_TOKEN_CATALOG,\n canvas,\n COLLECTION_ENTRIES_COMPONENT_ID,\n COLLECTION_TOKEN_CATALOG,\n COMPONENT_PROP_NAME_PATTERN,\n COMPONENT_PROP_TOKEN_PREFIX,\n EntityPickerContext,\n entityValueNeedsResolution,\n ENTRY_TOKEN_CATALOG,\n readYesNoValue,\n repeatItemToken,\n reusablePropDefaultValue,\n reusablePropHasAnswers,\n reusablePropValueClass,\n} from '@aglyn/aglyn'\nimport {\n getRepeatSourcesVersion,\n repeatKeyOptionLabel,\n repeatSourceOf,\n subscribeRepeatSources,\n} from '@aglyn/aglyn/app-utils/repeat-sources'\nimport { useContext, useEffect, useMemo, useSyncExternalStore } from 'react'\n\nimport {\n BindingPickerContext,\n type BindingOption,\n} from '../contexts/binding-picker-context'\nimport type { TokenLabelContext } from '../utils/token-segments'\n\nexport interface InsertTokenOptionsResult {\n /**\n * The full grouped picker list (AGL-583): host bindings first (AGL-100),\n * then the data-placeholder catalogs. Entry/Collection stay browsable\n * even out of context — with a hint saying where they resolve — while\n * the item group only appears inside a repeat whose entity resolves.\n */\n options: BindingOption[]\n /** Display-name resolution inputs for pill rendering (AGL-586). */\n labelContext: TokenLabelContext\n /**\n * Whether the node is inside a repeat (or repeats itself), where an\n * `{{item.*}}` token has a record to read (AGL-4212).\n */\n inRepeat: boolean\n /**\n * The record fields an `{{item.*}}` token can name here, with each one's\n * named type where it has one (AGL-4190) — so a field that takes only one\n * kind of value, an Icon picker, can offer only the fields that hold it.\n */\n itemFields: readonly ItemFieldOption[]\n /** What the repeat's items are called, for the menu's group heading. */\n itemNoun?: string\n /** The repeated entity's name, for the menu's group hint. */\n entityLabel?: string\n}\n\n/** One record field a repeat's `{{item.*}}` token can name. */\nexport interface ItemFieldOption {\n id: string\n label: string\n /** The field's named type (`icon`, `image`…), where it has one. */\n customType?: string\n}\n\n/**\n * The repeat's record fields of one named type as binding options (AGL-4190),\n * in the same group and words the `{}` menu uses for every record field.\n */\nexport function itemFieldBindingOptions(\n context: Pick<InsertTokenOptionsResult, 'itemFields' | 'itemNoun' | 'entityLabel'>,\n customType: string,\n): BindingOption[] {\n return context.itemFields\n .filter((field) => field.customType === customType)\n .map((field) => ({\n group: `${context.itemNoun ?? 'Repeat'} item`,\n label: field.label,\n token: repeatItemToken(field.id),\n ...(context.entityLabel\n ? {\n groupHint: `From ${(context.itemNoun ?? 'repeat').toLowerCase()} \"${context.entityLabel}\"`,\n }\n : {}),\n }))\n}\n\n/**\n * A component's or layout's own declared props as picker options (AGL-1335).\n * A free-text field offers every one; a field with no text box is handed only\n * the properties it can be bound to (see `withPropertyBinding`).\n *\n * Names are filtered by the SAME pattern the graft requires, so a picker can\n * never offer a token that would not substitute.\n */\nexport function componentPropBindingOptions(\n componentProps: readonly Aglyn.ReusableComponentProp[] | undefined | null,\n owner: 'component' | 'layout' = 'component',\n): BindingOption[] {\n const options: BindingOption[] = []\n for (const prop of componentProps ?? []) {\n if (!COMPONENT_PROP_NAME_PATTERN.test(prop?.name ?? '')) continue\n options.push({\n group: 'Properties',\n groupHint:\n owner === 'layout'\n ? 'Set per page in the Page Properties of each page using this layout'\n : // Pages and emails alike: an email block is a component too\n // (AGL-3287), and its values are set in each email it is in.\n 'Set in the Attributes panel wherever this component is used',\n label: prop.label || prop.name,\n token: `{{${COMPONENT_PROP_TOKEN_PREFIX}${prop.name}}}`,\n preview: componentPropDefaultPreview(prop),\n })\n }\n return options\n}\n\n/** The picker's second line for a property: what a page that sets nothing gets. */\nexport function componentPropDefaultPreview(\n prop: Aglyn.ReusableComponentProp,\n): string {\n const valueClass = reusablePropValueClass(prop)\n if (valueClass === 'boolean') {\n // A yes/no has no \"nothing\": unset with no default substitutes `''`,\n // which every Yes / no reader takes for a no.\n return readYesNoValue(prop.defaultValue) === true\n ? 'Defaults to Yes'\n : 'Defaults to No'\n }\n if (valueClass === 'icon') {\n // An icon id is not something to read out; the picker shows the icon.\n return prop.defaultValue\n ? 'Defaults to the icon picked in Properties'\n : 'No default — shows no icon until a page picks one'\n }\n const fallback = reusablePropDefaultValue(prop)\n if (reusablePropHasAnswers(prop)) {\n // Named by the label a page author picks, not the value a field gets.\n const chosen = (Array.isArray(fallback) ? fallback : [fallback])\n .map((value) => {\n const answer = (prop.options ?? []).find(\n (option) => option?.value && option.value === value,\n )\n return answer ? answer.label || answer.value : undefined\n })\n .filter(Boolean)\n return chosen.length\n ? `Defaults to ${chosen.join(', ')}`\n : 'No default — the field keeps its own until a page chooses'\n }\n if (fallback === undefined) {\n return valueClass === 'text'\n ? 'No default — renders as nothing until a page sets it'\n : 'No default — the field keeps its own until a page sets it'\n }\n return `Defaults to \"${Array.isArray(fallback) ? fallback.join(', ') : String(fallback)}\"`\n}\n\n/**\n * Assembles the insert-picker options for a canvas node from ITS context\n * (AGL-583, extracted for AGL-586 so the attributes panel and the inline\n * text editor share one walk): the ancestor chain is scanned for the\n * nearest repeat (its item tokens need the fields of the entity it repeats\n * over) and for a Collection entries block (entry tokens resolve right\n * there, not only on entry pages).\n *\n * A repeat is found through the registered repeat sources, never by a prop\n * name: the source says which prop holds its key and which entity picker\n * kind the key names (`RepeatSource.entityKind`). A key may be an entity id\n * OR a legacy display name — either resolves against the picker's options.\n * A source whose keys are no entity lists its fields itself\n * (`RepeatSource.fields`, AGL-4212).\n */\nexport function useInsertTokenOptions(\n node?: Aglyn.NodeSchema<any> | null,\n): InsertTokenOptionsResult {\n const {\n options: bindingOptions,\n variables: bindingVariables,\n functions: bindingFunctions,\n componentProps,\n componentPropsOwner,\n } = useContext(BindingPickerContext)\n const entityOptions = useContext(EntityPickerContext)\n // A plugin registers its repeat source when its console bundle loads,\n // which can be after this node was selected; the walk is redone then.\n const repeatSourcesVersion = useSyncExternalStore(\n subscribeRepeatSources,\n getRepeatSourcesVersion,\n getRepeatSourcesVersion,\n )\n\n const insertContext = useMemo(() => {\n const nodes = (canvas.toJSON().nodes ?? {}) as Record<string, any>\n let repeat: ReturnType<typeof repeatSourceOf> = undefined\n let inCollectionEntries = false\n let current = node?.$id ? nodes[node.$id] : undefined\n for (let hops = 0; current && hops < 100; hops += 1) {\n repeat ??= repeatSourceOf(current)\n if (current.componentId === COLLECTION_ENTRIES_COMPONENT_ID) {\n inCollectionEntries = true\n }\n current = current.parentId ? nodes[current.parentId] : undefined\n }\n const kind = repeat?.source.entityKind\n const key = kind ? repeat?.key : undefined\n const listed = kind ? entityOptions.options?.[kind] ?? [] : []\n /*\n * The browse window is a PAGE of the site's entities, so a repeat bound to\n * one outside it matches nothing here — and this is where the token menu\n * would silently stop offering that entity's fields on exactly the sites\n * with enough of them to need them. A resolution counts as a match, which\n * is the same keyed read the attributes panel already spends on a\n * picker's stored value.\n */\n const entity =\n kind && key\n ? listed.find((candidate) => candidate.id === key) ??\n listed.find((candidate) => candidate.label === key) ??\n entityOptions.resolved?.[kind]?.[key] ??\n undefined\n : undefined\n /*\n * A source whose keys are no entity (a plugin connection's record,\n * AGL-4212) names its fields itself, and its picker names the key.\n */\n const named =\n !kind && repeat?.source.fields\n ? {\n label: repeatKeyOptionLabel(repeat.source, repeat.key),\n fields: repeat.source.fields(repeat.key) ?? [],\n }\n : undefined\n return {\n inCollectionEntries,\n inRepeat: Boolean(repeat),\n // What the repeat's items are called in the menu — the source's own\n // name for what it repeats over.\n itemNoun: repeat?.source.label,\n entityLabel: named ? named.label : entity?.label,\n itemFields: (named\n ? named.fields.map((field) => ({ id: field.id, label: field.label }))\n : kind && entity\n ? entityOptions.entityFields?.[kind]?.[entity.id] ?? []\n : []) as readonly ItemFieldOption[],\n // Carried out of the walk so the effect below can ask for the entity\n // list without repeating it.\n entityKind: kind,\n entityKey: key,\n }\n // `repeatSourcesVersion` is read by `repeatSourceOf` through the registry.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [node, entityOptions, repeatSourcesVersion])\n\n /**\n * Ask for the repeated entity's list, and only when this node is inside a\n * repeat whose source names one (AGL-703).\n *\n * This hook runs on every selection — the props form and the inline text\n * editor both call it — so requesting unconditionally would put the\n * provider back to reading a list on every click. The repeat's key is the\n * precise condition: without it there is no entity to name and the token\n * menu offers no item tokens.\n */\n const requestEntities = entityOptions.request\n const resolveEntity = entityOptions.resolve\n useEffect(() => {\n const { entityKind: kind, entityKey: key } = insertContext\n if (!kind || !key) return\n requestEntities?.(kind)\n // Nothing to look up once the entity is named. A key may be a legacy\n // DISPLAY NAME, which the label match above answers from the window —\n // reading a document at that name as though it were an id would be a\n // read that could only ever miss.\n if (insertContext.entityLabel) return\n const id = entityValueNeedsResolution(entityOptions, kind, key)\n if (id) resolveEntity?.(kind, id)\n }, [requestEntities, resolveEntity, entityOptions, insertContext])\n\n const options = useMemo(() => {\n const assembled: BindingOption[] = [...(bindingOptions ?? [])]\n /**\n * The component's own declared props (AGL-1335), first because they are\n * the nearest scope — inside a component definition, `{{prop.x}}` is\n * what the author reaches for most.\n *\n * They were absent from this picker entirely, so binding one meant\n * typing `{{prop.name}}` by hand while a `{}` button sat next to the\n * field implying otherwise.\n */\n assembled.push(\n ...componentPropBindingOptions(componentProps, componentPropsOwner),\n )\n const entryHint = insertContext.inCollectionEntries\n ? undefined\n : 'Resolves in Collection entries blocks and on entry pages'\n for (const entry of ENTRY_TOKEN_CATALOG) {\n assembled.push({\n group: 'Entry',\n label: entry.label,\n token: entry.token,\n preview: entry.description,\n ...(entryHint ? { groupHint: entryHint } : {}),\n })\n }\n for (const entry of COLLECTION_TOKEN_CATALOG) {\n assembled.push({\n group: 'Collection',\n label: entry.label,\n token: entry.token,\n preview: entry.description,\n groupHint: 'Resolves on collection pages',\n })\n }\n for (const entry of AUTHOR_TOKEN_CATALOG) {\n assembled.push({\n group: 'Author',\n label: entry.label,\n token: entry.token,\n preview: entry.description,\n groupHint: 'Resolves on author pages',\n })\n }\n for (const field of insertContext.itemFields) {\n assembled.push({\n group: `${insertContext.itemNoun ?? 'Repeat'} item`,\n label: field.label,\n token: repeatItemToken(field.id),\n ...(insertContext.entityLabel\n ? {\n groupHint: `From ${(insertContext.itemNoun ?? 'repeat').toLowerCase()} \"${insertContext.entityLabel}\"`,\n }\n : {}),\n })\n }\n return assembled\n }, [bindingOptions, componentProps, componentPropsOwner, insertContext])\n\n const labelContext = useMemo<TokenLabelContext>(\n () => ({\n options,\n variables: bindingVariables as TokenLabelContext['variables'],\n functions: bindingFunctions as TokenLabelContext['functions'],\n itemFields: insertContext.itemFields,\n }),\n [options, bindingVariables, bindingFunctions, insertContext.itemFields],\n )\n\n const { inRepeat, itemFields, itemNoun, entityLabel } = insertContext\n return useMemo(\n () => ({ options, labelContext, inRepeat, itemFields, itemNoun, entityLabel }),\n [options, labelContext, inRepeat, itemFields, itemNoun, entityLabel],\n )\n}\n\nexport default useInsertTokenOptions\n"],"names":["AUTHOR_TOKEN_CATALOG","canvas","COLLECTION_ENTRIES_COMPONENT_ID","COLLECTION_TOKEN_CATALOG","COMPONENT_PROP_NAME_PATTERN","COMPONENT_PROP_TOKEN_PREFIX","EntityPickerContext","entityValueNeedsResolution","ENTRY_TOKEN_CATALOG","readYesNoValue","repeatItemToken","reusablePropDefaultValue","reusablePropHasAnswers","reusablePropValueClass","getRepeatSourcesVersion","repeatKeyOptionLabel","repeatSourceOf","subscribeRepeatSources","useContext","useEffect","useMemo","useSyncExternalStore","BindingPickerContext","itemFieldBindingOptions","context","customType","itemFields","filter","field","map","group","itemNoun","label","token","id","entityLabel","groupHint","toLowerCase","componentPropBindingOptions","componentProps","owner","options","prop","test","name","push","preview","componentPropDefaultPreview","valueClass","defaultValue","fallback","chosen","Array","isArray","value","answer","find","option","undefined","Boolean","length","join","String","useInsertTokenOptions","node","bindingOptions","variables","bindingVariables","functions","bindingFunctions","componentPropsOwner","entityOptions","repeatSourcesVersion","insertContext","listed","repeat","nodes","toJSON","inCollectionEntries","current","$id","hops","componentId","parentId","kind","source","entityKind","key","entity","candidate","resolved","named","fields","inRepeat","entityFields","entityKey","requestEntities","request","resolveEntity","resolve","assembled","entryHint","entry","description","labelContext"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SACEA,oBAAoB,EACpBC,MAAM,EACNC,+BAA+B,EAC/BC,wBAAwB,EACxBC,2BAA2B,EAC3BC,2BAA2B,EAC3BC,mBAAmB,EACnBC,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AC;gBACnDzC,OAAOJ,MAAMI,KAAK;gBAClBC,OAAOvB,gBAAgBkB,MAAMM,EAAE;eAC3BuC,cAActC,WAAW,GACzB;gBACEC,WAAW,CAAC,KAAK,EAAE,EAACqC,2BAAAA,cAAc1C,QAAQ,YAAtB0C,2BAA0B,UAAUpC,WAAW,GAAG,EAAE,EAAEoC,cAActC,WAAW,CAAC,CAAC,CAAC;YACxG,IACA,CAAC;QAET;QACA,OAAOiE;IACT,GAAG;QAACnC;QAAgB1B;QAAgB+B;QAAqBG;KAAc;IAEvE,MAAM+B,eAAepF,QACnB,IAAO,CAAA;YACLqB;YACAyB,WAAWC;YACXC,WAAWC;YACX3C,YAAY+C,cAAc/C,UAAU;QACtC,CAAA,GACA;QAACe;QAAS0B;QAAkBE;QAAkBI,cAAc/C,UAAU;KAAC;IAGzE,MAAM,EAAEmE,QAAQ,EAAEnE,UAAU,EAAEK,QAAQ,EAAEI,WAAW,EAAE,GAAGsC;IACxD,OAAOrD,QACL,IAAO,CAAA;YAAEqB;YAAS+D;YAAcX;YAAUnE;YAAYK;YAAUI;QAAY,CAAA,GAC5E;QAACM;QAAS+D;QAAcX;QAAUnE;QAAYK;QAAUI;KAAY;AAExE;AAEA,eAAe4B,sBAAqB"}
@@ -90,7 +90,7 @@ export interface TokenLabelContext {
90
90
  functions?: Record<string, {
91
91
  name?: string;
92
92
  } | undefined>;
93
- itemFields?: Array<{
93
+ itemFields?: ReadonlyArray<{
94
94
  id: string;
95
95
  label: string;
96
96
  }>;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/besigner/feature/designer/src/lib/utils/token-segments.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n COLLECTION_TOKEN_CATALOG,\n ENTRY_TOKEN_CATALOG,\n hostTokenDefinition,\n} from '@aglyn/aglyn'\n\nimport type { BindingOption } from '../contexts/binding-picker-context'\n\n/**\n * Token-pill segment model (AGL-586). Stored prop strings keep the raw\n * id-based `{{...}}` grammar (AGL-100/185) — these helpers only SPLIT a\n * string into runs of plain text and atomic tokens so editors can render\n * the tokens as friendly, clickable pills. Serializing the segments always\n * reproduces the exact input string; nothing here ever rewrites a token.\n *\n * Offset model: editor carets address \"units\", where every plain-text\n * character is 1 unit and every token — however long its raw text — is 1\n * atomic unit. A caret can therefore sit before or after a pill but never\n * inside one, which is exactly how the pills behave in the DOM\n * (`contenteditable=\"false\"`).\n */\nexport interface TokenSegment {\n type: 'text' | 'token'\n /** The literal slice of the serialized string (raw `{{...}}` for tokens). */\n value: string\n /** Set on token segments: the raw token, identical to `value`. */\n token?: string\n}\n\n/**\n * Any `{{...}}` occurrence without nested braces — var:/fn:/entry./\n * collection./item.* AND unknown tokens alike. `{{a{{b}}` yields the text\n * `{{a` plus the token `{{b}}` (the opener without a closer is plain text).\n */\nexport const TOKEN_SEGMENT_PATTERN = /\\{\\{[^{}]*\\}\\}/g\n\n/** Drops empty text runs and merges adjacent text segments. */\nfunction normalizeSegments(segments: TokenSegment[]): TokenSegment[] {\n const out: TokenSegment[] = []\n for (const segment of segments) {\n if (segment.type === 'text' && !segment.value) continue\n const last = out[out.length - 1]\n if (segment.type === 'text' && last?.type === 'text') {\n last.value += segment.value\n } else {\n out.push({ ...segment })\n }\n }\n return out\n}\n\n/** Splits `text` on `{{...}}` occurrences into text/token segments. */\nexport function parseTokenSegments(text: string): TokenSegment[] {\n const segments: TokenSegment[] = []\n let cursor = 0\n const pattern = new RegExp(TOKEN_SEGMENT_PATTERN.source, 'g')\n for (let match = pattern.exec(text); match; match = pattern.exec(text)) {\n if (match.index > cursor) {\n segments.push({ type: 'text', value: text.slice(cursor, match.index) })\n }\n segments.push({ type: 'token', value: match[0], token: match[0] })\n cursor = match.index + match[0].length\n }\n if (cursor < text.length) {\n segments.push({ type: 'text', value: text.slice(cursor) })\n }\n return segments\n}\n\n/** Joins segments back to the exact stored string (lossless round-trip). */\nexport function serializeTokenSegments(segments: TokenSegment[]): string {\n return segments.map((segment) => segment.value).join('')\n}\n\n/** True when any text run still holds a complete raw `{{...}}` token. */\nexport function hasUnmaterializedTokens(segments: TokenSegment[]): boolean {\n const probe = new RegExp(TOKEN_SEGMENT_PATTERN.source)\n return segments.some(\n (segment) => segment.type === 'text' && probe.test(segment.value),\n )\n}\n\n/** Unit length of one segment: text = char count, token = 1 atomic unit. */\nexport function segmentUnitLength(segment: TokenSegment): number {\n return segment.type === 'token' ? 1 : segment.value.length\n}\n\n/** Total unit length of a segment list (pills count as 1 unit each). */\nexport function segmentsUnitLength(segments: TokenSegment[]): number {\n return segments.reduce((sum, segment) => sum + segmentUnitLength(segment), 0)\n}\n\n/**\n * Extracts [from, to) in unit offsets. Tokens are atomic: since a token is\n * exactly 1 unit, an integer range either includes it wholly or not at all\n * — a caret can never split a pill.\n */\nexport function sliceSegmentsByUnits(\n segments: TokenSegment[],\n from: number,\n to: number,\n): TokenSegment[] {\n const out: TokenSegment[] = []\n let position = 0\n for (const segment of segments) {\n const length = segmentUnitLength(segment)\n const start = Math.max(from, position)\n const stop = Math.min(to, position + length)\n if (stop > start) {\n if (segment.type === 'token') {\n out.push({ ...segment })\n } else {\n out.push({\n type: 'text',\n value: segment.value.slice(start - position, stop - position),\n })\n }\n }\n position += length\n }\n return normalizeSegments(out)\n}\n\n/**\n * Splices `replacement` into `segments` at the unit-offset selection,\n * replacing any selected range — the caret-preserving insert used by the\n * {x} picker (AGL-583 semantics, pill-aware). A null/undefined start means\n * \"no caret captured\": the replacement appends at the end. Returns the new\n * segment list and the caret unit just after the inserted content.\n */\nexport function spliceSegmentsAtUnits(\n segments: TokenSegment[],\n replacement: TokenSegment[],\n start?: number | null,\n end?: number | null,\n): { segments: TokenSegment[]; caretUnit: number } {\n const length = segmentsUnitLength(segments)\n const clamp = (value: number) => Math.min(Math.max(value, 0), length)\n const at = start == null ? length : clamp(start)\n const to = end == null ? at : Math.max(clamp(end), at)\n const next = normalizeSegments([\n ...sliceSegmentsByUnits(segments, 0, at),\n ...replacement,\n ...sliceSegmentsByUnits(segments, to, Infinity),\n ])\n return { segments: next, caretUnit: at + segmentsUnitLength(replacement) }\n}\n\n/** A single token segment for `spliceSegmentsAtUnits` insertion. */\nexport function tokenSegment(token: string): TokenSegment {\n return { type: 'token', value: token, token }\n}\n\n/** A single text segment for `spliceSegmentsAtUnits` insertion. */\nexport function textSegment(text: string): TokenSegment {\n return { type: 'text', value: text }\n}\n\n/** Which catalog family a token belongs to — drives the pill color. */\nexport type TokenGroup =\n | 'variable'\n | 'function'\n | 'entry'\n | 'collection'\n /** `{{item.*}}` — a field of the record a repeat is rendering. */\n | 'item'\n | 'property'\n | 'host'\n | 'unknown'\n\n/**\n * Display-name inputs for {@link resolveTokenLabel}: the picker options\n * (which already carry friendly labels for every insertable token), the\n * host's variable/function docs keyed by id (AGL-194), and the fields of\n * the entity the nearest ancestor repeat names (id → current display name).\n */\nexport interface TokenLabelContext {\n options?: BindingOption[]\n variables?: Record<string, { name?: string } | undefined>\n functions?: Record<string, { name?: string } | undefined>\n itemFields?: Array<{ id: string; label: string }>\n}\n\nexport interface ResolvedTokenLabel {\n /** Friendly display name (the CURRENT name — ids stay in storage). */\n label: string\n /** Family for the pill color; shape-derived, stable across renames. */\n group: TokenGroup\n /** False when the referent can't be resolved (warning-colored pill). */\n known: boolean\n}\n\nconst stripBraces = (token: string): string =>\n token.replace(/^\\{\\{\\s*/, '').replace(/\\s*\\}\\}$/, '')\n\n/** Whitespace-insensitive raw-token comparison (`{{ var:x }}` ≡ `{{var:x}}`). */\nconst canonical = (token: string): string => token.replace(/\\s+/g, '')\n\n/**\n * Resolves a raw token to its display name (AGL-586 requirement 2: users\n * see NAMES, storage keeps IDS). The group comes from the token's shape so\n * pills stay consistently colored even when the referent is missing;\n * `known: false` marks unresolvable tokens for warning styling with the\n * raw token surfaced as the tooltip.\n */\nexport function resolveTokenLabel(\n token: string,\n context: TokenLabelContext = {},\n): ResolvedTokenLabel {\n const inner = stripBraces(token).trim()\n const optionByToken = (candidate: string): BindingOption | undefined =>\n (context.options ?? []).find(\n (option) => canonical(option.token) === canonical(candidate),\n )\n\n const variableMatch = /^var:([^\\s(){}]+)$/.exec(inner)\n if (variableMatch) {\n const id = variableMatch[1] as string\n const name =\n context.variables?.[id]?.name ?? optionByToken(`{{var:${id}}}`)?.label\n return { label: name ?? id, group: 'variable', known: Boolean(name) }\n }\n\n const functionMatch = /^fn:([^(){}]+)\\(([^)]*)\\)$/.exec(inner)\n if (functionMatch) {\n const id = String(functionMatch[1]).trim()\n // A stored call's args differ from the picker's parameter template, so\n // options match on the `{{fn:id(` prefix rather than the whole token.\n const name =\n context.functions?.[id]?.name ??\n (context.options ?? []).find((option) =>\n canonical(option.token).startsWith(canonical(`{{fn:${id}(`)),\n )?.label\n return { label: name ?? id, group: 'function', known: Boolean(name) }\n }\n\n if (inner.startsWith('entry.')) {\n const entry = ENTRY_TOKEN_CATALOG.find(\n (candidate) => canonical(candidate.token) === canonical(`{{${inner}}}`),\n )\n return { label: entry?.label ?? inner, group: 'entry', known: Boolean(entry) }\n }\n\n // `{{pagination.*}}` (AGL-1386) resolves on the same collection list pages\n // and lives in the same catalog, so it shares the collection pill rather\n // than reading as an unresolvable token in warning colors.\n if (inner.startsWith('collection.') || inner.startsWith('pagination.')) {\n const entry = COLLECTION_TOKEN_CATALOG.find(\n (candidate) => canonical(candidate.token) === canonical(`{{${inner}}}`),\n )\n return {\n label: entry?.label ?? inner,\n group: 'collection',\n known: Boolean(entry),\n }\n }\n\n /*\n * A component's own property (AGL-1335), named the way the Attributes panel\n * names it. Known only where the picker offers it — inside the component\n * that declares it — because that is the only place the token substitutes:\n * the same pill on an ordinary screen, or naming a property since removed,\n * resolves to nothing on the page and says so in warning colors.\n */\n const propertyMatch = /^prop\\.([A-Za-z_][A-Za-z0-9_]*)$/.exec(inner)\n if (propertyMatch) {\n const option = optionByToken(`{{${inner}}}`)\n return {\n label: option?.label ?? (propertyMatch[1] as string),\n group: 'property',\n known: Boolean(option),\n }\n }\n\n /*\n * A host variable (AGL-1022), named from the registry that resolves it\n * (AGL-2881), so the pill reads \"Business name\" wherever the token sits and\n * every surface agrees on what exists. A name the registry does not declare\n * renders nothing on the page, and says so in warning colors.\n */\n const hostMatch = /^host\\.([a-zA-Z][a-zA-Z0-9_]*)$/.exec(inner)\n if (hostMatch) {\n const definition = hostTokenDefinition(hostMatch[1] as string)\n return {\n label: definition?.label ?? inner,\n group: 'host',\n known: Boolean(definition),\n }\n }\n\n const itemMatch = /^item\\.([^.\\s{}]+)(?:\\.([^.\\s{}]+))?$/.exec(inner)\n if (itemMatch) {\n const fieldId = itemMatch[1] as string\n const hopId = itemMatch[2]\n const field = (context.itemFields ?? []).find(\n (candidate) => candidate.id === fieldId,\n )\n const label = field\n ? hopId\n ? `${field.label} → ${humanizeFieldId(hopId)}`\n : field.label\n : inner\n return { label, group: 'item', known: Boolean(field) }\n }\n\n return { label: inner || token, group: 'unknown', known: false }\n}\n\n/**\n * A stored field id read as words, for a hop the canvas names without the\n * target's own label: \"roast_preference\" → \"Roast preference\".\n */\nfunction humanizeFieldId(id: string): string {\n const words = id.replace(/_/g, ' ').trim()\n return words ? words.charAt(0).toUpperCase() + words.slice(1) : id\n}\n"],"names":["COLLECTION_TOKEN_CATALOG","ENTRY_TOKEN_CATALOG","hostTokenDefinition","TOKEN_SEGMENT_PATTERN","normalizeSegments","segments","out","segment","type","value","last","length","push","parseTokenSegments","text","cursor","pattern","RegExp","source","match","exec","index","slice","token","serializeTokenSegments","map","join","hasUnmaterializedTokens","probe","some","test","segmentUnitLength","segmentsUnitLength","reduce","sum","sliceSegmentsByUnits","from","to","position","start","Math","max","stop","min","spliceSegmentsAtUnits","replacement","end","clamp","at","next","Infinity","caretUnit","tokenSegment","textSegment","stripBraces","replace","canonical","resolveTokenLabel","context","inner","trim","optionByToken","candidate","options","find","option","variableMatch","id","name","variables","label","group","known","Boolean","functionMatch","String","functions","startsWith","entry","propertyMatch","hostMatch","definition","itemMatch","fieldId","hopId","field","itemFields","humanizeFieldId","words","charAt","toUpperCase"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,wBAAwB,EACxBC,mBAAmB,EACnBC,mBAAmB,QACd,eAAc;AAyBrB;;;;CAIC,GACD,OAAO,MAAMC,wBAAwB,kBAAiB;AAEtD,6DAA6D,GAC7D,SAASC,kBAAkBC,QAAwB;IACjD,MAAMC,MAAsB,EAAE;IAC9B,KAAK,MAAMC,WAAWF,SAAU;QAC9B,IAAIE,QAAQC,IAAI,KAAK,UAAU,CAACD,QAAQE,KAAK,EAAE;QAC/C,MAAMC,OAAOJ,GAAG,CAACA,IAAIK,MAAM,GAAG,EAAE;QAChC,IAAIJ,QAAQC,IAAI,KAAK,UAAUE,CAAAA,wBAAAA,KAAMF,IAAI,MAAK,QAAQ;YACpDE,KAAKD,KAAK,IAAIF,QAAQE,KAAK;QAC7B,OAAO;YACLH,IAAIM,IAAI,CAAC,aAAKL;QAChB;IACF;IACA,OAAOD;AACT;AAEA,qEAAqE,GACrE,OAAO,SAASO,mBAAmBC,IAAY;IAC7C,MAAMT,WAA2B,EAAE;IACnC,IAAIU,SAAS;IACb,MAAMC,UAAU,IAAIC,OAAOd,sBAAsBe,MAAM,EAAE;IACzD,IAAK,IAAIC,QAAQH,QAAQI,IAAI,CAACN,OAAOK,OAAOA,QAAQH,QAAQI,IAAI,CAACN,MAAO;QACtE,IAAIK,MAAME,KAAK,GAAGN,QAAQ;YACxBV,SAASO,IAAI,CAAC;gBAAEJ,MAAM;gBAAQC,OAAOK,KAAKQ,KAAK,CAACP,QAAQI,MAAME,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wCAAwC9D,IAAI,CAACuC;IAC/D,IAAIuB,WAAW;YAGExB;QAFf,MAAMyB,UAAUD,SAAS,CAAC,EAAE;QAC5B,MAAME,QAAQF,SAAS,CAAC,EAAE;QAC1B,MAAMG,QAAQ,EAAC3B,sBAAAA,QAAQ4B,UAAU,YAAlB5B,sBAAsB,EAAE,EAAEM,IAAI,CAC3C,CAACF,YAAcA,UAAUK,EAAE,KAAKgB;QAElC,MAAMb,QAAQe,QACVD,QACE,GAAGC,MAAMf,KAAK,CAAC,GAAG,EAAEiB,gBAAgBH,QAAQ,GAC5CC,MAAMf,KAAK,GACbX;QACJ,OAAO;YAAEW;YAAOC,OAAO;YAAQC,OAAOC,QAAQY;QAAO;IACvD;IAEA,OAAO;QAAEf,OAAOX,SAASpC;QAAOgD,OAAO;QAAWC,OAAO;IAAM;AACjE;AAEA;;;CAGC,GACD,SAASe,gBAAgBpB,EAAU;IACjC,MAAMqB,QAAQrB,GAAGZ,OAAO,CAAC,MAAM,KAAKK,IAAI;IACxC,OAAO4B,QAAQA,MAAMC,MAAM,CAAC,GAAGC,WAAW,KAAKF,MAAMlE,KAAK,CAAC,KAAK6C;AAClE"}
1
+ {"version":3,"sources":["../../../../../../../../libs/besigner/feature/designer/src/lib/utils/token-segments.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n COLLECTION_TOKEN_CATALOG,\n ENTRY_TOKEN_CATALOG,\n hostTokenDefinition,\n} from '@aglyn/aglyn'\n\nimport type { BindingOption } from '../contexts/binding-picker-context'\n\n/**\n * Token-pill segment model (AGL-586). Stored prop strings keep the raw\n * id-based `{{...}}` grammar (AGL-100/185) — these helpers only SPLIT a\n * string into runs of plain text and atomic tokens so editors can render\n * the tokens as friendly, clickable pills. Serializing the segments always\n * reproduces the exact input string; nothing here ever rewrites a token.\n *\n * Offset model: editor carets address \"units\", where every plain-text\n * character is 1 unit and every token — however long its raw text — is 1\n * atomic unit. A caret can therefore sit before or after a pill but never\n * inside one, which is exactly how the pills behave in the DOM\n * (`contenteditable=\"false\"`).\n */\nexport interface TokenSegment {\n type: 'text' | 'token'\n /** The literal slice of the serialized string (raw `{{...}}` for tokens). */\n value: string\n /** Set on token segments: the raw token, identical to `value`. */\n token?: string\n}\n\n/**\n * Any `{{...}}` occurrence without nested braces — var:/fn:/entry./\n * collection./item.* AND unknown tokens alike. `{{a{{b}}` yields the text\n * `{{a` plus the token `{{b}}` (the opener without a closer is plain text).\n */\nexport const TOKEN_SEGMENT_PATTERN = /\\{\\{[^{}]*\\}\\}/g\n\n/** Drops empty text runs and merges adjacent text segments. */\nfunction normalizeSegments(segments: TokenSegment[]): TokenSegment[] {\n const out: TokenSegment[] = []\n for (const segment of segments) {\n if (segment.type === 'text' && !segment.value) continue\n const last = out[out.length - 1]\n if (segment.type === 'text' && last?.type === 'text') {\n last.value += segment.value\n } else {\n out.push({ ...segment })\n }\n }\n return out\n}\n\n/** Splits `text` on `{{...}}` occurrences into text/token segments. */\nexport function parseTokenSegments(text: string): TokenSegment[] {\n const segments: TokenSegment[] = []\n let cursor = 0\n const pattern = new RegExp(TOKEN_SEGMENT_PATTERN.source, 'g')\n for (let match = pattern.exec(text); match; match = pattern.exec(text)) {\n if (match.index > cursor) {\n segments.push({ type: 'text', value: text.slice(cursor, match.index) })\n }\n segments.push({ type: 'token', value: match[0], token: match[0] })\n cursor = match.index + match[0].length\n }\n if (cursor < text.length) {\n segments.push({ type: 'text', value: text.slice(cursor) })\n }\n return segments\n}\n\n/** Joins segments back to the exact stored string (lossless round-trip). */\nexport function serializeTokenSegments(segments: TokenSegment[]): string {\n return segments.map((segment) => segment.value).join('')\n}\n\n/** True when any text run still holds a complete raw `{{...}}` token. */\nexport function hasUnmaterializedTokens(segments: TokenSegment[]): boolean {\n const probe = new RegExp(TOKEN_SEGMENT_PATTERN.source)\n return segments.some(\n (segment) => segment.type === 'text' && probe.test(segment.value),\n )\n}\n\n/** Unit length of one segment: text = char count, token = 1 atomic unit. */\nexport function segmentUnitLength(segment: TokenSegment): number {\n return segment.type === 'token' ? 1 : segment.value.length\n}\n\n/** Total unit length of a segment list (pills count as 1 unit each). */\nexport function segmentsUnitLength(segments: TokenSegment[]): number {\n return segments.reduce((sum, segment) => sum + segmentUnitLength(segment), 0)\n}\n\n/**\n * Extracts [from, to) in unit offsets. Tokens are atomic: since a token is\n * exactly 1 unit, an integer range either includes it wholly or not at all\n * — a caret can never split a pill.\n */\nexport function sliceSegmentsByUnits(\n segments: TokenSegment[],\n from: number,\n to: number,\n): TokenSegment[] {\n const out: TokenSegment[] = []\n let position = 0\n for (const segment of segments) {\n const length = segmentUnitLength(segment)\n const start = Math.max(from, position)\n const stop = Math.min(to, position + length)\n if (stop > start) {\n if (segment.type === 'token') {\n out.push({ ...segment })\n } else {\n out.push({\n type: 'text',\n value: segment.value.slice(start - position, stop - position),\n })\n }\n }\n position += length\n }\n return normalizeSegments(out)\n}\n\n/**\n * Splices `replacement` into `segments` at the unit-offset selection,\n * replacing any selected range — the caret-preserving insert used by the\n * {x} picker (AGL-583 semantics, pill-aware). A null/undefined start means\n * \"no caret captured\": the replacement appends at the end. Returns the new\n * segment list and the caret unit just after the inserted content.\n */\nexport function spliceSegmentsAtUnits(\n segments: TokenSegment[],\n replacement: TokenSegment[],\n start?: number | null,\n end?: number | null,\n): { segments: TokenSegment[]; caretUnit: number } {\n const length = segmentsUnitLength(segments)\n const clamp = (value: number) => Math.min(Math.max(value, 0), length)\n const at = start == null ? length : clamp(start)\n const to = end == null ? at : Math.max(clamp(end), at)\n const next = normalizeSegments([\n ...sliceSegmentsByUnits(segments, 0, at),\n ...replacement,\n ...sliceSegmentsByUnits(segments, to, Infinity),\n ])\n return { segments: next, caretUnit: at + segmentsUnitLength(replacement) }\n}\n\n/** A single token segment for `spliceSegmentsAtUnits` insertion. */\nexport function tokenSegment(token: string): TokenSegment {\n return { type: 'token', value: token, token }\n}\n\n/** A single text segment for `spliceSegmentsAtUnits` insertion. */\nexport function textSegment(text: string): TokenSegment {\n return { type: 'text', value: text }\n}\n\n/** Which catalog family a token belongs to — drives the pill color. */\nexport type TokenGroup =\n | 'variable'\n | 'function'\n | 'entry'\n | 'collection'\n /** `{{item.*}}` — a field of the record a repeat is rendering. */\n | 'item'\n | 'property'\n | 'host'\n | 'unknown'\n\n/**\n * Display-name inputs for {@link resolveTokenLabel}: the picker options\n * (which already carry friendly labels for every insertable token), the\n * host's variable/function docs keyed by id (AGL-194), and the fields of\n * the entity the nearest ancestor repeat names (id → current display name).\n */\nexport interface TokenLabelContext {\n options?: BindingOption[]\n variables?: Record<string, { name?: string } | undefined>\n functions?: Record<string, { name?: string } | undefined>\n itemFields?: ReadonlyArray<{ id: string; label: string }>\n}\n\nexport interface ResolvedTokenLabel {\n /** Friendly display name (the CURRENT name — ids stay in storage). */\n label: string\n /** Family for the pill color; shape-derived, stable across renames. */\n group: TokenGroup\n /** False when the referent can't be resolved (warning-colored pill). */\n known: boolean\n}\n\nconst stripBraces = (token: string): string =>\n token.replace(/^\\{\\{\\s*/, '').replace(/\\s*\\}\\}$/, '')\n\n/** Whitespace-insensitive raw-token comparison (`{{ var:x }}` ≡ `{{var:x}}`). */\nconst canonical = (token: string): string => token.replace(/\\s+/g, '')\n\n/**\n * Resolves a raw token to its display name (AGL-586 requirement 2: users\n * see NAMES, storage keeps IDS). The group comes from the token's shape so\n * pills stay consistently colored even when the referent is missing;\n * `known: false` marks unresolvable tokens for warning styling with the\n * raw token surfaced as the tooltip.\n */\nexport function resolveTokenLabel(\n token: string,\n context: TokenLabelContext = {},\n): ResolvedTokenLabel {\n const inner = stripBraces(token).trim()\n const optionByToken = (candidate: string): BindingOption | undefined =>\n (context.options ?? []).find(\n (option) => canonical(option.token) === canonical(candidate),\n )\n\n const variableMatch = /^var:([^\\s(){}]+)$/.exec(inner)\n if (variableMatch) {\n const id = variableMatch[1] as string\n const name =\n context.variables?.[id]?.name ?? optionByToken(`{{var:${id}}}`)?.label\n return { label: name ?? id, group: 'variable', known: Boolean(name) }\n }\n\n const functionMatch = /^fn:([^(){}]+)\\(([^)]*)\\)$/.exec(inner)\n if (functionMatch) {\n const id = String(functionMatch[1]).trim()\n // A stored call's args differ from the picker's parameter template, so\n // options match on the `{{fn:id(` prefix rather than the whole token.\n const name =\n context.functions?.[id]?.name ??\n (context.options ?? []).find((option) =>\n canonical(option.token).startsWith(canonical(`{{fn:${id}(`)),\n )?.label\n return { label: name ?? id, group: 'function', known: Boolean(name) }\n }\n\n if (inner.startsWith('entry.')) {\n const entry = ENTRY_TOKEN_CATALOG.find(\n (candidate) => canonical(candidate.token) === canonical(`{{${inner}}}`),\n )\n return { label: entry?.label ?? inner, group: 'entry', known: Boolean(entry) }\n }\n\n // `{{pagination.*}}` (AGL-1386) resolves on the same collection list pages\n // and lives in the same catalog, so it shares the collection pill rather\n // than reading as an unresolvable token in warning colors.\n if (inner.startsWith('collection.') || inner.startsWith('pagination.')) {\n const entry = COLLECTION_TOKEN_CATALOG.find(\n (candidate) => canonical(candidate.token) === canonical(`{{${inner}}}`),\n )\n return {\n label: entry?.label ?? inner,\n group: 'collection',\n known: Boolean(entry),\n }\n }\n\n /*\n * A component's own property (AGL-1335), named the way the Attributes panel\n * names it. Known only where the picker offers it — inside the component\n * that declares it — because that is the only place the token substitutes:\n * the same pill on an ordinary screen, or naming a property since removed,\n * resolves to nothing on the page and says so in warning colors.\n */\n const propertyMatch = /^prop\\.([A-Za-z_][A-Za-z0-9_]*)$/.exec(inner)\n if (propertyMatch) {\n const option = optionByToken(`{{${inner}}}`)\n return {\n label: option?.label ?? (propertyMatch[1] as string),\n group: 'property',\n known: Boolean(option),\n }\n }\n\n /*\n * A host variable (AGL-1022), named from the registry that resolves it\n * (AGL-2881), so the pill reads \"Business name\" wherever the token sits and\n * every surface agrees on what exists. A name the registry does not declare\n * renders nothing on the page, and says so in warning colors.\n */\n const hostMatch = /^host\\.([a-zA-Z][a-zA-Z0-9_]*)$/.exec(inner)\n if (hostMatch) {\n const definition = hostTokenDefinition(hostMatch[1] as string)\n return {\n label: definition?.label ?? inner,\n group: 'host',\n known: Boolean(definition),\n }\n }\n\n const itemMatch = /^item\\.([^.\\s{}]+)(?:\\.([^.\\s{}]+))?$/.exec(inner)\n if (itemMatch) {\n const fieldId = itemMatch[1] as string\n const hopId = itemMatch[2]\n const field = (context.itemFields ?? []).find(\n (candidate) => candidate.id === fieldId,\n )\n const label = field\n ? hopId\n ? `${field.label} → ${humanizeFieldId(hopId)}`\n : field.label\n : inner\n return { label, group: 'item', known: Boolean(field) }\n }\n\n return { label: inner || token, group: 'unknown', known: false }\n}\n\n/**\n * A stored field id read as words, for a hop the canvas names without the\n * target's own label: \"roast_preference\" → \"Roast preference\".\n */\nfunction humanizeFieldId(id: string): string {\n const words = id.replace(/_/g, ' ').trim()\n return words ? words.charAt(0).toUpperCase() + words.slice(1) : id\n}\n"],"names":["COLLECTION_TOKEN_CATALOG","ENTRY_TOKEN_CATALOG","hostTokenDefinition","TOKEN_SEGMENT_PATTERN","normalizeSegments","segments","out","segment","type","value","last","length","push","parseTokenSegments","text","cursor","pattern","RegExp","source","match","exec","index","slice","token","serializeTokenSegments","map","join","hasUnmaterializedTokens","probe","some","test","segmentUnitLength","segmentsUnitLength","reduce","sum","sliceSegmentsByUnits","from","to","position","start","Math","max","stop","min","spliceSegmentsAtUnits","replacement","end","clamp","at","next","Infinity","caretUnit","tokenSegment","textSegment","stripBraces","replace","canonical","resolveTokenLabel","context","inner","trim","optionByToken","candidate","options","find","option","variableMatch","id","name","variables","label","group","known","Boolean","functionMatch","String","functions","startsWith","entry","propertyMatch","hostMatch","definition","itemMatch","fieldId","hopId","field","itemFields","humanizeFieldId","words","charAt","toUpperCase"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,wBAAwB,EACxBC,mBAAmB,EACnBC,mBAAmB,QACd,eAAc;AAyBrB;;;;CAIC,GACD,OAAO,MAAMC,wBAAwB,kBAAiB;AAEtD,6DAA6D,GAC7D,SAASC,kBAAkBC,QAAwB;IACjD,MAAMC,MAAsB,EAAE;IAC9B,KAAK,MAAMC,WAAWF,SAAU;QAC9B,IAAIE,QAAQC,IAAI,KAAK,UAAU,CAACD,QAAQE,KAAK,EAAE;QAC/C,MAAMC,OAAOJ,GAAG,CAACA,IAAIK,MAAM,GAAG,EAAE;QAChC,IAAIJ,QAAQC,IAAI,KAAK,UAAUE,CAAAA,wBAAAA,KAAMF,IAAI,MAAK,QAAQ;YACpDE,KAAKD,KAAK,IAAIF,QAAQE,KAAK;QAC7B,OAAO;YACLH,IAAIM,IAAI,CAAC,aAAKL;QAChB;IACF;IACA,OAAOD;AACT;AAEA,qEAAqE,GACrE,OAAO,SAASO,mBAAmBC,IAAY;IAC7C,MAAMT,WAA2B,EAAE;IACnC,IAAIU,SAAS;IACb,MAAMC,UAAU,IAAIC,OAAOd,sBAAsBe,MAAM,EAAE;IACzD,IAAK,IAAIC,QAAQH,QAAQI,IAAI,CAACN,OAAOK,OAAOA,QAAQH,QAAQI,IAAI,CAACN,MAAO;QACtE,IAAIK,MAAME,KAAK,GAAGN,QAAQ;YACxBV,SAASO,IAAI,CAAC;gBAAEJ,MAAM;gBAAQC,OAAOK,KAAKQ,KAAK,CAACP,QAAQI,MAAME,KAAK;YAAE;QACvE;QACAhB,SAASO,IAAI,CAAC;YAAEJ,MAAM;YAASC,OAAOU,KAAK,CAAC,EAAE;YAAEI,OAAOJ,KAAK,CAAC,EAAE;QAAC;QAChEJ,SAASI,MAAME,KAAK,GAAGF,KAAK,CAAC,EAAE,CAACR,MAAM;IACxC;IACA,IAAII,SAASD,K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