@namroodinc/liquid-editorial 0.10.2 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/UPGRADING.md +61 -0
- package/dist/chunks/{ColourField-B03ejnGS.cjs → ColourField--rS9KDpq.cjs} +2 -2
- package/dist/chunks/{ColourField-B03ejnGS.cjs.map → ColourField--rS9KDpq.cjs.map} +1 -1
- package/dist/chunks/{ColourField-D17gkytm.js → ColourField-DkO8tjeB.js} +5 -5
- package/dist/chunks/{ColourField-D17gkytm.js.map → ColourField-DkO8tjeB.js.map} +1 -1
- package/dist/chunks/{DatePicker-0uvnuiye.js → DatePicker-B8tllGYy.js} +20 -20
- package/dist/chunks/{DatePicker-0uvnuiye.js.map → DatePicker-B8tllGYy.js.map} +1 -1
- package/dist/chunks/{DatePicker-CVaefhfS.cjs → DatePicker-OiqjoO-f.cjs} +2 -2
- package/dist/chunks/{DatePicker-CVaefhfS.cjs.map → DatePicker-OiqjoO-f.cjs.map} +1 -1
- package/dist/chunks/{EntryPicker-CiS8zT64.cjs → EntryPicker-BI_7g2Wg.cjs} +2 -2
- package/dist/chunks/{EntryPicker-CiS8zT64.cjs.map → EntryPicker-BI_7g2Wg.cjs.map} +1 -1
- package/dist/chunks/{EntryPicker-LWwX_EzL.js → EntryPicker-KxHZzZsh.js} +2 -2
- package/dist/chunks/{EntryPicker-LWwX_EzL.js.map → EntryPicker-KxHZzZsh.js.map} +1 -1
- package/dist/chunks/{FormEditor-BZ_4nxIG.cjs → FormEditor-BJcAIVcL.cjs} +2 -2
- package/dist/chunks/{FormEditor-BZ_4nxIG.cjs.map → FormEditor-BJcAIVcL.cjs.map} +1 -1
- package/dist/chunks/{FormEditor-IKdPwVPx.js → FormEditor-CdLqPaKK.js} +6 -6
- package/dist/chunks/{FormEditor-IKdPwVPx.js.map → FormEditor-CdLqPaKK.js.map} +1 -1
- package/dist/chunks/RichTextEditor-BXyhSeJd.cjs +2 -0
- package/dist/chunks/RichTextEditor-BXyhSeJd.cjs.map +1 -0
- package/dist/chunks/{RichTextEditor-CwoHE-AN.js → RichTextEditor-DmNM63Wg.js} +369 -280
- package/dist/chunks/RichTextEditor-DmNM63Wg.js.map +1 -0
- package/dist/chunks/{use-picker-session-BLH1tXk3.js → use-picker-session-BDEWL2jK.js} +8 -8
- package/dist/chunks/use-picker-session-BDEWL2jK.js.map +1 -0
- package/dist/chunks/use-picker-session-C4FGinLN.cjs +2 -0
- package/dist/chunks/use-picker-session-C4FGinLN.cjs.map +1 -0
- package/dist/components/ColourField/index.cjs +1 -1
- package/dist/components/ColourField/index.js +1 -1
- package/dist/components/DatePicker/index.cjs +1 -1
- package/dist/components/DatePicker/index.js +1 -1
- package/dist/components/EntryPicker/index.cjs +1 -1
- package/dist/components/EntryPicker/index.js +1 -1
- package/dist/components/EntryPicker/item.d.cts +1 -3
- package/dist/components/EntryPicker/item.d.cts.map +1 -1
- package/dist/components/EntryPicker/item.d.ts +1 -3
- package/dist/components/EntryPicker/item.d.ts.map +1 -1
- package/dist/components/FormEditor/README.md +20 -8
- package/dist/components/FormEditor/index.cjs +1 -1
- package/dist/components/FormEditor/index.js +1 -1
- package/dist/components/RichTextEditor/index.cjs +1 -1
- package/dist/components/RichTextEditor/index.js +1 -1
- package/dist/components/RichTextEditor/storyblock-view.d.cts +1 -1
- package/dist/components/RichTextEditor/storyblock-view.d.cts.map +1 -1
- package/dist/components/RichTextEditor/storyblock-view.d.ts +1 -1
- package/dist/components/RichTextEditor/storyblock-view.d.ts.map +1 -1
- package/dist/components/RichTextEditor/style.css +84 -29
- package/dist/index.cjs +1 -1
- package/dist/index.js +17 -17
- package/package.json +1 -1
- package/dist/chunks/RichTextEditor-CwoHE-AN.js.map +0 -1
- package/dist/chunks/RichTextEditor-DMrxJhA6.cjs +0 -2
- package/dist/chunks/RichTextEditor-DMrxJhA6.cjs.map +0 -1
- package/dist/chunks/use-picker-session-BLH1tXk3.js.map +0 -1
- package/dist/chunks/use-picker-session-tRDYUd_d.cjs +0 -2
- package/dist/chunks/use-picker-session-tRDYUd_d.cjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"RichTextEditor-DmNM63Wg.js","names":["_jsx","noItems","_Fragment","Icon","mergeRefs","cannotHoldFocus","focusNearest","PortalScopeContext","useLatest","moveHost","useMovableHost","useIsomorphicLayoutEffect","useLoadError","PickerDialog","EntryRow","useSelectedItems","chosenItems","usePickerSession","Fragment$1","revealCaretInContent","content","host","caret","editor","view","useEditorExpansion","expanded","setExpanded","useState","inlineHeight","setInlineHeight","inlineSlotRef","useRef","expandedSlotRef","toggleRef","restoreToggle","shownExpanded","dialogId","useId","disabled","isHeld","collapse","useCallback","frameRef","toggleLabel","jsx","Button","event","createPortal","surface","Modal","label","expandedWidth","invalid","labelledBy","validStoryblock","text","value","attrs","storyblockDocument","node","Storyblock","Node","key","element","mergeAttributes","HTMLAttributes","emptyDocument","baseExtensions","StarterKit","Link","richTextExtensions","storyblock","schema","getSchema","normalizeDocument","document","documentError","check","type","mark","markType","canEmbed","source","EmbedContext","createContext","noItems$1","alignments","barActions","focusSteps","moveBarFocus","step","buttons","index","target","useBarFocus","current","setCurrent","hasFocus","setHasFocus","isActive","isSelected","tabStop","available","action","useStoryblockItem","useContext","views","kind","items","ids","useMemo","id","picked","seed","itemId","selection","pick","forgetSeed","hasResolver","item","known","failures","failure","isStatic","each","StoryblockHandle","isMovable","onSelect","Badge","StoryblockBar","offered","canReplace","onEdit","isLocked","name","barProps","ButtonGroup","control","option","align","onAlign","onReplace","onRemove","StoryblockBody","missing","StoryblockView","editItem","selected","select","position","getPos","NodeViewWrapper","busy","updateAttributes","replace","embedCommitMeta","kinds","labels","noSources","noItems","blockAttrs","embedReason","restrictions","isTarget","session","stepMaps","transactions","transaction","mapBlock","pos","map","at","kept","oldStart","oldEnd","newEnd","newStart","result","mapOrigin","start","from","end","to","replaced","inPlace","boundaryAfter","$position","doc","useSourceView","isPresent","hasEditor","refreshKey","isDialogHidden","resolve","edit","EmbedPicker","picker","close","itemLabel","useEmbeds","setSession","sessionIds","bookmark","picks","pickCount","setPickCount","sessionSource","sources","active","latest","appendedTransactions","origin","now","isReadOnly","commit","replacing","previous","chain","count","open","isBusy","next","range","$from","actions","stable","copy","entryView","assetView","context","revision","LinkDialog","href","setHref","error","setError","formId","onTransaction","onClose","canEdit","save","url","Field","TextField","field","GROUPS","EditorToolbar","i","group","tool","state","openLink","embedControl","toolbarExtra","expandControl","EditorFrame","forwardRef","scopeRef","className","expansion","isFocused","contentError","errorId","children","EditableStoryblock","ReactNodeViewRenderer","oldNode","newNode","updateProps","releaseUnboundEscape","handle","RichTextEditor","ariaLabel","describedBy","ariaInvalid","props","mergedRef","ref","setIsFocused","linkSelection","setLinkSelection","closeLink","initialValue","isInvalid","isDisabled","getMarkRange","link","attributes","isRequired","required","editorProps","anchor","extensions","Placeholder","placeholder","initialContent","useEditor","e","useEffect","createDocument","useEditorState","embeds","size","EditorContent"],"sources":["../../src/components/RichTextEditor/expansion.tsx","../../src/components/RichTextEditor/storyblock.ts","../../src/components/RichTextEditor/document.ts","../../src/components/RichTextEditor/embed-context.ts","../../src/components/RichTextEditor/storyblock-view.tsx","../../src/components/RichTextEditor/use-embeds.tsx","../../src/components/RichTextEditor/index.tsx"],"sourcesContent":["import {\n useCallback,\n useId,\n useRef,\n useState,\n type CSSProperties,\n type ReactNode,\n type RefObject,\n} from \"react\";\nimport { createPortal } from \"react-dom\";\nimport type { Editor } from \"@tiptap/react\";\nimport { cannotHoldFocus, focusNearest } from \"../../internal/dialogFocus\";\nimport { moveHost, useMovableHost } from \"../../internal/movableHost\";\nimport { useIsomorphicLayoutEffect } from \"../../internal/useIsomorphicLayoutEffect\";\nimport { Button } from \"../Button\";\nimport { Modal } from \"../Modal\";\nimport type { RichTextEditorExpandedWidth } from \"./expanded-width\";\n\nexport type { RichTextEditorExpandedWidth } from \"./expanded-width\";\n\n/**\n * Moving the host resets the content's scroll position, so bring the caret\n * back into the content's own view. This scrolls only the content and needs no\n * DOM selection, so it also works when focus returns to the toggle.\n */\nfunction revealCaretInContent(editor: Editor, host: HTMLElement) {\n const content = host.querySelector<HTMLElement>(\".ds-rte__content\");\n if (!content) {\n return;\n }\n const caret = editor.view.coordsAtPos(editor.state.selection.head);\n const view = content.getBoundingClientRect();\n if (caret.top < view.top || caret.bottom > view.bottom) {\n content.scrollTop += caret.top - view.top - view.height / 2;\n }\n}\n\ninterface EditorExpansionOptions {\n editor: Editor | null;\n disabled: boolean;\n /**\n * Keep an expanded view open while disabled: an embed's source is completing\n * a creation, and its block lands where the writer is working.\n */\n isHeld?: boolean;\n invalid: boolean;\n label: string;\n labelledBy?: string;\n expandedWidth: RichTextEditorExpandedWidth;\n frameRef: RefObject<HTMLDivElement | null>;\n}\n\n/**\n * The expanded writing view is a headerless Modal. The editor's surface renders\n * once into a movable host that sits in the inline frame or in the Modal's\n * body, so the same toolbar, content, editor instance and selection survive\n * every toggle. Modal owns the scrim, frame, dialog stack, focus trap, scroll\n * lock and Escape.\n */\nexport function useEditorExpansion({\n editor,\n disabled,\n isHeld = false,\n invalid,\n label,\n labelledBy,\n expandedWidth,\n frameRef,\n}: EditorExpansionOptions) {\n const host = useMovableHost(\"ds-rte__host\");\n const [expanded, setExpanded] = useState(false);\n const [inlineHeight, setInlineHeight] = useState(0);\n const inlineSlotRef = useRef<HTMLDivElement | null>(null);\n const expandedSlotRef = useRef<HTMLDivElement | null>(null);\n const toggleRef = useRef<HTMLButtonElement | null>(null);\n const restoreToggle = useRef(false);\n const shownExpanded = useRef(false);\n const dialogId = useId();\n\n if (expanded && disabled && !isHeld) {\n setExpanded(false);\n }\n\n const collapse = useCallback(() => {\n restoreToggle.current = document.activeElement === toggleRef.current;\n setExpanded(false);\n }, []);\n\n useIsomorphicLayoutEffect(() => {\n if (!host) {\n return;\n }\n moveHost(host, expanded ? expandedSlotRef.current : inlineSlotRef.current);\n // Only a change of mode hands focus and the caret across; other updates,\n // such as disabling while saving, leave the editor exactly where it is.\n if (shownExpanded.current === expanded) {\n return;\n }\n shownExpanded.current = expanded;\n // A disabled editor can't take focus. Keep it near the editor instead, in the\n // nearest focusable container such as an enclosing Drawer, not on the page.\n if (disabled || !editor) {\n if (cannotHoldFocus(document.activeElement)) {\n focusNearest(frameRef.current, { preventScroll: true });\n }\n return;\n }\n revealCaretInContent(editor, host);\n if (!expanded && restoreToggle.current) {\n // Focus decides what stays visible: the toggle, where the person left it.\n toggleRef.current?.focus();\n } else {\n // The writing surface takes focus, and the page or an enclosing panel\n // scrolls to its caret, which a growing inline editor needs on collapse.\n editor.view.focus();\n editor.commands.scrollIntoView();\n }\n restoreToggle.current = false;\n }, [host, expanded, editor, disabled, frameRef]);\n\n const toggleLabel = expanded ? \"Collapse editor\" : \"Expand editor\";\n const toggle = (\n <Button\n ref={toggleRef}\n size=\"sm\"\n isIconOnly\n iconStart={expanded ? \"minimize-2\" : \"maximize-2\"}\n className=\"ds-rte__expand\"\n aria-label={toggleLabel}\n title={toggleLabel}\n aria-expanded={expanded}\n aria-controls={expanded ? dialogId : undefined}\n isDisabled={disabled || !editor || !host}\n onMouseDown={(event) => event.preventDefault()}\n onClick={() => {\n if (expanded) {\n collapse();\n return;\n }\n setInlineHeight(frameRef.current!.getBoundingClientRect().height);\n setExpanded(true);\n }}\n />\n );\n\n /** The inline place for the surface: the host after hydration, inline markup before it. */\n const surfaceSlot = (surface: ReactNode) => (\n <div\n ref={inlineSlotRef}\n className=\"ds-rte__slot\"\n >\n {host ? createPortal(surface, host) : surface}\n </div>\n );\n\n const dialog = (\n <Modal\n id={dialogId}\n isOpen={expanded}\n onClose={collapse}\n title={label}\n hasHeader={false}\n size={expandedWidth === \"full\" ? \"full\" : \"wide\"}\n className=\"ds-rte__modal\"\n data-invalid={invalid || undefined}\n aria-labelledby={labelledBy}\n >\n <div\n ref={expandedSlotRef}\n className=\"ds-rte__expanded-slot\"\n />\n </Modal>\n );\n\n /** The inline frame keeps its measured height while the surface is away. */\n const frameStyle: CSSProperties | undefined = expanded\n ? { minBlockSize: inlineHeight }\n : undefined;\n\n return { expanded, toggle, surfaceSlot, dialog, frameStyle };\n}\n","import { Node, mergeAttributes, type JSONContent } from \"@tiptap/react\";\n\nexport type StoryblockAlignment = \"left\" | \"full\" | \"right\";\nexport type StoryblockIdentity =\n { type: \"entry\"; id: string; entryId: string } | { type: \"asset\"; assetId: string };\nexport type StoryblockAttributes = StoryblockIdentity & { align: StoryblockAlignment };\n\nexport function validStoryblock(attrs: Record<string, unknown>): boolean {\n const text = (value: unknown) => typeof value === \"string\" && value.trim().length > 0;\n return (\n [\"left\", \"full\", \"right\"].includes(attrs.align == null ? \"full\" : (attrs.align as string)) &&\n (attrs.type === \"entry\"\n ? text(attrs.id) && text(attrs.entryId) && attrs.assetId == null\n : attrs.type === \"asset\" && text(attrs.assetId) && attrs.id == null && attrs.entryId == null)\n );\n}\n\n/** Strip schema defaults belonging to the other kind from the external document. */\nexport function storyblockDocument<T extends JSONContent>(node: T): T {\n return {\n ...node,\n ...(node.type === \"storyblock\" && node.attrs\n ? {\n attrs: {\n type: node.attrs.type,\n ...(node.attrs.type === \"entry\"\n ? { id: node.attrs.id, entryId: node.attrs.entryId }\n : { assetId: node.attrs.assetId }),\n align: node.attrs.align ?? \"full\",\n },\n }\n : {}),\n ...(node.content ? { content: node.content.map(storyblockDocument) } : {}),\n };\n}\n\n/** Schema and HTML representation contain references only, never resolved item data. */\nexport const Storyblock = Node.create({\n name: \"storyblock\",\n group: \"block\",\n atom: true,\n draggable: true,\n selectable: true,\n marks: \"\",\n addAttributes() {\n return Object.fromEntries(\n [\"type\", \"id\", \"entryId\", \"assetId\", \"align\"].map((key) => [\n key,\n {\n default: key === \"align\" ? \"full\" : null,\n parseHTML: (element: HTMLElement) =>\n element.getAttribute(`data-storyblock-${key.toLowerCase()}`),\n renderHTML: () => ({}),\n },\n ]),\n );\n },\n parseHTML() {\n return [\n {\n tag: \"div[data-storyblock]\",\n getAttrs: (element) => {\n const attrs = Object.fromEntries(\n [\"type\", \"id\", \"entryId\", \"assetId\", \"align\"].map((key) => [\n key,\n element.getAttribute(`data-storyblock-${key.toLowerCase()}`),\n ]),\n );\n return validStoryblock(attrs) ? null : false;\n },\n },\n ];\n },\n renderHTML({ node, HTMLAttributes }) {\n const attrs = storyblockDocument({ type: \"storyblock\", attrs: node.attrs }).attrs!;\n return [\n \"div\",\n mergeAttributes(HTMLAttributes, {\n \"data-storyblock\": \"\",\n ...Object.fromEntries(\n Object.entries(attrs).map(([key, value]) => [\n `data-storyblock-${key.toLowerCase()}`,\n value,\n ]),\n ),\n }),\n ];\n },\n});\n","import { getSchema, type JSONContent } from \"@tiptap/react\";\nimport { StarterKit } from \"@tiptap/starter-kit\";\nimport { Link } from \"@tiptap/extension-link\";\nimport { Storyblock, validStoryblock } from \"./storyblock\";\n\nexport type RichTextDocument = JSONContent & { type: \"doc\" };\n\nexport const emptyDocument: RichTextDocument = { type: \"doc\", content: [{ type: \"paragraph\" }] };\n\nconst baseExtensions = [\n StarterKit.configure({ link: false, trailingNode: { notAfter: [\"paragraph\", \"storyblock\"] } }),\n Link.configure({ openOnClick: false, autolink: true }),\n];\n\n/**\n * The shared schema's extensions. The editor passes its node-view variant of\n * `storyblock`; every call returns the same configured instances, so an editor\n * keeps the same extension identities across renders.\n */\nexport function richTextExtensions(storyblock: typeof Storyblock = Storyblock) {\n return [storyblock, ...baseExtensions];\n}\n\nconst schema = getSchema(richTextExtensions());\n\n/** ProseMirror represents an empty writing surface with one empty paragraph. */\nexport function normalizeDocument(document: RichTextDocument): RichTextDocument {\n return !document.content?.length ? { ...document, content: emptyDocument.content } : document;\n}\n\nexport function documentError(value: unknown): string | undefined {\n try {\n if (!value || typeof value !== \"object\" || !(\"type\" in value) || value.type !== \"doc\") {\n throw new Error();\n }\n const check = (node: JSONContent) => {\n const type = schema.nodes[node.type ?? \"\"];\n if (\n !type ||\n Object.keys(node).some(\n (key) => ![\"type\", \"attrs\", \"content\", \"marks\", \"text\"].includes(key),\n ) ||\n (node.text !== undefined && node.type !== \"text\") ||\n (node.attrs &&\n Object.keys(node.attrs).some((key) => !Object.hasOwn(type.spec.attrs ?? {}, key)))\n ) {\n throw new Error();\n }\n if (\n node.type === \"storyblock\" &&\n (!validStoryblock(node.attrs ?? {}) || node.marks?.length)\n ) {\n throw new Error();\n }\n for (const mark of node.marks ?? []) {\n const markType = schema.marks[mark.type];\n if (\n !markType ||\n Object.keys(mark).some((key) => ![\"type\", \"attrs\"].includes(key)) ||\n Object.keys(mark.attrs ?? {}).some(\n (key) => !Object.hasOwn(markType.spec.attrs ?? {}, key),\n )\n ) {\n throw new Error();\n }\n }\n node.content?.forEach(check);\n };\n const document = value as RichTextDocument;\n check(document);\n schema.nodeFromJSON(normalizeDocument(document)).check();\n } catch {\n return \"Unsupported or invalid rich-text document.\";\n }\n}\n","import { createContext } from \"react\";\nimport type { EntryItem } from \"../EntryPicker\";\nimport type { SeedCopy } from \"../EntryPicker/use-selected-items\";\nimport type { RichTextEmbedKind, RichTextEmbedSource } from \"./embed-types\";\n\n/** Whether a source can offer something to embed: choices to list, or one to create. */\nexport function canEmbed(source: RichTextEmbedSource | undefined) {\n return Boolean(source && (source.loadPage || source.items?.length || source.onCreate));\n}\n\n/**\n * What a block's node view reads from its source. Callbacks are stable wrappers\n * over the latest source and the rest are plain values, so an application that\n * builds new sources on every render doesn't re-render every block.\n */\nexport interface EmbedSourceView {\n resolveItem?: (id: string) => EntryItem | null | Promise<EntryItem | null>;\n refreshKey?: string | number;\n items?: EntryItem[];\n isDialogHidden: boolean;\n /** The source can list or create a replacement. */\n canEmbed: boolean;\n onEditItem?: (item: EntryItem) => void;\n}\n\nexport const EmbedContext = createContext<{\n views: Partial<Record<RichTextEmbedKind, EmbedSourceView>>;\n disabled: boolean;\n /** A picker session is suspended or creating: starting another would orphan it. */\n busy: boolean;\n replace: (kind: RichTextEmbedKind, position: number) => void;\n /**\n * Changes with each pick. Picking a block's own item again leaves an equal node\n * that ProseMirror doesn't re-render, so blocks re-read `seed` when it changes.\n */\n pickCount: number;\n /** The row a writer just picked for this item, so its new block shows it at once. */\n seed: (kind: RichTextEmbedKind, id: string) => SeedCopy | undefined;\n /** The block has shown `copy`; later blocks for the item describe it afresh. */\n forgetSeed: (kind: RichTextEmbedKind, id: string, copy: SeedCopy) => void;\n}>({\n views: {},\n disabled: false,\n busy: false,\n pickCount: 0,\n replace: () => {},\n seed: () => undefined,\n forgetSeed: () => {},\n});\n","import {\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useState,\n type FocusEvent,\n type KeyboardEvent,\n type MouseEvent,\n} from \"react\";\nimport { NodeViewWrapper, type NodeViewProps } from \"@tiptap/react\";\nimport { Button } from \"../Button\";\nimport { ButtonGroup } from \"../ButtonGroup\";\nimport { Badge } from \"../Badge\";\nimport { Icon } from \"../Icon\";\nimport { EntryRow } from \"../EntryPicker/item\";\nimport { chosenItems } from \"../EntryPicker/chosen\";\nimport { useSelectedItems } from \"../EntryPicker/use-selected-items\";\nimport { useLoadError } from \"../EntryPicker/feedback\";\nimport type { EntryItem } from \"../EntryPicker\";\nimport { EmbedContext } from \"./embed-context\";\nimport type { RichTextEmbedKind } from \"./embed-types\";\nimport type { StoryblockAlignment } from \"./storyblock\";\n\nconst noItems: EntryItem[] = [];\nconst alignments = [\n { align: \"left\", icon: \"align-left\", label: \"Align left\" },\n { align: \"full\", icon: \"align-justify\", label: \"Full width\" },\n { align: \"right\", icon: \"align-right\", label: \"Align right\" },\n] as const;\n\ntype BarAction = StoryblockAlignment | \"replace\" | \"edit\" | \"remove\";\nconst barActions: BarAction[] = [\"left\", \"full\", \"right\", \"replace\", \"edit\", \"remove\"];\nconst focusSteps = new Map([\n [\"ArrowLeft\", -1],\n [\"ArrowRight\", 1],\n [\"Home\", -Infinity],\n [\"End\", Infinity],\n]);\n\n/** Arrow keys move between a title bar's enabled buttons, wrapping; Home and End go to its ends. */\nfunction moveBarFocus(event: KeyboardEvent<HTMLElement>) {\n const step = focusSteps.get(event.key);\n if (step === undefined || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) {\n return;\n }\n const buttons = Array.from(\n event.currentTarget.querySelectorAll<HTMLButtonElement>(\"button:not(:disabled)\"),\n );\n const index = buttons.indexOf(event.target as HTMLButtonElement);\n if (index === -1) {\n return;\n }\n event.preventDefault();\n const target = index + step;\n const next = Number.isFinite(target)\n ? (target + buttons.length) % buttons.length\n : Math.max(0, Math.min(target, buttons.length - 1));\n buttons[next].focus();\n}\n\n/**\n * One tab stop across a title bar's available actions, and only while its block\n * is selected or the bar holds focus, so Tab never walks every block's buttons.\n */\nfunction useBarFocus(isSelected: boolean, available: BarAction[]) {\n const [current, setCurrent] = useState<BarAction>();\n const [hasFocus, setHasFocus] = useState(false);\n const isActive = isSelected || hasFocus;\n const tabStop = current && available.includes(current) ? current : available[0];\n return {\n control: (action: BarAction) => ({\n isDisabled: !available.includes(action),\n tabIndex: isActive && action === tabStop ? 0 : -1,\n onFocus: () => setCurrent(action),\n }),\n barProps: {\n onKeyDown: moveBarFocus,\n onFocus: () => setHasFocus(true),\n onBlur: (event: FocusEvent<HTMLElement>) => {\n if (!event.currentTarget.contains(event.relatedTarget)) {\n setHasFocus(false);\n }\n },\n },\n };\n}\n\n/**\n * The block's item through the shared selected-item reader: static items, the\n * row a writer just picked, then `resolveItem`, with its loading, stale-refresh\n * and retry behavior. Null or removed-tone items read as missing.\n */\nfunction useStoryblockItem(kind: RichTextEmbedKind, id: string) {\n const { views, seed, forgetSeed } = useContext(EmbedContext);\n const view = views[kind];\n const items = view?.items ?? noItems;\n const ids = useMemo(() => [id], [id]);\n // A block just inserted or replaced starts from the row the writer picked.\n const picked = useCallback((itemId: string) => seed(kind, itemId), [seed, kind]);\n const selection = useSelectedItems(ids, items, view?.resolveItem, view?.refreshKey, picked);\n // A pick describes this block only, including a Replace that picks its own\n // item again: any later block for the item, after an undo, paste or reset, is\n // described afresh.\n const pick = seed(kind, id);\n useEffect(() => {\n if (pick) {\n forgetSeed(kind, id, pick);\n }\n }, [forgetSeed, kind, id, pick]);\n const { known, failures } = selection;\n const hasResolver = Boolean(view?.resolveItem);\n const item = useMemo(\n () =>\n chosenItems({\n selected: ids,\n items,\n pageItems: noItems,\n known,\n failures,\n hasResolver,\n itemLabel: kind,\n })[0],\n [ids, items, known, failures, hasResolver, kind],\n );\n const failure = useLoadError(\n `Couldn't load ${kind}`,\n selection.status,\n selection.error,\n selection.retry,\n );\n // As in chosenItems, a static item takes precedence over a cached lookup: one\n // supplied after a lookup found nothing repairs the block. Static items never\n // enter `known`, so a removed one is read from the item itself.\n const isStatic = items.some((each) => each.id === id);\n const missing = item.tone === \"removed\" || (!isStatic && known.has(id) && !known.get(id));\n return { view, item, missing, failure };\n}\n\n/**\n * The grip and kind label: the block's drag handle. It holds no buttons, so\n * pressing one never starts a drag. A pointer affordance only: keyboard writers\n * move blocks by cut and paste.\n */\nfunction StoryblockHandle({\n kind,\n isMovable,\n onSelect,\n}: {\n kind: RichTextEmbedKind;\n isMovable: boolean;\n onSelect?: () => void;\n}) {\n return (\n <span\n className=\"ds-storyblock__kind\"\n data-drag-handle={isMovable ? \"\" : undefined}\n draggable={isMovable || undefined}\n title={isMovable ? \"Drag to move\" : undefined}\n onClick={isMovable ? onSelect : undefined}\n >\n {isMovable && (\n <span\n className=\"ds-storyblock__grip\"\n aria-hidden=\"true\"\n >\n <Icon\n name=\"grip-vertical\"\n size={16}\n />\n </span>\n )}\n <Badge\n className=\"ds-storyblock__kind-label\"\n shape=\"tag\"\n size=\"sm\"\n >\n {kind}\n </Badge>\n </span>\n );\n}\n\n/**\n * The editable title bar: the handle, alignment, Replace, Edit and Remove. Every\n * block has one, so each action's name says which item it acts on.\n */\nfunction StoryblockBar({\n kind,\n name,\n align,\n isSelected,\n isLocked,\n canReplace,\n onEdit,\n onSelect,\n onAlign,\n onReplace,\n onRemove,\n}: {\n kind: RichTextEmbedKind;\n name: string;\n align: StoryblockAlignment;\n isSelected: boolean;\n /** One of these blocks may be a suspended replacement's target: no action may touch it. */\n isLocked: boolean;\n /** Replace is shown, and enabled unless another session is busy. */\n canReplace: { isShown: boolean; isEnabled: boolean };\n onEdit: (() => void) | undefined;\n onSelect: () => void;\n onAlign: (align: StoryblockAlignment) => void;\n onReplace: () => void;\n onRemove: () => void;\n}) {\n const offered: Record<BarAction, boolean> = {\n left: true,\n full: true,\n right: true,\n replace: canReplace.isEnabled,\n edit: Boolean(onEdit),\n remove: true,\n };\n const available = isLocked ? [] : barActions.filter((action) => offered[action]);\n const { control, barProps } = useBarFocus(isSelected, available);\n return (\n <div\n className=\"ds-storyblock__bar\"\n role=\"toolbar\"\n aria-label={`Block actions for ${name}`}\n {...barProps}\n >\n <StoryblockHandle\n kind={kind}\n isMovable={!isLocked}\n onSelect={onSelect}\n />\n <ButtonGroup\n className=\"ds-storyblock__alignment\"\n aria-label=\"Alignment\"\n >\n {alignments.map((option) => (\n <Button\n key={option.align}\n {...control(option.align)}\n size=\"sm\"\n isIconOnly\n iconStart={option.icon}\n aria-label={`${option.label}: ${name}`}\n title={option.label}\n aria-pressed={align === option.align}\n variant={align === option.align ? \"active\" : \"neutral\"}\n onClick={() => onAlign(option.align)}\n />\n ))}\n </ButtonGroup>\n <div className=\"ds-storyblock__actions\">\n {canReplace.isShown && (\n <Button\n {...control(\"replace\")}\n variant=\"simple\"\n size=\"sm\"\n aria-label={`Replace ${name}`}\n onClick={onReplace}\n >\n Replace\n </Button>\n )}\n {onEdit && (\n <Button\n {...control(\"edit\")}\n variant=\"simple\"\n size=\"sm\"\n isIconOnly\n iconStart=\"pencil\"\n aria-label={`Edit ${name}`}\n title={`Edit ${kind}`}\n onClick={onEdit}\n />\n )}\n <Button\n {...control(\"remove\")}\n variant=\"simple\"\n size=\"sm\"\n isIconOnly\n iconStart=\"trash\"\n aria-label={`Remove ${name}`}\n title=\"Remove block from this field\"\n onClick={onRemove}\n />\n </div>\n </div>\n );\n}\n\nfunction StoryblockBody({\n kind,\n id,\n item,\n missing,\n}: {\n kind: RichTextEmbedKind;\n id: string;\n item: EntryItem;\n missing: boolean;\n}) {\n return (\n <div className=\"ds-entry ds-storyblock__body\">\n {missing ? (\n <span className=\"ds-entry__body\">\n <em className=\"ds-entry__title\">{`Unavailable ${kind}`}</em>\n <span className=\"ds-entry__meta\">\n <span>{`This ${kind} was deleted. Replace or remove it.`}</span>\n <code>{id}</code>\n </span>\n </span>\n ) : (\n <EntryRow item={item} />\n )}\n </div>\n );\n}\n\nexport function StoryblockView({\n node,\n selected,\n editor,\n getPos,\n updateAttributes,\n}: NodeViewProps) {\n const { disabled, busy, replace } = useContext(EmbedContext);\n const kind = node.attrs.type as RichTextEmbedKind;\n const id = String(kind === \"entry\" ? node.attrs.entryId : node.attrs.assetId);\n const { view, item, missing, failure } = useStoryblockItem(kind, id);\n const align = (node.attrs.align ?? \"full\") as StoryblockAlignment;\n const editItem = !missing && !item.isUnavailable && !item.isDisabled && view?.onEditItem;\n // A read-only block never shows as selected, however ProseMirror selects it.\n const isSelected = selected && !disabled;\n const select = () => {\n const position = getPos();\n if (position !== undefined) {\n editor.chain().focus().setNodeSelection(position).run();\n }\n };\n // Deleting the selected block leaves the caret where the block was.\n const remove = () => {\n const position = getPos();\n if (position !== undefined) {\n editor\n .chain()\n .focus()\n .setNodeSelection(position)\n .deleteRange({ from: position, to: position + node.nodeSize })\n .run();\n }\n };\n const onMouseDown = (event: MouseEvent) => {\n const target = event.target instanceof Element ? event.target : null;\n // Pressing a button keeps focus where the writer is. React handles node\n // view events before ProseMirror, which then ignores the press.\n if (target?.closest(\"button\")) {\n event.preventDefault();\n } else if (!disabled && !target?.closest(\"[data-drag-handle]\")) {\n event.preventDefault();\n select();\n }\n };\n return (\n <NodeViewWrapper\n className=\"ds-storyblock\"\n data-align={align}\n data-selected={isSelected || undefined}\n data-missing={missing || undefined}\n data-tone={missing ? \"removed\" : item.tone}\n contentEditable={false}\n onMouseDown={onMouseDown}\n >\n {disabled ? (\n <div className=\"ds-storyblock__bar\">\n <StoryblockHandle\n kind={kind}\n isMovable={false}\n />\n </div>\n ) : (\n <StoryblockBar\n kind={kind}\n name={missing ? `Unavailable ${kind}` : item.title}\n align={align}\n isSelected={isSelected}\n // While this kind's picker is suspended, removing or moving its\n // pending replacement's target would orphan the creation.\n isLocked={Boolean(view?.isDialogHidden)}\n canReplace={{\n isShown: Boolean(view?.canEmbed),\n isEnabled: Boolean(view?.canEmbed) && !busy,\n }}\n onEdit={editItem ? () => editItem(item) : undefined}\n onSelect={select}\n onAlign={(align) => updateAttributes({ align })}\n onReplace={() => {\n const position = getPos();\n if (position !== undefined) {\n replace(kind, position);\n }\n }}\n onRemove={remove}\n />\n )}\n <StoryblockBody\n kind={kind}\n id={id}\n item={item}\n missing={missing}\n />\n {failure && <div className=\"ds-storyblock__failure\">{failure}</div>}\n </NodeViewWrapper>\n );\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport type { Editor, EditorEvents } from \"@tiptap/react\";\nimport { useLatest } from \"../../internal/useLatest\";\nimport { Button } from \"../Button\";\nimport { ButtonGroup } from \"../ButtonGroup\";\nimport { PickerDialog } from \"../EntryPicker/dialog\";\nimport { usePickerSession } from \"../EntryPicker/use-picker-session\";\nimport type { SeedCopy } from \"../EntryPicker/use-selected-items\";\nimport type { EntryItem } from \"../EntryPicker\";\nimport { canEmbed, type EmbedSourceView } from \"./embed-context\";\nimport { validStoryblock } from \"./storyblock\";\nimport type {\n RichTextEmbedItem,\n RichTextEmbedKind,\n RichTextEmbedSource,\n RichTextEmbedSources,\n RichTextEmbedTarget,\n} from \"./embed-types\";\n\ntype Transaction = EditorEvents[\"transaction\"][\"transaction\"];\ntype Doc = Editor[\"state\"][\"doc\"];\ntype DocNode = ReturnType<Doc[\"nodeAt\"]>;\n\n/**\n * Marks the transaction that commits an embed: the one change a disabled\n * editor reports, while the embed's source completes a creation.\n */\nexport const embedCommitMeta = \"ds-rte-embed-commit\";\n\nconst kinds = [\"entry\", \"asset\"] as const;\nconst labels = {\n entry: { itemLabel: \"entry\", itemsLabel: \"entries\" },\n asset: { itemLabel: \"asset\", itemsLabel: \"assets\" },\n} as const;\nconst noSources: RichTextEmbedSources = {};\nconst noItems: EntryItem[] = [];\n\ninterface Session {\n /** Each opening's own identity, so a new session never inherits picker state. */\n id: number;\n kind: RichTextEmbedKind;\n replaceId?: string;\n}\n/**\n * Where a session's pick lands. A replacement holds its block's start (`from`,\n * with `to` one past it). An insertion holds the top-level block the cursor was\n * in, from its start to the boundary after it; an empty range is a gap between\n * blocks.\n */\ninterface Bookmark {\n session: Session | null;\n from: number;\n to: number;\n alive: boolean;\n}\n\nfunction blockAttrs(kind: RichTextEmbedKind, align: string, item: RichTextEmbedItem) {\n return {\n type: kind,\n align,\n ...(kind === \"entry\" ? { id: item.modelId, entryId: item.id } : { assetId: item.id }),\n };\n}\n\n/** Why an item can't become a block, shown on its row; undefined when it can. */\nfunction embedReason(kind: RichTextEmbedKind, item: RichTextEmbedItem) {\n if (item.tone === \"removed\") {\n return { label: item.removedLabel ?? \"Removed\", description: `This ${kind} was removed.` };\n }\n if (!validStoryblock(blockAttrs(kind, \"full\", item))) {\n const missing = kind === \"entry\" && !item.modelId?.trim() ? \"model API ID\" : \"ID\";\n return { label: \"Can't embed\", description: `This ${kind} has no ${missing}.` };\n }\n return undefined;\n}\nconst restrictions = {\n entry: (item: EntryItem) => embedReason(\"entry\", item),\n asset: (item: EntryItem) => embedReason(\"asset\", item),\n};\n\n/** Whether `node` is still the block a replacement session targets. */\nfunction isTarget(node: DocNode, session: Session) {\n return (\n node?.type.name === \"storyblock\" &&\n node.attrs.type === session.kind &&\n String(session.kind === \"entry\" ? node.attrs.entryId : node.attrs.assetId) === session.replaceId\n );\n}\n\nfunction stepMaps(transactions: Transaction[]) {\n return transactions.flatMap((transaction) => transaction.mapping.maps);\n}\n\n/**\n * Map a replacement's block start through a transaction and the transactions\n * plugins appended to it. The bookmark moves with the block, and a same-size\n * change covering it, such as new alignment, keeps it; any other change that\n * deletes the block ends it: null. Callers still check the block's identity.\n */\nfunction mapBlock(transactions: Transaction[], position: number) {\n let pos = position;\n for (const map of stepMaps(transactions)) {\n const at = pos;\n let kept: number | undefined;\n map.forEach((oldStart, oldEnd, newStart, newEnd) => {\n const covers = oldStart <= at && at < oldEnd;\n if (kept === undefined && covers && oldEnd - oldStart === newEnd - newStart) {\n kept = newStart + (at - oldStart);\n }\n });\n if (kept !== undefined) {\n pos = kept;\n continue;\n }\n const result = map.mapResult(at, 1);\n if (result.deletedAfter) {\n return null;\n }\n pos = result.pos;\n }\n return pos;\n}\n\n/**\n * Map an insertion's origin block through a transaction and the transactions\n * plugins appended to it. Structural changes around it, such as wrapping,\n * lifting or joining, keep it; a single change that replaces all of it ends\n * it: null. A leaf block changed in place, such as a selected block's new\n * alignment, is the same block. Its end stays before content added at that\n * boundary, such as a trailing paragraph.\n */\nfunction mapOrigin(transactions: Transaction[], from: number, to: number) {\n let start = from;\n let end = to;\n for (const map of stepMaps(transactions)) {\n if (start === end) {\n start = end = map.map(end, -1);\n continue;\n }\n let replaced = false;\n map.forEach((oldStart, oldEnd, newStart, newEnd) => {\n const inPlace =\n end - start === 1 && oldStart === start && oldEnd === end && newEnd - newStart === 1;\n replaced ||= oldStart <= start && end <= oldEnd && !inPlace;\n });\n start = map.map(start, 1);\n end = map.map(end, -1);\n if (replaced || end <= start) {\n return null;\n }\n }\n return { from: start, to: end };\n}\n\n/** The top-level boundary at or after `position`: an embed is always a top-level block. */\nfunction boundaryAfter(doc: Doc, position: number) {\n const $position = doc.resolve(Math.min(position, doc.content.size));\n return $position.depth ? $position.after(1) : $position.pos;\n}\n\n/**\n * The node views' stable reading of one source: values they render, plus the\n * stable `resolve` and `edit` wrappers in place of the source's own callbacks.\n */\nfunction useSourceView(\n source: RichTextEmbedSource | undefined,\n resolve: NonNullable<EmbedSourceView[\"resolveItem\"]>,\n edit: NonNullable<EmbedSourceView[\"onEditItem\"]>,\n): EmbedSourceView | undefined {\n const isPresent = source !== undefined;\n const hasResolver = Boolean(source?.resolveItem);\n const hasEditor = Boolean(source?.onEditItem);\n const refreshKey = source?.refreshKey;\n const items = source?.items;\n const isDialogHidden = Boolean(source?.isDialogHidden);\n const offered = canEmbed(source);\n return useMemo(\n () =>\n isPresent\n ? {\n resolveItem: hasResolver ? resolve : undefined,\n refreshKey,\n items,\n isDialogHidden,\n canEmbed: offered,\n onEditItem: hasEditor ? edit : undefined,\n }\n : undefined,\n [isPresent, hasResolver, hasEditor, refreshKey, items, isDialogHidden, offered, resolve, edit],\n );\n}\n\nfunction EmbedPicker({\n session,\n source,\n disabled,\n label,\n close,\n target,\n pick,\n}: {\n session: Session;\n source: RichTextEmbedSource;\n disabled: boolean;\n label: string;\n close: () => void;\n target: RichTextEmbedTarget;\n pick: (item: EntryItem, revision: SeedCopy[\"revision\"]) => void;\n}) {\n const { itemLabel, itemsLabel } = labels[session.kind];\n const selected = useMemo(() => (session.replaceId ? [session.replaceId] : []), [session]);\n // The dialog never shows its selection's own copy, so it never resolves one.\n const picker = usePickerSession(\n selected,\n source.items ?? noItems,\n { ...source, resolveItem: undefined, mode: \"single\" },\n {\n isOpen: true,\n isDisabled: disabled,\n itemLabel,\n itemsLabel,\n close,\n restrict: restrictions[session.kind],\n },\n );\n const action = session.replaceId ? \"Replace\" : \"Embed\";\n return (\n <PickerDialog\n {...picker.dialog}\n isOpen\n onClose={close}\n onToggle={(id) => {\n const item = picker.choice(id);\n if (item) {\n pick(item, picker.revision);\n }\n }}\n addLabel={`${action} ${itemLabel}`}\n onCreate={source.onCreate ? () => source.onCreate?.(target) : undefined}\n isCreating={source.isCreating}\n dialogTitle={source.dialogTitle}\n dialogDescription={`Choose one ${itemLabel} to embed in ${label}. ${source.dialogDescription ?? \"\"}`.trim()}\n isDialogHidden={source.isDialogHidden}\n />\n );\n}\n\nexport function useEmbeds(\n editor: Editor | null,\n sources: RichTextEmbedSources = noSources,\n disabled: boolean,\n label: string,\n) {\n const [session, setSession] = useState<Session | null>(null);\n const sessionIds = useRef(0);\n const bookmark = useRef<Bookmark>({ session: null, from: 0, to: 0, alive: false });\n /** The latest pick, by kind and ID, until its new block has shown it. */\n const picks = useRef(new Map<string, SeedCopy>());\n const [pickCount, setPickCount] = useState(0);\n const close = useCallback(() => {\n bookmark.current.alive = false;\n setSession(null);\n }, []);\n\n // A session ends with its source, and when the editor turns read only for\n // any reason but a creation its source is completing.\n const sessionSource = session ? sources[session.kind] : undefined;\n const active =\n session && canEmbed(sessionSource) && (!disabled || sessionSource?.isCreating) ? session : null;\n if (session && !active) {\n setSession(null);\n }\n // While its picker is suspended or its source creates, another session would\n // replace the bookmark and orphan the creation.\n const busy = Boolean(active && (sessionSource?.isDialogHidden || sessionSource?.isCreating));\n const latest = useLatest({ editor, sources, disabled, busy });\n\n useEffect(() => {\n if (!editor || !session) {\n return;\n }\n bookmark.current.alive = true;\n const map = ({\n editor: current,\n transaction,\n appendedTransactions,\n }: EditorEvents[\"transaction\"]) => {\n const transactions = [transaction, ...appendedTransactions];\n if (!bookmark.current.alive || !transactions.some((each) => each.docChanged)) {\n return;\n }\n const { from, to } = bookmark.current;\n if (session.replaceId === undefined) {\n const origin = mapOrigin(transactions, from, to);\n if (origin) {\n Object.assign(bookmark.current, origin);\n } else {\n close();\n }\n return;\n }\n const position = mapBlock(transactions, from);\n if (position === null || !isTarget(current.state.doc.nodeAt(position), session)) {\n close();\n } else {\n Object.assign(bookmark.current, { from: position, to: position + 1 });\n }\n };\n editor.on(\"transaction\", map);\n return () => {\n editor.off(\"transaction\", map);\n if (bookmark.current.session === session) {\n bookmark.current.alive = false;\n }\n };\n }, [editor, session, close]);\n\n // These read the latest editor, sources and bookmark when called, so a target\n // an application holds across renders always answers for now.\n const available = (target: Session) => {\n const { editor: now, sources: current, disabled: isReadOnly } = latest.current;\n const source = current[target.kind];\n return Boolean(\n now &&\n !now.isDestroyed &&\n bookmark.current.session === target &&\n bookmark.current.alive &&\n canEmbed(source) &&\n (!isReadOnly || source?.isCreating),\n );\n };\n const commit = (target: Session, item: RichTextEmbedItem, revision: SeedCopy[\"revision\"]) => {\n const now = latest.current.editor;\n if (!now || !available(target) || item.isDisabled || item.tone === \"removed\") {\n return false;\n }\n const { doc } = now.state;\n const replacing = target.replaceId !== undefined;\n const previous = replacing ? doc.nodeAt(bookmark.current.from) : null;\n if (replacing && !isTarget(previous, target)) {\n return false;\n }\n // A replacement keeps the block's alignment as it is now, not as it was when opened.\n const attrs = blockAttrs(target.kind, previous?.attrs.align ?? \"full\", item);\n if (!validStoryblock(attrs)) {\n return false;\n }\n const position = replacing ? bookmark.current.from : boundaryAfter(doc, bookmark.current.to);\n const key = `${target.kind}:${item.id}`;\n bookmark.current.alive = false;\n picks.current = new Map([[key, { item, revision }]]);\n let result = false;\n try {\n const chain = now.chain().focus().setMeta(embedCommitMeta, true);\n result = replacing\n ? chain.setNodeSelection(position).updateAttributes(\"storyblock\", attrs).run()\n : chain\n .insertContentAt(position, { type: \"storyblock\", attrs })\n .setNodeSelection(position)\n .run();\n } catch {\n // A chain that throws dispatches nothing; the target reports the failure.\n result = false;\n } finally {\n close();\n }\n if (result) {\n setPickCount((count) => count + 1);\n } else {\n picks.current.delete(key);\n }\n return result;\n };\n const open = (kind: RichTextEmbedKind, position?: number) => {\n const { editor: now, sources: current, disabled: isReadOnly, busy: isBusy } = latest.current;\n if (!now || isReadOnly || isBusy || !canEmbed(current[kind])) {\n return;\n }\n const node = position === undefined ? null : now.state.doc.nodeAt(position);\n if (position !== undefined && (node?.type.name !== \"storyblock\" || node.attrs.type !== kind)) {\n return;\n }\n const { $from, from, to } = now.state.selection;\n const next: Session = {\n id: (sessionIds.current += 1),\n kind,\n replaceId: node\n ? String(kind === \"entry\" ? node.attrs.entryId : node.attrs.assetId)\n : undefined,\n };\n const range =\n position !== undefined\n ? { from: position, to: position + 1 }\n : $from.depth\n ? { from: $from.before(1), to: $from.after(1) }\n : { from, to };\n bookmark.current = { session: next, ...range, alive: true };\n setSession(next);\n };\n const actions = useLatest({ open });\n // Stable for the node views' context: a keystroke never re-renders every block.\n const [stable] = useState(() => ({\n replace: (kind: RichTextEmbedKind, position: number) => actions.current.open(kind, position),\n seed: (kind: RichTextEmbedKind, id: string) => picks.current.get(`${kind}:${id}`),\n // Only that pick: a newer one for the same item still awaits its block.\n forgetSeed: (kind: RichTextEmbedKind, id: string, copy: SeedCopy) => {\n if (picks.current.get(`${kind}:${id}`) === copy) {\n picks.current.delete(`${kind}:${id}`);\n }\n },\n resolve: {\n entry: (id: string) => latest.current.sources.entry?.resolveItem?.(id) ?? null,\n asset: (id: string) => latest.current.sources.asset?.resolveItem?.(id) ?? null,\n },\n edit: {\n entry: (item: EntryItem) => {\n latest.current.sources.entry?.onEditItem?.(item);\n },\n asset: (item: EntryItem) => {\n latest.current.sources.asset?.onEditItem?.(item);\n },\n },\n }));\n const entryView = useSourceView(sources.entry, stable.resolve.entry, stable.edit.entry);\n const assetView = useSourceView(sources.asset, stable.resolve.asset, stable.edit.asset);\n const context = useMemo(\n () => ({\n views: { entry: entryView, asset: assetView },\n disabled,\n busy,\n pickCount,\n replace: stable.replace,\n seed: stable.seed,\n forgetSeed: stable.forgetSeed,\n }),\n [entryView, assetView, disabled, busy, pickCount, stable],\n );\n const offered = kinds.filter((kind) => canEmbed(sources[kind]));\n return {\n context,\n /**\n * A source is completing a creation, which its app may hold the editor read\n * only for, from the dialog until it clears `isCreating` after the commit.\n */\n isCreating: kinds.some((kind) => sources[kind]?.isCreating),\n toolbar: offered.length > 0 && (\n <ButtonGroup aria-label=\"Embed\">\n {offered.map((kind) => (\n <Button\n key={kind}\n size=\"sm\"\n isIconOnly\n iconStart={kind === \"entry\" ? \"file-text\" : \"image\"}\n aria-label={`Embed ${kind}`}\n title={`Embed ${kind}`}\n aria-pressed={active?.kind === kind}\n variant={active?.kind === kind ? \"active\" : \"neutral\"}\n isDisabled={disabled || busy || !editor}\n onClick={() => open(kind)}\n />\n ))}\n </ButtonGroup>\n ),\n dialog: editor && active && sessionSource && (\n <EmbedPicker\n key={active.id}\n session={active}\n source={sessionSource}\n disabled={disabled}\n label={label}\n close={close}\n target={{\n available: () => available(active),\n // A newly created item is as fresh as the source's latest refresh.\n commit: (item) => commit(active, item, latest.current.sources[active.kind]?.refreshKey),\n }}\n pick={(item, revision) => commit(active, item, revision)}\n />\n ),\n };\n}\n","import {\n forwardRef,\n useCallback,\n useEffect,\n useId,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n type RefObject,\n} from \"react\";\nimport {\n ReactNodeViewRenderer,\n createDocument,\n EditorContent,\n getMarkRange,\n useEditor,\n useEditorState,\n type Editor,\n type EditorOptions,\n} from \"@tiptap/react\";\nimport { Placeholder } from \"@tiptap/extension-placeholder\";\nimport { Button } from \"../Button\";\nimport { ButtonGroup } from \"../ButtonGroup\";\nimport { Field } from \"../Field\";\nimport { Modal } from \"../Modal\";\nimport { TextField } from \"../TextField\";\nimport type { IconName } from \"../Icon/icons\";\nimport { mergeRefs } from \"../../internal/mergeRefs\";\nimport { PortalScopeContext } from \"../../internal/portalScope\";\nimport { useEditorExpansion, type RichTextEditorExpandedWidth } from \"./expansion\";\nimport {\n documentError,\n emptyDocument,\n normalizeDocument,\n richTextExtensions,\n type RichTextDocument,\n} from \"./document\";\nimport \"../Field/style.css\";\nimport type { FieldBinding } from \"../Field\";\nimport \"./style.css\";\nimport { Storyblock, storyblockDocument } from \"./storyblock\";\nimport { StoryblockView } from \"./storyblock-view\";\nimport { EmbedContext } from \"./embed-context\";\nimport { embedCommitMeta, useEmbeds } from \"./use-embeds\";\nimport type { RichTextEmbedSources } from \"./embed-types\";\nexport type {\n RichTextEmbedItem,\n RichTextEmbedSource,\n RichTextEmbedSources,\n RichTextEmbedTarget,\n} from \"./embed-types\";\nexport type { StoryblockAlignment, StoryblockIdentity, StoryblockAttributes } from \"./storyblock\";\n\nexport type RichTextEditorSize = \"sm\" | \"md\" | \"lg\";\n\nexport type { RichTextDocument } from \"./document\";\nexport type { RichTextEditorExpandedWidth } from \"./expansion\";\n\ninterface RichTextEditorCommonProps extends FieldBinding {\n placeholder?: string;\n size?: RichTextEditorSize;\n /** Expanded writing measure. `wide` caps at the shared 920px Modal width; `full` fills the viewport. */\n expandedWidth?: RichTextEditorExpandedWidth;\n isDisabled?: boolean;\n isInvalid?: boolean;\n /** Accessible name for the editing surface. */\n label?: string;\n className?: string;\n /** Extra controls appended to the toolbar, e.g. a word count. */\n toolbarExtra?: ReactNode;\n embeds?: RichTextEmbedSources;\n isRequired?: boolean;\n}\n\nexport type RichTextEditorProps = RichTextEditorCommonProps &\n (\n | { format?: \"html\"; value?: string; defaultValue?: string; onChange?: (html: string) => void }\n | {\n format: \"json\";\n value?: RichTextDocument;\n defaultValue?: RichTextDocument;\n onChange?: (document: RichTextDocument) => void;\n }\n );\n\ninterface ToolItem {\n id: string;\n icon: IconName;\n label: string;\n run: (editor: Editor) => void;\n active?: (editor: Editor) => boolean;\n}\n\ninterface LinkSelection {\n from: number;\n to: number;\n href: string;\n isEditing: boolean;\n document: Editor[\"state\"][\"doc\"];\n}\n\nfunction LinkDialog({\n editor,\n selection,\n onClose,\n}: {\n editor: Editor;\n selection: LinkSelection;\n onClose: () => void;\n}) {\n const [href, setHref] = useState(selection.href);\n const [error, setError] = useState<string>();\n const formId = useId();\n\n useEffect(() => {\n const onTransaction = () => {\n if (!editor.state.doc.eq(selection.document)) {\n onClose();\n }\n };\n editor.on(\"transaction\", onTransaction);\n return () => {\n editor.off(\"transaction\", onTransaction);\n };\n }, [editor, selection, onClose]);\n\n const canEdit = () =>\n !editor.isDestroyed && editor.isEditable && editor.state.doc.eq(selection.document);\n const save = () => {\n if (!canEdit()) {\n onClose();\n return;\n }\n const url = href.trim();\n if (!url || !editor.can().setLink({ href: url })) {\n setError(url ? \"Enter a valid link URL.\" : \"Enter a link URL.\");\n return;\n }\n const chain = editor\n .chain()\n .focus()\n .setTextSelection({ from: selection.from, to: selection.to });\n if (selection.from === selection.to && !selection.isEditing) {\n chain\n .setLink({ href: url })\n .insertContent({ type: \"text\", text: url, marks: [{ type: \"link\", attrs: { href: url } }] })\n .run();\n } else {\n chain.setLink({ href: url }).run();\n }\n onClose();\n };\n\n return (\n <Modal\n isOpen\n title={selection.isEditing ? \"Edit link\" : \"Add link\"}\n size=\"dialog\"\n onClose={onClose}\n footer={\n <>\n {selection.isEditing && (\n <Button\n variant=\"danger\"\n onClick={() => {\n if (canEdit()) {\n editor\n .chain()\n .focus()\n .setTextSelection({ from: selection.from, to: selection.to })\n .unsetLink()\n .run();\n }\n onClose();\n }}\n >\n Remove link\n </Button>\n )}\n <Button onClick={onClose}>Cancel</Button>\n <Button\n variant=\"primary\"\n type=\"submit\"\n form={formId}\n >\n Save\n </Button>\n </>\n }\n >\n <form\n id={formId}\n noValidate\n onSubmit={(event) => {\n event.preventDefault();\n event.stopPropagation();\n save();\n }}\n >\n <Field\n label=\"URL\"\n isRequired\n error={error}\n >\n {(field) => (\n <TextField\n {...field}\n value={href}\n inputMode=\"url\"\n autoComplete=\"url\"\n placeholder=\"https://example.com\"\n onChange={(event) => {\n setHref(event.target.value);\n setError(undefined);\n }}\n />\n )}\n </Field>\n </form>\n </Modal>\n );\n}\n\nconst GROUPS: ToolItem[][] = [\n [\n {\n id: \"bold\",\n icon: \"bold\",\n label: \"Bold\",\n run: (e) => e.chain().focus().toggleBold().run(),\n active: (e) => e.isActive(\"bold\"),\n },\n {\n id: \"italic\",\n icon: \"italic\",\n label: \"Italic\",\n run: (e) => e.chain().focus().toggleItalic().run(),\n active: (e) => e.isActive(\"italic\"),\n },\n {\n id: \"strike\",\n icon: \"strikethrough\",\n label: \"Strikethrough\",\n run: (e) => e.chain().focus().toggleStrike().run(),\n active: (e) => e.isActive(\"strike\"),\n },\n {\n id: \"code\",\n icon: \"code\",\n label: \"Inline code\",\n run: (e) => e.chain().focus().toggleCode().run(),\n active: (e) => e.isActive(\"code\"),\n },\n ],\n [\n {\n id: \"h2\",\n icon: \"heading-2\",\n label: \"Heading\",\n run: (e) => e.chain().focus().toggleHeading({ level: 2 }).run(),\n active: (e) => e.isActive(\"heading\", { level: 2 }),\n },\n {\n id: \"h3\",\n icon: \"heading-3\",\n label: \"Subheading\",\n run: (e) => e.chain().focus().toggleHeading({ level: 3 }).run(),\n active: (e) => e.isActive(\"heading\", { level: 3 }),\n },\n {\n id: \"quote\",\n icon: \"quote\",\n label: \"Quote\",\n run: (e) => e.chain().focus().toggleBlockquote().run(),\n active: (e) => e.isActive(\"blockquote\"),\n },\n ],\n [\n {\n id: \"ul\",\n icon: \"list\",\n label: \"Bulleted list\",\n run: (e) => e.chain().focus().toggleBulletList().run(),\n active: (e) => e.isActive(\"bulletList\"),\n },\n {\n id: \"ol\",\n icon: \"list-ordered\",\n label: \"Numbered list\",\n run: (e) => e.chain().focus().toggleOrderedList().run(),\n active: (e) => e.isActive(\"orderedList\"),\n },\n ],\n [\n {\n id: \"undo\",\n icon: \"undo\",\n label: \"Undo\",\n run: (e) => e.chain().focus().undo().run(),\n },\n {\n id: \"redo\",\n icon: \"redo\",\n label: \"Redo\",\n run: (e) => e.chain().focus().redo().run(),\n },\n ],\n];\n\ninterface ToolbarState {\n active: Record<string, boolean>;\n linkActive: boolean;\n}\n\nfunction EditorToolbar({\n editor,\n state,\n disabled,\n label,\n toolbarExtra,\n openLink,\n expandControl,\n embedControl,\n}: {\n editor: Editor | null;\n state: ToolbarState | null;\n disabled: boolean;\n label: string;\n toolbarExtra: ReactNode;\n openLink: (state: Editor[\"state\"], position?: number) => void;\n expandControl: ReactNode;\n embedControl: ReactNode;\n}) {\n return (\n <div\n className=\"ds-rte__toolbar\"\n role=\"toolbar\"\n aria-label={`${label} formatting`}\n >\n {GROUPS.map((group, i) => (\n <ButtonGroup\n key={i}\n aria-label={`Formatting ${i + 1}`}\n >\n {group.map((tool) => (\n <Button\n key={tool.id}\n size=\"sm\"\n isIconOnly\n iconStart={tool.icon}\n aria-label={tool.label}\n title={tool.label}\n aria-pressed={tool.active ? state?.active[tool.id] : undefined}\n variant={state?.active[tool.id] ? \"active\" : \"neutral\"}\n isDisabled={disabled || !editor}\n onClick={() => editor && tool.run(editor)}\n />\n ))}\n </ButtonGroup>\n ))}\n <ButtonGroup aria-label=\"Link\">\n <Button\n size=\"sm\"\n isIconOnly\n iconStart=\"link\"\n aria-label={state?.linkActive ? \"Edit link\" : \"Add link\"}\n title={state?.linkActive ? \"Edit link\" : \"Add link\"}\n variant={state?.linkActive ? \"active\" : \"neutral\"}\n isDisabled={disabled || !editor}\n onClick={() =>\n editor &&\n openLink(\n editor.state,\n editor.isActive(\"link\") ? editor.state.selection.from : undefined,\n )\n }\n />\n </ButtonGroup>\n {embedControl}\n {toolbarExtra}\n {expandControl}\n </div>\n );\n}\n\n/**\n * The editorial writing surface. Rich text plus links — the same field skin,\n * radius and states as `TextField`, with the toolbar inside the frame.\n */\ninterface EditorFrameProps {\n scopeRef: RefObject<HTMLDivElement | null>;\n className?: string;\n expansion: ReturnType<typeof useEditorExpansion>;\n isFocused: boolean;\n disabled: boolean;\n invalid: boolean;\n contentError?: string;\n errorId: string;\n /** Toolbar and content: rendered once, inline or in the expanded Modal. */\n surface: ReactNode;\n /** Overlays such as the link dialog. */\n children?: ReactNode;\n}\n\n/**\n * The inline frame stays the outermost element, so `className` and layout apply\n * to it. It keeps its place and height while the surface is expanded, and\n * overlays opened from the editor carry its theme, direction and language.\n */\nconst EditorFrame = forwardRef<HTMLDivElement, EditorFrameProps>(function EditorFrame(\n {\n scopeRef,\n className,\n expansion,\n isFocused,\n disabled,\n invalid,\n contentError,\n errorId,\n surface,\n children,\n },\n ref,\n) {\n return (\n <PortalScopeContext.Provider value={scopeRef}>\n <div\n ref={ref}\n className={[\"ds-rte\", className].filter(Boolean).join(\" \")}\n style={expansion.frameStyle}\n data-expanded={expansion.expanded || undefined}\n data-focused={(isFocused && !expansion.expanded) || undefined}\n data-disabled={disabled || undefined}\n aria-invalid={invalid || undefined}\n >\n {contentError && (\n <p\n id={errorId}\n role=\"alert\"\n className=\"ds-field__error\"\n >\n {contentError}\n </p>\n )}\n {expansion.expanded && (\n <p className=\"ds-rte__placeholder\">Editing in expanded view. Press Esc to return.</p>\n )}\n {expansion.surfaceSlot(\n <div\n className=\"ds-rte__surface\"\n hidden={!!contentError}\n data-invalid={invalid || undefined}\n >\n {surface}\n </div>,\n )}\n {expansion.dialog}\n {children}\n </div>\n </PortalScopeContext.Provider>\n );\n});\n\n/** The schema's storyblock, rendered by its React node view. Defined once, so it keeps its identity. */\nconst EditableStoryblock = Storyblock.extend({\n addNodeView() {\n return ReactNodeViewRenderer(StoryblockView, {\n // A block of the other kind is a different block, even with an equal\n // resource ID: a fresh view, so its item reader never keeps the previous\n // kind's copy. Otherwise, as tiptap's default, re-render on a new node.\n update: ({ oldNode, newNode, updateProps }) => {\n if (oldNode.attrs.type !== newNode.attrs.type) {\n return false;\n }\n if (oldNode !== newNode) {\n updateProps();\n }\n return true;\n },\n });\n },\n});\n\n/**\n * ProseMirror cancels every Escape, bound or not, so an enclosing Modal or\n * Drawer would never close from the writing surface. Run the editor's own key\n * bindings and leave an unbound Escape to the page. Escape that ends an IME\n * composition stays with ProseMirror.\n */\nfunction releaseUnboundEscape(view: Editor[\"view\"], event: KeyboardEvent) {\n if (event.key !== \"Escape\" || event.isComposing) {\n return false;\n }\n if (view.someProp(\"handleKeyDown\", (handle) => handle(view, event))) {\n event.preventDefault();\n }\n return true;\n}\n\nexport const RichTextEditor = forwardRef<HTMLDivElement, RichTextEditorProps>(\n function RichTextEditor(props, ref) {\n const {\n placeholder = \"Write something…\",\n size = \"md\",\n expandedWidth = \"wide\",\n isDisabled = false,\n isInvalid = false,\n label = \"Rich text editor\",\n className,\n toolbarExtra,\n id,\n isRequired,\n required,\n \"aria-label\": ariaLabel,\n \"aria-labelledby\": labelledBy,\n \"aria-describedby\": describedBy,\n \"aria-invalid\": ariaInvalid,\n } = props;\n const frameRef = useRef<HTMLDivElement>(null);\n const mergedRef = useMemo(() => mergeRefs(frameRef, ref), [ref]);\n const [isFocused, setIsFocused] = useState(false);\n const [linkSelection, setLinkSelection] = useState<LinkSelection | null>(null);\n const closeLink = useCallback(() => setLinkSelection(null), []);\n const [initialValue] = useState(\n () => props.defaultValue ?? (props.format === \"json\" ? emptyDocument : \"\"),\n );\n const content = props.value !== undefined ? props.value : initialValue;\n const contentError = useMemo(\n () => (props.format === \"json\" ? documentError(content) : undefined),\n [props.format, content],\n );\n const errorId = useId();\n const invalid = isInvalid || !!contentError || ariaInvalid;\n const disabled = isDisabled || !!contentError;\n if (disabled && linkSelection) {\n setLinkSelection(null);\n }\n const openLink = useCallback(\n (state: Editor[\"state\"], position?: number) => {\n if (disabled) {\n return;\n }\n const range =\n position === undefined\n ? undefined\n : getMarkRange(state.doc.resolve(position), state.schema.marks.link);\n const link =\n range &&\n state.doc.nodeAt(range.from)?.marks.find((mark) => mark.type === state.schema.marks.link);\n setLinkSelection({\n from: range?.from ?? state.selection.from,\n to: range?.to ?? state.selection.to,\n href: link?.attrs.href ?? \"\",\n isEditing: !!link,\n document: state.doc,\n });\n },\n [disabled],\n );\n const attributes = useMemo(\n () => ({\n role: \"textbox\",\n ...(!labelledBy ? { \"aria-label\": ariaLabel ?? label } : {}),\n \"aria-multiline\": \"true\",\n ...(id ? { id } : {}),\n ...(labelledBy ? { \"aria-labelledby\": labelledBy } : {}),\n ...(describedBy ? { \"aria-describedby\": describedBy } : {}),\n ...(invalid ? { \"aria-invalid\": String(invalid) } : {}),\n ...(isRequired || required ? { \"aria-required\": \"true\" } : {}),\n }),\n [label, ariaLabel, id, labelledBy, describedBy, invalid, isRequired, required],\n );\n const editorProps = useMemo<EditorOptions[\"editorProps\"]>(\n () => ({\n attributes,\n handleDOMEvents: {\n keydown: releaseUnboundEscape,\n click: (view, event) => {\n const anchor = event.target instanceof Element ? event.target.closest(\"a\") : null;\n if (!anchor || !view.dom.contains(anchor)) {\n return false;\n }\n event.preventDefault();\n if (view.editable) {\n openLink(view.state, view.posAtDOM(anchor, 0));\n }\n return true;\n },\n },\n }),\n [attributes, openLink],\n );\n\n // Stable options, so tiptap doesn't reapply them to the view on every render.\n // The content option seeds a new editor; the value effect below syncs later changes.\n const extensions = useMemo(\n () => [...richTextExtensions(EditableStoryblock), Placeholder.configure({ placeholder })],\n [placeholder],\n );\n const initialContent = useMemo(\n () =>\n contentError\n ? emptyDocument\n : typeof content === \"string\"\n ? content\n : normalizeDocument(content),\n [content, contentError],\n );\n const editor = useEditor({\n immediatelyRender: false,\n editable: !disabled,\n content: initialContent,\n extensions,\n editorProps,\n onFocus: () => setIsFocused(true),\n onBlur: () => setIsFocused(false),\n onUpdate: ({ editor: e, transaction }) => {\n // A read-only editor reports only an embed its source completes while\n // creating; selection and plugin changes (a trailing paragraph) stay local.\n if (disabled && !transaction.getMeta(embedCommitMeta)) {\n return;\n }\n if (props.format === \"json\") {\n props.onChange?.(storyblockDocument(e.getJSON()) as RichTextDocument);\n } else {\n props.onChange?.(e.getHTML());\n }\n },\n });\n\n useEffect(() => {\n if (!editor) {\n return;\n }\n editor.setEditable(!disabled, false);\n editor.setOptions({ editorProps });\n }, [editor, disabled, editorProps]);\n\n useEffect(() => {\n if (!editor || props.value === undefined || contentError) {\n return;\n }\n const next =\n typeof props.value === \"string\"\n ? createDocument(props.value, editor.schema)\n : editor.schema.nodeFromJSON(normalizeDocument(props.value));\n // Parent echoes should preserve the current selection and undo history.\n if (!next.eq(editor.state.doc)) {\n editor.commands.setContent(next, { emitUpdate: false });\n }\n }, [editor, props.value, contentError]);\n\n const state = useEditorState({\n editor,\n selector: ({ editor: e }) =>\n e\n ? {\n active: Object.fromEntries(GROUPS.flat().map((t) => [t.id, t.active?.(e) ?? false])),\n linkActive: e.isActive(\"link\"),\n }\n : null,\n });\n\n const embeds = useEmbeds(editor, contentError ? undefined : props.embeds, disabled, label);\n const expansion = useEditorExpansion({\n editor,\n disabled,\n isHeld: embeds.isCreating,\n invalid: !!invalid,\n label: ariaLabel ?? label,\n labelledBy,\n expandedWidth,\n frameRef,\n });\n\n return (\n <EmbedContext.Provider value={embeds.context}>\n <EditorFrame\n ref={mergedRef}\n scopeRef={frameRef}\n className={className}\n expansion={expansion}\n isFocused={isFocused}\n disabled={disabled}\n invalid={!!invalid}\n contentError={contentError}\n errorId={errorId}\n surface={\n <>\n <EditorToolbar\n editor={editor}\n state={state}\n disabled={disabled}\n label={label}\n toolbarExtra={toolbarExtra}\n openLink={openLink}\n expandControl={expansion.toggle}\n embedControl={embeds.toolbar}\n />\n <div\n className=\"ds-rte__content\"\n data-size={size}\n >\n <EditorContent editor={editor} />\n </div>\n </>\n }\n >\n {embeds.dialog}\n {editor && linkSelection && !disabled && (\n <LinkDialog\n editor={editor}\n selection={linkSelection}\n onClose={closeLink}\n />\n )}\n </EditorFrame>\n </EmbedContext.Provider>\n );\n },\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAyBA,SAASmB,EAAqB,GAAgB,GAAmB;CAC/D,IAAMC,IAAUC,EAAK,cAA2B,kBAAkB;CAClE,IAAI,CAACD,GACH;CAEF,IAAME,IAAQC,EAAO,KAAK,YAAYA,EAAO,MAAM,UAAU,IAAI,GAC3DC,IAAOJ,EAAQ,sBAAsB;CAC3C,CAAIE,EAAM,MAAME,EAAK,OAAOF,EAAM,SAASE,EAAK,YAC9C,EAAQ,aAAaF,EAAM,MAAME,EAAK,MAAMA,EAAK,SAAS;AAE9D;AAwBA,SAAgBC,GAAmB,EACjC,WACA,aACA,YAAS,IACT,YACA,UACA,eACA,kBACA,eACyB;CACzB,IAAMJ,IAAOX,EAAe,cAAc,GACpC,CAACgB,GAAUC,KAAeC,EAAS,EAAK,GACxC,CAACC,GAAcC,KAAmBF,EAAS,CAAC,GAC5CG,IAAgBC,EAA8B,IAAI,GAClDC,IAAkBD,EAA8B,IAAI,GACpDE,IAAYF,EAAiC,IAAI,GACjDG,IAAgBH,EAAO,EAAK,GAC5BI,IAAgBJ,EAAO,EAAK,GAC5BK,IAAWC,EAAM;CAEvB,AAAIZ,KAAYa,KAAY,CAACC,KAC3Bb,EAAY,E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CAED,OACE,kBAACiC,EAAa,UAAd;EAAuB,OAAO0N,EAAO;EACnC,UAAA,kBAAC9C,IAAD;GACE,KAAKqB;GACL,UAAU1O;GACC;GACA;GACA;GACD;GACV,SAAS,CAAC,CAACU;GACG;GACL;GACT,SACE,kBAAAnD,GAAA,EAAA,UAAA,CACE,kBAACqP,IAAD;IACU;IACD;IACG;IACH;IACO;IACJ;IACV,eAAea,EAAU;IACzB,cAAc0C,EAAO;GACtB,CAAA,GACD,kBAAC,OAAD;IACE,WAAU;IACV,aAAWC;IAEX,UAAA,kBAACC,IAAD,EAAuB,UAAS,CAAA;GAC7B,CAAA,CACL,EAAA,CAAA;GA5BN,UAAA,CA+BGF,EAAO,QACPvR,KAAUiQ,KAAiB,CAACjP,KAC3B,kBAACiM,IAAD;IACU;IACR,WAAWgD;IACX,SAASE;GACV,CAAA,CAEQ;;CACQ,CAAA;AAE3B,CACF"}
|
|
@@ -20,8 +20,8 @@ function C(e) {
|
|
|
20
20
|
function w(e) {
|
|
21
21
|
return C(e) ? void 0 : S(e);
|
|
22
22
|
}
|
|
23
|
-
function T({ item: t, reasonId: n
|
|
24
|
-
let
|
|
23
|
+
function T({ item: t, reasonId: n }) {
|
|
24
|
+
let r = S(t);
|
|
25
25
|
return /* @__PURE__ */ x(y, { children: [/* @__PURE__ */ b("span", {
|
|
26
26
|
className: "ds-entry__thumb",
|
|
27
27
|
children: t.imageUrl ? /* @__PURE__ */ b("img", {
|
|
@@ -35,26 +35,26 @@ function T({ item: t, reasonId: n, titlePrefix: r }) {
|
|
|
35
35
|
}), /* @__PURE__ */ x("span", {
|
|
36
36
|
className: "ds-entry__body",
|
|
37
37
|
children: [
|
|
38
|
-
/* @__PURE__ */
|
|
38
|
+
/* @__PURE__ */ b("span", {
|
|
39
39
|
className: "ds-entry__title",
|
|
40
40
|
"data-unavailable": t.isUnavailable || void 0,
|
|
41
|
-
children:
|
|
41
|
+
children: t.title
|
|
42
42
|
}),
|
|
43
43
|
t.metadata != null && /* @__PURE__ */ b("span", {
|
|
44
44
|
className: "ds-entry__meta",
|
|
45
45
|
children: t.metadata
|
|
46
46
|
}),
|
|
47
|
-
|
|
47
|
+
r && /* @__PURE__ */ x("span", {
|
|
48
48
|
id: n,
|
|
49
49
|
className: "ds-entry__reason",
|
|
50
50
|
children: [
|
|
51
51
|
/* @__PURE__ */ b(a, {
|
|
52
52
|
shape: "tag",
|
|
53
53
|
size: "sm",
|
|
54
|
-
children:
|
|
54
|
+
children: r.label
|
|
55
55
|
}),
|
|
56
56
|
" ",
|
|
57
|
-
/* @__PURE__ */ b("span", { children:
|
|
57
|
+
/* @__PURE__ */ b("span", { children: r.description })
|
|
58
58
|
]
|
|
59
59
|
})
|
|
60
60
|
]
|
|
@@ -709,4 +709,4 @@ function ue(e, t, n, { isOpen: r, isDisabled: i, itemLabel: a, itemsLabel: o, cl
|
|
|
709
709
|
//#endregion
|
|
710
710
|
export { L as a, O as c, E as d, w as f, K as i, T as l, X as n, I as o, Y as r, A as s, ue as t, D as u };
|
|
711
711
|
|
|
712
|
-
//# sourceMappingURL=use-picker-session-
|
|
712
|
+
//# sourceMappingURL=use-picker-session-BDEWL2jK.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-picker-session-BDEWL2jK.js","names":["_Fragment","_Fragment","_Fragment","Icon","cannotHoldFocus","tabbableControls","useLatest","usableLimit","useRetryAttempt","LoadError","LoadState","Fragment$1","entryReason","item","isRemovedSelection","selectedReason","EntryRow","reason","reasonId","Badge","SelectedEntry","RemovedLabel","EditItemButton","onEdit","Button","placeholder","chosenItems","staticById","items","pageById","pageItems","selected","id","known","itemLabel","hasResolver","failures","asError","failure","without","ids","map","next","seeded","found","seed","copy","copies","fresh","old","entries","list","changesIds","previous","update","refreshKey","removed","useSelectedItems","resolve","resolveItem","selection","stored","setCopies","useState","shown","useMemo","stale","remember","seen","revision","gaps","staticIds","unknown","unknownKey","requested","useRef","resolveOne","tokens","unseen","token","settle","describe","failed","useLoadError","retry","status","error","onRetry","NoResults","search","query","itemsLabel","canCreate","resultControl","scroll","paging","rows","row","start","control","usePagingFocus","pagingRef","focusFrom","remote","useEffect","more","offset","useSwapFocus","shows","PickerPaging","load","isRemote","total","pageSize","count","resultBlock","isDisabled","searching","isSelected","atMax","PickerResults","useId","fullId","block","blocked","index","event","onToggle","Checkbox","usePickerScroll","ref","scrolled","setScrolled","PickerDialog","refreshFailure","Modal","isDialogHidden","dialogTitle","addLabel","dialogDescription","cap","LimitReading","onClose","PickerFrame","onCreate","isCreating","results","toTop","onQuery","SearchField","isSearching","action","banner","isBusy","selectsOne","mode","max","selectionLimit","selectionCount","pickerCap","limit","description","SEARCH_DELAY_MS","unique","noRows","noPages","moreState","isAvailable","extend","page","appendPage","key","loadRows","target","pages","isCurrent","answered","loading","hasMore","isStale","refreshFailed","usePickerData","loadPage","report","onItems","round","setRound","setPages","setMore","setRefreshFailure","wasOpen","setWasOpen","isOpen","lastSearch","canLoadMore","refresh","plan","delay","timer","loadOne","loadMore","loadMorePage","requestKey","asked","applies","emptyItems","restricted","restrict","usePickerSession","setQuery","source","filtered","editItem","onEditItem","close","result"],"sources":["../../src/components/EntryPicker/item.tsx","../../src/components/EntryPicker/chosen.ts","../../src/components/EntryPicker/use-selected-items.ts","../../src/components/EntryPicker/feedback.tsx","../../src/components/EntryPicker/blocked.ts","../../src/components/EntryPicker/results.tsx","../../src/components/EntryPicker/use-picker-scroll.ts","../../src/components/EntryPicker/dialog.tsx","../../src/components/EntryPicker/limit.ts","../../src/components/EntryPicker/use-picker-data.ts","../../src/components/EntryPicker/use-picker-session.ts"],"sourcesContent":["import { Button } from \"../Button\";\nimport { Badge } from \"../Badge\";\nimport { Icon } from \"../Icon\";\nimport type { EntryItem } from \"./types\";\n\n/**\n * The reason an item's row shows, which also describes the row's controls:\n * its own `disabledReason` while `isDisabled`. Rows and their `aria-describedby`\n * both read it, so a description never points at a reason that isn't shown.\n */\nexport function entryReason(item: EntryItem) {\n return item.isDisabled ? item.disabledReason : undefined;\n}\n\n/** A removed selection shows compactly, without thumbnail, pencil or reason. */\nfunction isRemovedSelection(item: EntryItem) {\n return item.tone === \"removed\";\n}\n\n/** The reason a selected row shows ({@link SelectedEntry}). */\nexport function selectedReason(item: EntryItem) {\n return isRemovedSelection(item) ? undefined : entryReason(item);\n}\n\n/** Thumbnail, title, app metadata and any restriction on the item. */\nexport function EntryRow({ item, reasonId }: { item: EntryItem; reasonId?: string }) {\n const reason = entryReason(item);\n return (\n <>\n <span className=\"ds-entry__thumb\">\n {item.imageUrl ? (\n <img\n src={item.imageUrl}\n alt=\"\"\n loading=\"lazy\"\n />\n ) : (\n <Icon\n name=\"file-text\"\n size={20}\n />\n )}\n </span>\n <span className=\"ds-entry__body\">\n <span\n className=\"ds-entry__title\"\n data-unavailable={item.isUnavailable || undefined}\n >\n {item.title}\n </span>\n {item.metadata != null && <span className=\"ds-entry__meta\">{item.metadata}</span>}\n {reason && (\n <span\n id={reasonId}\n className=\"ds-entry__reason\"\n >\n <Badge\n shape=\"tag\"\n size=\"sm\"\n >\n {reason.label}\n </Badge>{\" \"}\n <span>{reason.description}</span>\n </span>\n )}\n </span>\n </>\n );\n}\n\n/** A selected row: a removed record shows compactly, by title and metadata or ID. */\nexport function SelectedEntry({ item, reasonId }: { item: EntryItem; reasonId?: string }) {\n if (isRemovedSelection(item)) {\n return (\n <span className=\"ds-entry__removed\">\n <strong>{item.title}</strong> {item.metadata ?? <code>{item.id}</code>}\n </span>\n );\n }\n return (\n <EntryRow\n item={item}\n reasonId={reasonId}\n />\n );\n}\n\nexport function RemovedLabel({ item }: { item: EntryItem }) {\n return isRemovedSelection(item) ? (\n <Badge shape=\"tag\">{item.removedLabel ?? \"Removed on save\"}</Badge>\n ) : null;\n}\n\nexport function EditItemButton({\n item,\n onEdit,\n isDisabled,\n}: {\n item: EntryItem;\n onEdit?: (item: EntryItem) => void;\n isDisabled?: boolean;\n}) {\n if (!onEdit || item.isUnavailable || item.isDisabled) {\n return null;\n }\n return (\n <Button\n variant=\"simple\"\n size=\"sm\"\n isIconOnly\n iconStart=\"pencil\"\n aria-label={`Edit ${item.title}`}\n isDisabled={isDisabled}\n onClick={() => onEdit(item)}\n />\n );\n}\n","import type { EntryItem } from \"./types\";\n\nfunction placeholder(id: string, title: string, metadata?: string): EntryItem {\n return { id, title, metadata, isUnavailable: true };\n}\n\n/**\n * The selected rows, in stored order. Static items come first, then the latest\n * known copy, then the current page. Without `resolveItem` an ID nothing\n * describes shows as itself: not knowing an item isn't the same as it being gone.\n */\nexport function chosenItems({\n selected,\n items,\n pageItems,\n known,\n failures,\n hasResolver,\n itemLabel,\n}: {\n selected: string[];\n items: EntryItem[];\n pageItems: EntryItem[];\n known: Map<string, EntryItem | null>;\n failures: Map<string, unknown>;\n hasResolver: boolean;\n itemLabel: string;\n}): EntryItem[] {\n const staticById = new Map(items.map((item) => [item.id, item]));\n const pageById = new Map(pageItems.map((item) => [item.id, item]));\n return selected.map((id) => {\n const item = staticById.get(id) ?? (known.has(id) ? known.get(id) : pageById.get(id));\n if (item) {\n return item;\n }\n if (known.has(id)) {\n const name = `${itemLabel.charAt(0).toUpperCase()}${itemLabel.slice(1)}`;\n return placeholder(id, `${name} no longer available`, \"Replace or clear this selection.\");\n }\n if (!hasResolver) {\n return { id, title: id };\n }\n return placeholder(id, failures.has(id) ? `Couldn't load ${itemLabel}` : \"Loading…\");\n });\n}\n","import { useEffect, useMemo, useRef, useState } from \"react\";\nimport type { LoadStatus } from \"../LoadState\";\nimport { useLatest } from \"../../internal/useLatest\";\nimport type { EntryItem, EntryPickerSource } from \"./types\";\n\ntype RefreshKey = EntryPickerSource[\"refreshKey\"];\n\nexport function asError(failure: unknown) {\n return failure instanceof Error ? failure : null;\n}\n\n/** The map without `ids`, or the same map when it holds none of them. */\nfunction without<V>(map: Map<string, V>, ids: string[]) {\n if (!ids.some((id) => map.has(id))) {\n return map;\n }\n const next = new Map(map);\n for (const id of ids) {\n next.delete(id);\n }\n return next;\n}\n\n/** What the picker knows about the selected IDs beyond its static items. */\ninterface Copies {\n /** The refresh that `known` and `failures` describe. */\n refreshKey: RefreshKey;\n /** The selected IDs the maps describe, in any order. */\n selected: string[];\n /** The copy a page, a pick or `resolveItem` supplied since the last refresh; null: unavailable. */\n known: Map<string, EntryItem | null>;\n /** Copies from before the last refresh, shown until a fresh copy replaces them. */\n stale: Map<string, EntryItem | null>;\n failures: Map<string, Error | null>;\n /** The seed copies already applied, by ID, so each pick applies once. */\n seeds: Map<string, SeedCopy>;\n}\n\n/** A copy of an item someone already read, at the `refreshKey` it was read at. */\nexport interface SeedCopy {\n item: EntryItem;\n revision: RefreshKey;\n}\nexport type SeedLookup = (id: string) => SeedCopy | undefined;\n\n/**\n * Apply copies read elsewhere for `ids`, each seed copy once, as `remember`\n * would: one read at the current refresh is the latest copy, replacing a\n * cached lookup or failure, and an older one only fills a stale gap. Applied\n * during render, so a seeded ID never shows Loading… or is resolved, and a new\n * pick for an ID already shown replaces its copy.\n */\nfunction seeded(copies: Copies, ids: string[], seed: SeedLookup | undefined): Copies {\n const found = seed\n ? ids.flatMap((id) => {\n const copy = seed(id);\n return copy?.item.id === id && copies.seeds.get(id) !== copy ? [copy] : [];\n })\n : [];\n if (found.length === 0) {\n return copies;\n }\n const fresh = found.filter((copy) => Object.is(copy.revision, copies.refreshKey));\n const old = found.filter(\n (copy) =>\n !Object.is(copy.revision, copies.refreshKey) &&\n !copies.known.has(copy.item.id) &&\n !copies.stale.has(copy.item.id),\n );\n const entries = (list: SeedCopy[]) => list.map((copy) => [copy.item.id, copy.item] as const);\n return {\n ...copies,\n seeds: new Map([...copies.seeds, ...found.map((copy) => [copy.item.id, copy] as const)]),\n known: fresh.length ? new Map([...copies.known, ...entries(fresh)]) : copies.known,\n stale: old.length ? new Map([...copies.stale, ...entries(old)]) : copies.stale,\n failures: without(\n copies.failures,\n fresh.map((copy) => copy.item.id),\n ),\n };\n}\n\n/** Whether `next` adds or removes an ID. A reorder changes nothing the maps describe. */\nfunction changesIds(previous: string[], next: string[]) {\n return (\n previous !== next &&\n (previous.length !== next.length || next.some((id) => !previous.includes(id)))\n );\n}\n\n/**\n * A refresh makes every copy stale and clears failures, so each ID is described\n * again. Removing an ID forgets it, so a restored ID (an undo or a form reset)\n * is described afresh. Picks remembered before a controlled value catches up\n * are kept: they were never removed.\n */\nfunction update(\n copies: Copies,\n selected: string[],\n refreshKey: RefreshKey,\n seed: SeedLookup | undefined,\n): Copies {\n let next = copies;\n if (!Object.is(next.refreshKey, refreshKey)) {\n next = {\n ...next,\n refreshKey,\n known: new Map(),\n stale: new Map([...next.stale, ...next.known]),\n failures: new Map(),\n };\n }\n if (changesIds(next.selected, selected)) {\n const removed = next.selected.filter((id) => !selected.includes(id));\n next = {\n ...next,\n selected,\n known: without(next.known, removed),\n stale: without(next.stale, removed),\n failures: without(next.failures, removed),\n seeds: without(next.seeds, removed),\n };\n }\n return seeded(next, selected, seed);\n}\n\n/**\n * The latest copy of each selected item. Only IDs without a copy since the last\n * refresh are resolved, once each, and a retry re-resolves just the failed\n * ones. A stale copy stays on screen until its fresh one arrives, so a refresh\n * never blanks a row. A reply for an ID removed, described or refreshed since\n * it was requested is dropped. `seed` supplies copies another reader already\n * holds, such as a row just picked in a dialog, for IDs as they arrive.\n */\nexport function useSelectedItems(\n selected: string[],\n items: EntryItem[],\n resolveItem: EntryPickerSource[\"resolveItem\"],\n refreshKey?: RefreshKey,\n seed?: SeedLookup,\n) {\n const resolve = useLatest(resolveItem);\n const selection = useLatest(selected);\n const [stored, setCopies] = useState<Copies>(() =>\n seeded(\n {\n refreshKey,\n selected,\n known: new Map(),\n stale: new Map(),\n failures: new Map(),\n seeds: new Map(),\n },\n selected,\n seed,\n ),\n );\n const copies = update(stored, selected, refreshKey, seed);\n if (copies !== stored) {\n setCopies(copies);\n }\n const { known, stale, failures } = copies;\n const shown = useMemo(\n () => (stale.size === 0 ? known : new Map([...stale, ...known])),\n [stale, known],\n );\n\n /**\n * Keep the latest copy of selected items a page or a pick shows, so edits\n * appear. A copy read at `revision`, before the latest refresh, is no fresher\n * than the stale copies: it only fills a gap among them, so a pick from older\n * rows keeps its title and actions while it is described again.\n */\n const remember = (\n seen: (EntryItem | undefined)[],\n revision: RefreshKey,\n ids = selection.current,\n ) => {\n const copies = seen\n .filter((item): item is EntryItem => item !== undefined && ids.includes(item.id))\n .map((item) => [item.id, item] as const);\n if (copies.length === 0) {\n return;\n }\n setCopies((previous) => {\n if (Object.is(previous.refreshKey, revision)) {\n return { ...previous, known: new Map([...previous.known, ...copies]) };\n }\n const gaps = copies.filter(([id]) => !previous.known.has(id) && !previous.stale.has(id));\n return gaps.length === 0\n ? previous\n : { ...previous, stale: new Map([...previous.stale, ...gaps]) };\n });\n };\n\n const staticIds = new Set(items.map((item) => item.id));\n const unknown = resolveItem\n ? selected.filter((id) => !staticIds.has(id) && !known.has(id) && !failures.has(id))\n : [];\n const unknownKey = JSON.stringify(unknown);\n /** Lookups in flight for the current refresh, by ID. */\n const requested = useRef({ refreshKey, tokens: new Map<string, symbol>() });\n useEffect(() => {\n const resolveOne = resolve.current;\n if (!resolveOne) {\n return;\n }\n const ids = JSON.parse(unknownKey) as string[];\n if (!Object.is(requested.current.refreshKey, refreshKey)) {\n requested.current = { refreshKey, tokens: new Map() };\n }\n const { tokens } = requested.current;\n // A lookup for an ID since described or removed no longer counts.\n for (const id of tokens.keys()) {\n if (!ids.includes(id)) {\n tokens.delete(id);\n }\n }\n for (const id of ids.filter((unseen) => !tokens.has(unseen))) {\n const token = Symbol(id);\n tokens.set(id, token);\n const settle = (describe: (previous: Copies) => Copies) => {\n if (requested.current.tokens.get(id) !== token) {\n return;\n }\n requested.current.tokens.delete(id);\n setCopies((previous) =>\n Object.is(previous.refreshKey, refreshKey) && previous.selected.includes(id)\n ? describe(previous)\n : previous,\n );\n };\n void Promise.resolve()\n .then(() => resolveOne(id))\n .then(\n // A page or pick that arrived meanwhile is at least as fresh.\n (item) =>\n settle((previous) =>\n previous.known.has(id)\n ? previous\n : { ...previous, known: new Map(previous.known).set(id, item ?? null) },\n ),\n (failure: unknown) =>\n settle((previous) => ({\n ...previous,\n failures: new Map(previous.failures).set(id, asError(failure)),\n })),\n );\n }\n }, [unknownKey, refreshKey, resolve]);\n\n const failed = selected.filter((id) => failures.has(id) && !known.has(id));\n const status: LoadStatus = unknown.length > 0 ? \"loading\" : failed.length > 0 ? \"error\" : \"ready\";\n return {\n known: shown,\n failures,\n remember,\n status,\n error: failed.length > 0 ? (failures.get(failed[0]) ?? null) : null,\n retry: () =>\n setCopies((previous) => ({ ...previous, failures: without(previous.failures, failed) })),\n };\n}\n","import { useEffect, useRef, type RefObject } from \"react\";\nimport { Button } from \"../Button\";\nimport { LoadError, type LoadStatus } from \"../LoadState\";\nimport { useRetryAttempt } from \"../LoadState/useRetryAttempt\";\nimport { cannotHoldFocus, tabbableControls } from \"../../internal/dialogFocus\";\nimport type { PickerData } from \"./use-picker-data\";\n\n/** The shared failure banner while a load has failed or its retry runs; null otherwise. */\nexport function useLoadError(\n title: string,\n status: LoadStatus,\n error: Error | null,\n onRetry: () => void,\n) {\n const retry = useRetryAttempt(status, error, onRetry);\n if (status !== \"error\" && retry.state !== \"pending\") {\n return null;\n }\n return (\n <LoadError\n title={title}\n error={retry.error}\n onRetry={retry.retry}\n retryState={retry.state}\n />\n );\n}\n\nexport function NoResults({\n query,\n itemLabel,\n itemsLabel,\n canCreate,\n}: {\n query: string;\n itemLabel: string;\n itemsLabel: string;\n canCreate: boolean;\n}) {\n const search = query.trim();\n return (\n <div className=\"ds-entry-picker__no-results\">\n <p>{search ? `No ${itemsLabel} match “${search}”` : `No ${itemsLabel} yet`}</p>\n {search && (\n <p>Try a different search.{canCreate ? ` Or create the ${itemLabel} you need.` : \"\"}</p>\n )}\n </div>\n );\n}\n\n/** The first control in the result rows from `start`, else the nearest one before it. */\nfunction resultControl(paging: HTMLElement, start: number) {\n const scroll = paging.closest(\".ds-entry-picker__scroll\") ?? paging.parentElement;\n const rows = Array.from(scroll?.querySelectorAll<HTMLElement>(\".ds-entry-picker__result\") ?? []);\n for (const row of [...rows.slice(start), ...rows.slice(0, start).reverse()]) {\n const control = tabbableControls(row)[0];\n if (control) {\n return control;\n }\n }\n return undefined;\n}\n\n/**\n * Load more unmounts when the last page arrives or its request fails, and a\n * failure banner unmounts when its retry succeeds. When the paging held focus\n * and lost it that way, focus moves to the first new row, or to Try again.\n */\nfunction usePagingFocus(remote: PickerData) {\n const pagingRef = useRef<HTMLDivElement | null>(null);\n const focusFrom = useRef<number | null>(null);\n const { more, offset } = remote;\n const load = () => {\n focusFrom.current = pagingRef.current?.contains(document.activeElement) ? offset : null;\n more.load();\n };\n useEffect(() => {\n const start = focusFrom.current;\n const paging = pagingRef.current;\n if (start === null || more.status === \"loading\") {\n return;\n }\n focusFrom.current = null;\n if (paging && cannotHoldFocus(document.activeElement)) {\n const target =\n more.status === \"error\" ? tabbableControls(paging)[0] : resultControl(paging, start);\n target?.focus();\n }\n }, [more.status, offset]);\n return { pagingRef, load };\n}\n\n/**\n * A search or refresh also swaps the paging's control without the paging\n * asking: it hides a failed Load more, and the rows it brings hide the banner\n * or end paging. When that drops focus, focus moves to the control that\n * replaced it, else to the last row.\n */\nfunction useSwapFocus(\n pagingRef: RefObject<HTMLDivElement | null>,\n shows: \"failure\" | \"more\" | \"none\",\n) {\n const shown = useRef(shows);\n useEffect(() => {\n if (shown.current === shows) {\n return;\n }\n shown.current = shows;\n const paging = pagingRef.current;\n if (paging && cannotHoldFocus(document.activeElement)) {\n (tabbableControls(paging)[0] ?? resultControl(paging, Infinity))?.focus();\n }\n }, [pagingRef, shows]);\n}\n\n/** How much is shown, and for server results a Load more action with its own failure. */\nexport function PickerPaging({\n count,\n total,\n isRemote,\n pageSize,\n remote,\n itemsLabel,\n}: {\n count: number;\n total: number;\n isRemote: boolean;\n pageSize: number;\n remote: PickerData;\n itemsLabel: string;\n}) {\n const { more } = remote;\n const { pagingRef, load } = usePagingFocus(remote);\n const failure = useLoadError(`Couldn't load more ${itemsLabel}`, more.status, more.error, load);\n useSwapFocus(pagingRef, failure ? \"failure\" : isRemote && remote.hasMore ? \"more\" : \"none\");\n if (total === 0) {\n return null;\n }\n return (\n <div\n ref={pagingRef}\n className=\"ds-entry-picker__paging\"\n >\n {failure ??\n (isRemote && remote.hasMore && (\n <Button\n isPending={more.status === \"loading\"}\n isFocusableWhenDisabled\n isDisabled={!more.isAvailable}\n onClick={load}\n >\n Load {Math.min(pageSize, total - remote.offset)} more\n </Button>\n ))}\n <span>{count < total ? `Showing ${count} of ${total}` : `All ${count} shown`}</span>\n </div>\n );\n}\n","import type { EntryItem } from \"./types\";\n\nexport interface PickerBlockState {\n /** The whole picker is disabled. */\n isDisabled: boolean;\n /** A new search will replace the rows shown. */\n searching: boolean;\n /** A capped multiple selection is full. */\n atMax: boolean;\n}\n\n/**\n * Why a result can't be toggled now, or undefined when it can. The rows and the\n * picker's own toggle share this rule, so neither can bypass the other.\n *\n * - `\"inactive\"`: the picker can't act at all; its checkboxes are natively disabled.\n * - `\"restricted\"`: the item's own `isDisabled`, explained by its `disabledReason`.\n * - `\"full\"`: the selection has reached its cap.\n *\n * Restricted and full results keep a focusable checkbox, described by why.\n */\nexport function resultBlock(\n item: EntryItem,\n isSelected: boolean,\n { isDisabled, searching, atMax }: PickerBlockState,\n): \"inactive\" | \"restricted\" | \"full\" | undefined {\n if (isDisabled || searching) {\n return \"inactive\";\n }\n if (item.isDisabled) {\n return \"restricted\";\n }\n if (!isSelected && atMax) {\n return \"full\";\n }\n return undefined;\n}\n","import { useId } from \"react\";\nimport { Checkbox } from \"../Choice\";\nimport { resultBlock, type PickerBlockState } from \"./blocked\";\nimport { EditItemButton, EntryRow, entryReason } from \"./item\";\nimport type { EntryItem } from \"./types\";\nexport function PickerResults({\n items,\n selected,\n block,\n onToggle,\n onEdit,\n}: {\n items: EntryItem[];\n selected: string[];\n block: PickerBlockState;\n onToggle: (id: string) => void;\n onEdit?: (item: EntryItem) => void;\n}) {\n const id = useId();\n const fullId = `${id}-full`;\n return (\n <>\n {/* Describes results refused only because the selection is full. */}\n <span\n id={fullId}\n hidden\n >\n The selection is full. Remove one to choose another.\n </span>\n <ul\n className=\"ds-entry-picker__results\"\n data-searching={block.searching || undefined}\n >\n {items.map((item, index) => {\n const isSelected = selected.includes(item.id);\n const blocked = resultBlock(item, isSelected, block);\n const reasonId = entryReason(item) ? `${id}-reason-${index}` : undefined;\n return (\n <li\n key={item.id}\n className=\"ds-entry-picker__result\"\n data-selected={isSelected || undefined}\n data-blocked={blocked ? true : undefined}\n onClick={(event) => {\n const control =\n event.target instanceof Element\n ? event.target.closest(\n \"button, input, label, a, select, textarea, summary, [tabindex]\",\n )\n : null;\n // The picker's toggle refuses blocked results.\n if (!control || !event.currentTarget.contains(control)) {\n onToggle(item.id);\n }\n }}\n >\n <Checkbox\n checked={isSelected}\n aria-checked={isSelected}\n aria-label={`Select ${item.title}`}\n aria-describedby={blocked === \"full\" ? fullId : reasonId}\n disabled={Boolean(blocked)}\n isFocusableWhenDisabled={blocked !== \"inactive\"}\n onChange={() => onToggle(item.id)}\n />\n <span className=\"ds-entry\">\n <EntryRow\n item={item}\n reasonId={reasonId}\n />\n </span>\n <EditItemButton\n item={item}\n onEdit={onEdit}\n isDisabled={blocked === \"inactive\"}\n />\n </li>\n );\n })}\n </ul>\n </>\n );\n}\n","import { useRef, useState, type UIEvent } from \"react\";\n\n/**\n * The picker's results pane. Suspended dialogs stay laid out, so the browser\n * keeps the pane's position and nothing here restores it. Only a new search\n * moves the pane: `toTop` runs in the same event as the query change, so both\n * render once. Scrolling rerenders only when the pane reaches or leaves the top.\n */\nexport function usePickerScroll() {\n const ref = useRef<HTMLDivElement>(null);\n const [scrolled, setScrolled] = useState(false);\n return {\n ref,\n scrolled,\n toTop: () => {\n setScrolled(false);\n if (ref.current) {\n ref.current.scrollTop = 0;\n }\n },\n onScroll: (event: UIEvent<HTMLDivElement>) => {\n setScrolled(event.currentTarget.scrollTop > 0);\n },\n };\n}\n","import type { ReactNode } from \"react\";\nimport { Button } from \"../Button\";\nimport { LoadState } from \"../LoadState\";\nimport { LimitReading } from \"../LimitReading\";\nimport { Modal } from \"../Modal\";\nimport { SearchField } from \"../SearchField\";\nimport type { PickerBlockState } from \"./blocked\";\nimport { NoResults, PickerPaging, useLoadError } from \"./feedback\";\nimport type { PickerCap } from \"./limit\";\nimport { PickerResults } from \"./results\";\nimport type { EntryItem, EntryPickerProps } from \"./types\";\nimport { usePickerScroll } from \"./use-picker-scroll\";\nimport type { PickerData } from \"./use-picker-data\";\ntype DialogProps = Pick<\n EntryPickerProps,\n \"onCreate\" | \"isCreating\" | \"dialogTitle\" | \"dialogDescription\" | \"isDialogHidden\"\n> & {\n itemLabel: string;\n itemsLabel: string;\n addLabel: string;\n isOpen: boolean;\n onClose: () => void;\n query: string;\n onQuery: (query: string) => void;\n selected: string[];\n results: EntryItem[];\n /** The picker's own cap, which its Field's counter may override. */\n cap: PickerCap;\n block: PickerBlockState;\n isRemote: boolean;\n pageSize: number;\n remote: PickerData;\n onToggle: (id: string) => void;\n onEdit?: (item: EntryItem) => void;\n};\nexport function PickerDialog({\n isOpen,\n onClose,\n query,\n onQuery,\n selected,\n results,\n cap,\n block,\n isRemote,\n pageSize,\n remote,\n onToggle,\n onEdit,\n itemLabel,\n itemsLabel,\n addLabel,\n onCreate,\n isCreating,\n dialogTitle,\n dialogDescription,\n isDialogHidden,\n}: DialogProps) {\n // The rows stay usable after a failed refresh; this offers to read them again.\n const refreshFailure = useLoadError(\n `Couldn't refresh ${itemsLabel}`,\n remote.refresh.status,\n remote.refresh.error,\n remote.refresh.retry,\n );\n return (\n <Modal\n isOpen={isOpen}\n isHidden={isDialogHidden}\n onClose={onClose}\n title={dialogTitle ?? addLabel}\n description={dialogDescription ?? cap.description}\n className=\"ds-entry-picker__dialog\"\n footer={\n <>\n <span\n className=\"ds-entry-picker__selection\"\n role=\"status\"\n >\n {cap.reading ? (\n <LimitReading\n {...cap.reading}\n size=\"lg\"\n />\n ) : (\n `${selected.length} selected`\n )}\n </span>\n <Button\n variant=\"primary\"\n onClick={onClose}\n >\n Done\n </Button>\n </>\n }\n >\n <PickerFrame\n query={query}\n onQuery={onQuery}\n itemsLabel={itemsLabel}\n isSearching={remote.loading}\n action={\n onCreate && (\n // Primary beside Done: Button's one recorded exception (decision 0086).\n // Focusable while blocked, so creation that ends at the cap keeps focus here.\n <Button\n variant=\"primary\"\n isPending={isCreating}\n isFocusableWhenDisabled\n iconStart=\"plus\"\n isDisabled={block.isDisabled || cap.atMax}\n onClick={onCreate}\n >\n {`New ${itemLabel}`}\n </Button>\n )\n }\n banner={refreshFailure}\n isBusy={\n remote.loading || remote.more.status === \"loading\" || remote.refresh.status === \"loading\"\n }\n >\n <LoadState\n status={remote.status}\n errorTitle={`Couldn't load ${itemsLabel}`}\n error={remote.error}\n onRetry={remote.retry}\n >\n <PickerResults\n items={results}\n selected={selected}\n block={block}\n onToggle={onToggle}\n onEdit={onEdit}\n />\n {!remote.searching && results.length === 0 && (\n <NoResults\n query={query}\n itemLabel={itemLabel}\n itemsLabel={itemsLabel}\n canCreate={Boolean(onCreate)}\n />\n )}\n <PickerPaging\n count={results.length}\n total={isRemote ? remote.total : results.length}\n isRemote={isRemote}\n pageSize={pageSize}\n remote={remote}\n itemsLabel={itemsLabel}\n />\n </LoadState>\n </PickerFrame>\n </Modal>\n );\n}\n\n/**\n * The search row, an optional banner and the scrolling results. Rendered inside\n * the Modal, so it mounts with each opening and starts at the top. A new search\n * returns to the top in the same event that changes the query, so both render\n * once.\n */\nfunction PickerFrame({\n query,\n onQuery,\n itemsLabel,\n isSearching,\n action,\n banner,\n isBusy,\n children,\n}: {\n query: string;\n onQuery: (query: string) => void;\n itemsLabel: string;\n isSearching: boolean;\n action: ReactNode;\n banner: ReactNode;\n isBusy: boolean;\n children: ReactNode;\n}) {\n const { ref, scrolled, onScroll, toTop } = usePickerScroll();\n const search = (next: string) => {\n toTop();\n onQuery(next);\n };\n return (\n <>\n <div\n className=\"ds-entry-picker__search\"\n data-scrolled={scrolled || undefined}\n >\n <SearchField\n aria-label={`Search ${itemsLabel}`}\n value={query}\n isBusy={isSearching}\n placeholder={`Search ${itemsLabel}`}\n onChange={(event) => search(event.target.value)}\n onClear={() => search(\"\")}\n />\n {action}\n </div>\n {banner && <div className=\"ds-entry-picker__refresh\">{banner}</div>}\n <div\n className=\"ds-entry-picker__scroll\"\n ref={ref}\n onScroll={onScroll}\n aria-busy={isBusy}\n >\n {children}\n </div>\n </>\n );\n}\n","import type { FieldLimit } from \"../Field/types\";\nimport { usableLimit } from \"../LimitReading/limit\";\nimport type { EntryPickerMode } from \".\";\n\n/** A single selection, or a multiple one capped at one, holds one item. */\nfunction selectsOne(mode: EntryPickerMode, max: number | undefined) {\n return mode === \"single\" || max === 1;\n}\n\n/**\n * The selection's usage limit. A one-item selection is a slot to fill, read\n * neutrally; otherwise only an explicitly capped multiple selection has one.\n * Pure, so FormEditor's model derives the same server-rendered limit the\n * picker reports.\n */\nexport function selectionLimit(\n mode: EntryPickerMode,\n count: number,\n max: number | undefined,\n): FieldLimit | undefined {\n if (selectsOne(mode, max)) {\n return { count, max: 1, tone: \"neutral\" };\n }\n return mode === \"multiple\" && max !== undefined ? { count, max } : undefined;\n}\n\n/** The Field's count badge, which a one-item slot's own reading replaces. */\nexport function selectionCount(mode: EntryPickerMode, count: number, max: number | undefined) {\n return selectsOne(mode, max) ? undefined : count;\n}\n\nexport interface PickerCap {\n /** The Field counter's limit, as FormEditor's model derives it. */\n limit: FieldLimit | undefined;\n /** The selection has reached an enforced cap. */\n atMax: boolean;\n /** The dialog's default description. */\n description: string;\n /** The footer's LimitReading, when the limit reads as usage. */\n reading: FieldLimit | undefined;\n}\n\n/**\n * Everything the picker derives from its mode and max, so the cap is decided\n * in one place: only a finite max in multiple mode is enforced and described.\n * Infinity and NaN never fill, so they read as no limit.\n */\nexport function pickerCap(\n mode: EntryPickerMode,\n count: number,\n max: number | undefined,\n { itemLabel, itemsLabel }: { itemLabel: string; itemsLabel: string },\n): PickerCap {\n const limit = selectionLimit(mode, count, max);\n // Single mode replaces its one selection, so only a multiple cap blocks rows.\n const cap = mode === \"multiple\" && limit && Number.isFinite(limit.max) ? limit.max : undefined;\n let description = `Choose as many ${itemsLabel} as you need.`;\n if (mode === \"single\" || cap === 1) {\n description = `Choose one ${itemLabel}.`;\n } else if (cap !== undefined) {\n description = `Choose up to ${cap} ${itemsLabel}.`;\n }\n return {\n limit,\n atMax: cap !== undefined && count >= cap,\n description,\n // Single mode closes on its first pick, so its footer keeps the plain count.\n reading: mode === \"multiple\" && usableLimit(limit) ? limit : undefined,\n };\n}\n","import { useEffect, useRef, useState } from \"react\";\nimport type { LoadStatus } from \"../LoadState\";\nimport { useLatest } from \"../../internal/useLatest\";\nimport { asError } from \"./use-selected-items\";\nimport type { EntryItem, EntryPickerPage, EntryPickerSource } from \"./types\";\n\nconst SEARCH_DELAY_MS = 250;\n\ntype LoadPage = NonNullable<EntryPickerSource[\"loadPage\"]>;\ntype RefreshKey = EntryPickerSource[\"refreshKey\"];\n\nfunction unique(items: EntryItem[]) {\n return Array.from(new Map(items.map((item) => [item.id, item])).values());\n}\n\n/** Rows read from the start of a result list. */\ninterface Rows {\n items: EntryItem[];\n /** The next server offset; a duplicate row still advances it. */\n offset: number;\n total: number;\n}\nconst noRows: Rows = { items: [], offset: 0, total: 0 };\n\ninterface Pages extends Rows {\n /** The request these rows answer; null until an open dialog's first reply. */\n key: string | null;\n /** The `refreshKey` they were read at. */\n revision: RefreshKey;\n status: \"ready\" | \"error\";\n error: Error | null;\n}\nconst noPages: Pages = { ...noRows, key: null, revision: undefined, status: \"ready\", error: null };\n\ninterface MoreRequest {\n token: symbol;\n status: \"loading\" | \"error\";\n error: Error | null;\n}\n\n/**\n * What Load more reports for the shown rows. Paging extends only current rows,\n * so it waits while a search or refresh replaces them, and a failed Load more,\n * which belongs to the rows it extended, is no longer reported meanwhile. One in\n * flight stays loading: a refresh folds it in.\n */\nfunction moreState(more: MoreRequest | null, isAvailable: boolean) {\n const failed = more?.status === \"error\" && isAvailable;\n const status: LoadStatus = more?.status === \"loading\" ? \"loading\" : failed ? \"error\" : \"ready\";\n return { status, error: failed ? (more.error ?? null) : null, isAvailable };\n}\n\n/** A background refresh that failed, leaving the rows read at an earlier revision. */\ninterface RefreshFailure {\n key: string;\n revision: RefreshKey;\n error: Error | null;\n}\n\n/** The rows after `page`, which was requested at their offset. */\nfunction extend(rows: Rows, page: EntryPickerPage): Rows {\n return {\n items: unique([...rows.items, ...page.items]),\n offset: rows.offset + page.items.length,\n // An empty page ends paging even when the total overcounted.\n total: page.items.length === 0 ? Math.min(page.total, rows.offset) : page.total,\n };\n}\n\n/** Append a further page, unless a newer search or page replaced the rows meanwhile. */\nfunction appendPage(previous: Pages, key: string, offset: number, page: EntryPickerPage): Pages {\n if (previous.key !== key || previous.offset !== offset) {\n return previous;\n }\n return { ...previous, ...extend(previous, page) };\n}\n\n/**\n * At least one page, and at least the first `target` rows. Full pages are\n * requested together; a short page before the end moves every later offset, so\n * the rest is read one page at a time from where it stopped.\n */\nasync function loadRows(\n load: LoadPage,\n query: string,\n limit: number,\n target: number,\n isCurrent: () => boolean,\n) {\n const count = Math.max(1, Math.ceil(target / limit));\n const pages = await Promise.all(\n Array.from({ length: count }, (_, index) => load({ offset: index * limit, limit }, { query })),\n );\n let rows = noRows;\n for (const [index, page] of pages.entries()) {\n if (rows.offset !== index * limit) {\n break;\n }\n rows = extend(rows, page);\n }\n while (rows.offset < target && rows.offset < rows.total && isCurrent()) {\n rows = extend(rows, await load({ offset: rows.offset, limit }, { query }));\n }\n return rows;\n}\n\n/** What the shown rows mean for the request, at the revision, the picker wants answered. */\nfunction describe(\n key: string | null,\n pages: Pages,\n refreshKey: RefreshKey,\n failure: RefreshFailure | null,\n) {\n const answered = key !== null && pages.key === key;\n const isCurrent = answered && Object.is(pages.revision, refreshKey);\n // A new request, or a failed one whose source has since changed.\n const loading = key !== null && !isCurrent && (!answered || pages.status === \"error\");\n // Rows from the previous search stay, dimmed, until the new search answers.\n const searching = loading && pages.key !== null && pages.status === \"ready\";\n const status: LoadStatus =\n loading && !searching ? \"loading\" : pages.status === \"error\" ? \"error\" : \"ready\";\n const hasMore = pages.status === \"ready\" && pages.offset < pages.total;\n // Rows read before a refresh stay usable while they are read again.\n const isStale = answered && !isCurrent && pages.status === \"ready\";\n const refreshFailed = isStale && failure?.key === key && Object.is(failure.revision, refreshKey);\n const refresh: LoadStatus = isStale ? (refreshFailed ? \"error\" : \"loading\") : \"ready\";\n return { loading, searching, status, hasMore, refresh, refreshFailed };\n}\n\n/**\n * Server pages for an open picker. Opening, a new search, a page size or a\n * retry requests the first page; an older reply never overwrites a newer one.\n * Closing discards the pages and starts a new round, so the next opening reads\n * the source afresh and no reply from an earlier opening, Load more included,\n * matches it. A new `refreshKey` reads the shown rows again in the background;\n * they stay usable meanwhile, and stay on screen if that fails. `loadPage` is\n * read when called, so an inline callback never reloads.\n */\nexport function usePickerData(\n loadPage: EntryPickerSource[\"loadPage\"],\n pageSize: number,\n query: string,\n isOpen: boolean,\n onItems: (items: EntryItem[], revision: RefreshKey) => void,\n refreshKey?: RefreshKey,\n) {\n const load = useLatest(loadPage);\n const report = useLatest(onItems);\n const revision = useLatest(refreshKey);\n // Each retry and each closing starts a new round of requests.\n const [round, setRound] = useState(0);\n const [pages, setPages] = useState(noPages);\n const [more, setMore] = useState<MoreRequest | null>(null);\n const [refreshFailure, setRefreshFailure] = useState<RefreshFailure | null>(null);\n const [wasOpen, setWasOpen] = useState(isOpen);\n if (wasOpen !== isOpen) {\n setWasOpen(isOpen);\n if (!isOpen) {\n setPages(noPages);\n setMore(null);\n setRefreshFailure(null);\n setRound((count) => count + 1);\n }\n }\n const search = query.trim();\n const key = loadPage && isOpen ? JSON.stringify([search, pageSize, round]) : null;\n const shown = useLatest(pages);\n // The Load more request in flight; replacing the rows makes it obsolete.\n const paging = useRef<symbol | null>(null);\n const lastSearch = useRef(search);\n const { loading, searching, status, hasMore, refresh, refreshFailed } = describe(\n key,\n pages,\n refreshKey,\n refreshFailure,\n );\n // A new search or a refresh would page at an old offset.\n const canLoadMore = !loading && refresh === \"ready\";\n const plan = loading ? \"load\" : refresh === \"loading\" ? \"refresh\" : null;\n\n useEffect(() => {\n if (key === null) {\n return;\n }\n const delay = plan === \"load\" && search !== lastSearch.current ? SEARCH_DELAY_MS : 0;\n lastSearch.current = search;\n if (plan === null) {\n return;\n }\n // A Load more in flight joins the refreshed rows instead of appending to the old ones.\n const target = plan === \"refresh\" ? shown.current.offset + (paging.current ? pageSize : 0) : 0;\n let isCurrent = true;\n const timer = window.setTimeout(() => {\n const loadOne = load.current;\n if (!loadOne) {\n return;\n }\n void loadRows(loadOne, search, pageSize, target, () => isCurrent).then(\n (rows) => {\n if (isCurrent) {\n paging.current = null;\n setPages({ ...rows, key, revision: refreshKey, status: \"ready\", error: null });\n setMore(null);\n setRefreshFailure(null);\n report.current(rows.items, refreshKey);\n }\n },\n (failure: unknown) => {\n if (!isCurrent) {\n return;\n }\n if (plan === \"refresh\") {\n setRefreshFailure({ key, revision: refreshKey, error: asError(failure) });\n return;\n }\n // A failed search drops the previous rows, so none stay selectable or pageable.\n paging.current = null;\n setPages({\n ...noPages,\n key,\n revision: refreshKey,\n status: \"error\",\n error: asError(failure),\n });\n setMore(null);\n },\n );\n }, delay);\n return () => {\n isCurrent = false;\n window.clearTimeout(timer);\n };\n }, [key, plan, refreshKey, search, pageSize, load, report, shown]);\n\n const loadMore = () => {\n const loadMorePage = load.current;\n const requestKey = pages.key;\n const { offset } = pages;\n if (!loadMorePage || requestKey === null || !canLoadMore) {\n return;\n }\n if (!hasMore || paging.current) {\n return;\n }\n const token = Symbol(\"load more\");\n const asked = refreshKey;\n paging.current = token;\n setMore({ token, status: \"loading\", error: null });\n // A reply counts only while it extends the rows on screen and no refresh began since.\n const applies = () =>\n paging.current === token &&\n shown.current.key === requestKey &&\n shown.current.offset === offset &&\n Object.is(revision.current, asked);\n const settle = (next: MoreRequest | null) => {\n if (paging.current === token) {\n paging.current = null;\n }\n setMore((previous) => (previous?.token === token ? next : previous));\n };\n void Promise.resolve()\n .then(() => loadMorePage({ offset, limit: pageSize }, { query: search }))\n .then(\n (page) => {\n if (applies()) {\n setPages((previous) => appendPage(previous, requestKey, offset, page));\n report.current(page.items, asked);\n }\n settle(null);\n },\n (failure: unknown) =>\n settle(applies() ? { token, status: \"error\", error: asError(failure) } : null),\n );\n };\n\n return {\n items: pages.items,\n total: pages.total,\n offset: pages.offset,\n hasMore,\n /** The `refreshKey` the shown rows were read at. */\n pageRevision: pages.revision,\n loading,\n searching,\n status,\n error: pages.error,\n retry: () => setRound((count) => count + 1),\n /** `isAvailable` is false while a search or refresh replaces the rows; `load` then does nothing. */\n more: { ...moreState(more, canLoadMore), load: loadMore },\n refresh: {\n status: refresh,\n error: refreshFailed ? (refreshFailure?.error ?? null) : null,\n retry: () => setRefreshFailure(null),\n },\n };\n}\n\nexport type PickerData = ReturnType<typeof usePickerData>;\n","import { useMemo, useState } from \"react\";\nimport { resultBlock } from \"./blocked\";\nimport { pickerCap } from \"./limit\";\nimport type { EntryItem, EntryPickerSource } from \"./types\";\nimport { usePickerData } from \"./use-picker-data\";\nimport { useSelectedItems } from \"./use-selected-items\";\n\nconst emptyItems: EntryItem[] = [];\n\ntype Restriction = (item: EntryItem) => EntryItem[\"disabledReason\"] | undefined;\n\ninterface PickerSessionOptions {\n isOpen: boolean;\n isDisabled: boolean;\n itemLabel: string;\n itemsLabel: string;\n /** Dismisses the dialog, as an edit returning false asks. */\n close: () => void;\n /**\n * The host's own reason a row can't be chosen, shown and enforced as the\n * row's `isDisabled` would be. Keep it stable; rows that already carry their\n * own restriction keep it.\n */\n restrict?: Restriction;\n}\n\nfunction restricted(items: EntryItem[], restrict: Restriction | undefined) {\n if (!restrict) {\n return items;\n }\n return items.map((item) => {\n const reason = item.isDisabled ? undefined : restrict(item);\n return reason ? { ...item, isDisabled: true, disabledReason: reason } : item;\n });\n}\n\n/**\n * Shared search, selected-item cache, paged reads and selection rules for field\n * and editor dialogs. `choice` is the one place a toggled row is checked, so no\n * host can bypass the rows' own blocking; `dialog` carries the PickerDialog\n * props every host passes the same way.\n */\nexport function usePickerSession(\n selected: string[],\n items: EntryItem[],\n source: Pick<\n EntryPickerSource,\n \"resolveItem\" | \"refreshKey\" | \"loadPage\" | \"pageSize\" | \"mode\" | \"max\" | \"onEditItem\"\n >,\n { isOpen, isDisabled, itemLabel, itemsLabel, close, restrict }: PickerSessionOptions,\n) {\n const [query, setQuery] = useState(\"\");\n const {\n resolveItem,\n refreshKey,\n loadPage,\n pageSize = 10,\n mode = \"multiple\",\n max,\n onEditItem,\n } = source;\n const selection = useSelectedItems(selected, items, resolveItem, refreshKey);\n const remote = usePickerData(loadPage, pageSize, query, isOpen, selection.remember, refreshKey);\n const isRemote = Boolean(loadPage);\n const filtered = useMemo(() => {\n const search = query.trim().toLowerCase();\n return isRemote\n ? emptyItems\n : items.filter(\n (item) =>\n !search ||\n [item.title, ...(item.keywords ?? [])].join(\" \").toLowerCase().includes(search),\n );\n }, [isRemote, items, query]);\n const shown = isRemote ? remote.items : filtered;\n const results = useMemo(() => restricted(shown, restrict), [shown, restrict]);\n const cap = pickerCap(mode, selected.length, max, { itemLabel, itemsLabel });\n const block = { isDisabled, searching: remote.searching, atMax: cap.atMax };\n const editItem = onEditItem\n ? (item: EntryItem) => {\n if (onEditItem(item) === false) {\n close();\n }\n }\n : undefined;\n return {\n selection,\n remote,\n isRemote,\n results,\n cap,\n block,\n editItem,\n /** The `refreshKey` a picked row was read at, for `selection.remember`. */\n revision: isRemote ? remote.pageRevision : refreshKey,\n /** The result `id` names, when the selection rules let it change now. */\n choice: (id: string) => {\n const item = results.find((result) => result.id === id);\n return item && !resultBlock(item, selected.includes(id), block) ? item : undefined;\n },\n dialog: {\n query,\n onQuery: setQuery,\n selected,\n results,\n cap,\n block,\n isRemote,\n pageSize,\n remote,\n onEdit: editItem,\n itemLabel,\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AC,KAAK,GAAG,CAAC,CAAC,YAAY,CAAC,CAAC,SAAS4E,CAAM,CAClF;CACN,GAAG;EAACsB;EAAUnF;EAAO8D;CAAK,CAAC,GACrB1B,IAAQ+C,IAAWR,EAAO,QAAQ4G,GAClCjE,IAAUjF,QAAc6I,GAAW9I,GAAO+I,CAAQ,GAAG,CAAC/I,GAAO+I,CAAQ,CAAC,GACtEnE,IAAMmB,GAAUJ,GAAM5H,EAAS,QAAQ6H,GAAK;EAAE;EAAW;CAAW,CAAC,GACrEjC,IAAQ;EAAE;EAAY,WAAWpB,EAAO;EAAW,OAAOqC,EAAI;CAAM,GACpEwE,IAAWC,KACZ,MAAoB;EACnB,AAAIA,EAAWxM,CAAI,MAAM,MACvByM,EAAM;CAEV,IACA,KAAA;CACJ,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EAEA,UAAUvG,IAAWR,EAAO,eAAehD;EAE3C,SAAS,MAAe;GACtB,IAAM1C,IAAOqI,EAAQ,MAAM,MAAWqE,EAAO,OAAOvL,CAAE;GACtD,OAAOnB,KAAQ,CAACsG,EAAYtG,GAAMkB,EAAS,SAASC,CAAE,GAAG2F,CAAK,IAAI9G,IAAO,KAAA;EAC3E;EACA,QAAQ;GACN;GACA,SAASoM;GACT;GACA;GACA;GACA;GACA;GACA;GACA;GACA,QAAQG;GACR;GACA;EACF;CACF;AACF"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=require("./Icon-CD3oeiNA.cjs"),t=require("../components/Button/index.cjs"),n=require("./overlayLayer-seJG-EFn.cjs"),r=require("../components/Badge/index.cjs"),i=require("./limit-BNo4dlRj.cjs"),a=require("../components/LimitReading/index.cjs"),o=require("../components/Modal/index.cjs"),s=require("./LoadState-BXLG-SkQ.cjs"),c=require("../components/SearchField/index.cjs"),l=require("../components/Choice/index.cjs");let u=require("react"),d=require("react/jsx-runtime");function f(e){return e.isDisabled?e.disabledReason:void 0}function p(e){return e.tone===`removed`}function m(e){return p(e)?void 0:f(e)}function h({item:t,reasonId:n}){let i=f(t);return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(`span`,{className:`ds-entry__thumb`,children:t.imageUrl?(0,d.jsx)(`img`,{src:t.imageUrl,alt:``,loading:`lazy`}):(0,d.jsx)(e.t,{name:`file-text`,size:20})}),(0,d.jsxs)(`span`,{className:`ds-entry__body`,children:[(0,d.jsx)(`span`,{className:`ds-entry__title`,"data-unavailable":t.isUnavailable||void 0,children:t.title}),t.metadata!=null&&(0,d.jsx)(`span`,{className:`ds-entry__meta`,children:t.metadata}),i&&(0,d.jsxs)(`span`,{id:n,className:`ds-entry__reason`,children:[(0,d.jsx)(r.Badge,{shape:`tag`,size:`sm`,children:i.label}),` `,(0,d.jsx)(`span`,{children:i.description})]})]})]})}function g({item:e,reasonId:t}){return p(e)?(0,d.jsxs)(`span`,{className:`ds-entry__removed`,children:[(0,d.jsx)(`strong`,{children:e.title}),` `,e.metadata??(0,d.jsx)(`code`,{children:e.id})]}):(0,d.jsx)(h,{item:e,reasonId:t})}function _({item:e}){return p(e)?(0,d.jsx)(r.Badge,{shape:`tag`,children:e.removedLabel??`Removed on save`}):null}function v({item:e,onEdit:n,isDisabled:r}){return!n||e.isUnavailable||e.isDisabled?null:(0,d.jsx)(t.Button,{variant:`simple`,size:`sm`,isIconOnly:!0,iconStart:`pencil`,"aria-label":`Edit ${e.title}`,isDisabled:r,onClick:()=>n(e)})}function y(e,t,n){return{id:e,title:t,metadata:n,isUnavailable:!0}}function b({selected:e,items:t,pageItems:n,known:r,failures:i,hasResolver:a,itemLabel:o}){let s=new Map(t.map(e=>[e.id,e])),c=new Map(n.map(e=>[e.id,e]));return e.map(e=>(s.get(e)??(r.has(e)?r.get(e):c.get(e)))||(r.has(e)?y(e,`${`${o.charAt(0).toUpperCase()}${o.slice(1)}`} no longer available`,`Replace or clear this selection.`):a?y(e,i.has(e)?`Couldn't load ${o}`:`Loading…`):{id:e,title:e}))}function x(e){return e instanceof Error?e:null}function S(e,t){if(!t.some(t=>e.has(t)))return e;let n=new Map(e);for(let e of t)n.delete(e);return n}function C(e,t,n){let r=n?t.flatMap(t=>{let r=n(t);return r?.item.id===t&&e.seeds.get(t)!==r?[r]:[]}):[];if(r.length===0)return e;let i=r.filter(t=>Object.is(t.revision,e.refreshKey)),a=r.filter(t=>!Object.is(t.revision,e.refreshKey)&&!e.known.has(t.item.id)&&!e.stale.has(t.item.id)),o=e=>e.map(e=>[e.item.id,e.item]);return{...e,seeds:new Map([...e.seeds,...r.map(e=>[e.item.id,e])]),known:i.length?new Map([...e.known,...o(i)]):e.known,stale:a.length?new Map([...e.stale,...o(a)]):e.stale,failures:S(e.failures,i.map(e=>e.item.id))}}function w(e,t){return e!==t&&(e.length!==t.length||t.some(t=>!e.includes(t)))}function T(e,t,n,r){let i=e;if(Object.is(i.refreshKey,n)||(i={...i,refreshKey:n,known:new Map,stale:new Map([...i.stale,...i.known]),failures:new Map}),w(i.selected,t)){let e=i.selected.filter(e=>!t.includes(e));i={...i,selected:t,known:S(i.known,e),stale:S(i.stale,e),failures:S(i.failures,e),seeds:S(i.seeds,e)}}return C(i,t,r)}function E(e,t,r,i,a){let o=n.u(r),s=n.u(e),[c,l]=(0,u.useState)(()=>C({refreshKey:i,selected:e,known:new Map,stale:new Map,failures:new Map,seeds:new Map},e,a)),d=T(c,e,i,a);d!==c&&l(d);let{known:f,stale:p,failures:m}=d,h=(0,u.useMemo)(()=>p.size===0?f:new Map([...p,...f]),[p,f]),g=(e,t,n=s.current)=>{let r=e.filter(e=>e!==void 0&&n.includes(e.id)).map(e=>[e.id,e]);r.length!==0&&l(e=>{if(Object.is(e.refreshKey,t))return{...e,known:new Map([...e.known,...r])};let n=r.filter(([t])=>!e.known.has(t)&&!e.stale.has(t));return n.length===0?e:{...e,stale:new Map([...e.stale,...n])}})},_=new Set(t.map(e=>e.id)),v=r?e.filter(e=>!_.has(e)&&!f.has(e)&&!m.has(e)):[],y=JSON.stringify(v),b=(0,u.useRef)({refreshKey:i,tokens:new Map});(0,u.useEffect)(()=>{let e=o.current;if(!e)return;let t=JSON.parse(y);Object.is(b.current.refreshKey,i)||(b.current={refreshKey:i,tokens:new Map});let{tokens:n}=b.current;for(let e of n.keys())t.includes(e)||n.delete(e);for(let r of t.filter(e=>!n.has(e))){let t=Symbol(r);n.set(r,t);let a=e=>{b.current.tokens.get(r)===t&&(b.current.tokens.delete(r),l(t=>Object.is(t.refreshKey,i)&&t.selected.includes(r)?e(t):t))};Promise.resolve().then(()=>e(r)).then(e=>a(t=>t.known.has(r)?t:{...t,known:new Map(t.known).set(r,e??null)}),e=>a(t=>({...t,failures:new Map(t.failures).set(r,x(e))})))}},[y,i,o]);let w=e.filter(e=>m.has(e)&&!f.has(e));return{known:h,failures:m,remember:g,status:v.length>0?`loading`:w.length>0?`error`:`ready`,error:w.length>0?m.get(w[0])??null:null,retry:()=>l(e=>({...e,failures:S(e.failures,w)}))}}function D(e,t,n,r){let i=s.n(t,n,r);return t!==`error`&&i.state!==`pending`?null:(0,d.jsx)(s.r,{title:e,error:i.error,onRetry:i.retry,retryState:i.state})}function O({query:e,itemLabel:t,itemsLabel:n,canCreate:r}){let i=e.trim();return(0,d.jsxs)(`div`,{className:`ds-entry-picker__no-results`,children:[(0,d.jsx)(`p`,{children:i?`No ${n} match “${i}”`:`No ${n} yet`}),i&&(0,d.jsxs)(`p`,{children:[`Try a different search.`,r?` Or create the ${t} you need.`:``]})]})}function k(e,t){let r=e.closest(`.ds-entry-picker__scroll`)??e.parentElement,i=Array.from(r?.querySelectorAll(`.ds-entry-picker__result`)??[]);for(let e of[...i.slice(t),...i.slice(0,t).reverse()]){let t=n.h(e)[0];if(t)return t}}function A(e){let t=(0,u.useRef)(null),r=(0,u.useRef)(null),{more:i,offset:a}=e;return(0,u.useEffect)(()=>{let e=r.current,a=t.current;e!==null&&i.status!==`loading`&&(r.current=null,a&&n.d(document.activeElement)&&(i.status===`error`?n.h(a)[0]:k(a,e))?.focus())},[i.status,a]),{pagingRef:t,load:()=>{r.current=t.current?.contains(document.activeElement)?a:null,i.load()}}}function j(e,t){let r=(0,u.useRef)(t);(0,u.useEffect)(()=>{if(r.current===t)return;r.current=t;let i=e.current;i&&n.d(document.activeElement)&&(n.h(i)[0]??k(i,1/0))?.focus()},[e,t])}function M({count:e,total:n,isRemote:r,pageSize:i,remote:a,itemsLabel:o}){let{more:s}=a,{pagingRef:c,load:l}=A(a),u=D(`Couldn't load more ${o}`,s.status,s.error,l);return j(c,u?`failure`:r&&a.hasMore?`more`:`none`),n===0?null:(0,d.jsxs)(`div`,{ref:c,className:`ds-entry-picker__paging`,children:[u??(r&&a.hasMore&&(0,d.jsxs)(t.Button,{isPending:s.status===`loading`,isFocusableWhenDisabled:!0,isDisabled:!s.isAvailable,onClick:l,children:[`Load `,Math.min(i,n-a.offset),` more`]})),(0,d.jsx)(`span`,{children:e<n?`Showing ${e} of ${n}`:`All ${e} shown`})]})}function N(e,t,{isDisabled:n,searching:r,atMax:i}){if(n||r)return`inactive`;if(e.isDisabled)return`restricted`;if(!t&&i)return`full`}function P({items:e,selected:t,block:n,onToggle:r,onEdit:i}){let a=(0,u.useId)(),o=`${a}-full`;return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(`span`,{id:o,hidden:!0,children:`The selection is full. Remove one to choose another.`}),(0,d.jsx)(`ul`,{className:`ds-entry-picker__results`,"data-searching":n.searching||void 0,children:e.map((e,s)=>{let c=t.includes(e.id),u=N(e,c,n),p=f(e)?`${a}-reason-${s}`:void 0;return(0,d.jsxs)(`li`,{className:`ds-entry-picker__result`,"data-selected":c||void 0,"data-blocked":u?!0:void 0,onClick:t=>{let n=t.target instanceof Element?t.target.closest(`button, input, label, a, select, textarea, summary, [tabindex]`):null;(!n||!t.currentTarget.contains(n))&&r(e.id)},children:[(0,d.jsx)(l.Checkbox,{checked:c,"aria-checked":c,"aria-label":`Select ${e.title}`,"aria-describedby":u===`full`?o:p,disabled:!!u,isFocusableWhenDisabled:u!==`inactive`,onChange:()=>r(e.id)}),(0,d.jsx)(`span`,{className:`ds-entry`,children:(0,d.jsx)(h,{item:e,reasonId:p})}),(0,d.jsx)(v,{item:e,onEdit:i,isDisabled:u===`inactive`})]},e.id)})})]})}function F(){let e=(0,u.useRef)(null),[t,n]=(0,u.useState)(!1);return{ref:e,scrolled:t,toTop:()=>{n(!1),e.current&&(e.current.scrollTop=0)},onScroll:e=>{n(e.currentTarget.scrollTop>0)}}}function I({isOpen:e,onClose:n,query:r,onQuery:i,selected:c,results:l,cap:u,block:f,isRemote:p,pageSize:m,remote:h,onToggle:g,onEdit:_,itemLabel:v,itemsLabel:y,addLabel:b,onCreate:x,isCreating:S,dialogTitle:C,dialogDescription:w,isDialogHidden:T}){let E=D(`Couldn't refresh ${y}`,h.refresh.status,h.refresh.error,h.refresh.retry);return(0,d.jsx)(o.Modal,{isOpen:e,isHidden:T,onClose:n,title:C??b,description:w??u.description,className:`ds-entry-picker__dialog`,footer:(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(`span`,{className:`ds-entry-picker__selection`,role:`status`,children:u.reading?(0,d.jsx)(a.LimitReading,{...u.reading,size:`lg`}):`${c.length} selected`}),(0,d.jsx)(t.Button,{variant:`primary`,onClick:n,children:`Done`})]}),children:(0,d.jsx)(L,{query:r,onQuery:i,itemsLabel:y,isSearching:h.loading,action:x&&(0,d.jsx)(t.Button,{variant:`primary`,isPending:S,isFocusableWhenDisabled:!0,iconStart:`plus`,isDisabled:f.isDisabled||u.atMax,onClick:x,children:`New ${v}`}),banner:E,isBusy:h.loading||h.more.status===`loading`||h.refresh.status===`loading`,children:(0,d.jsxs)(s.t,{status:h.status,errorTitle:`Couldn't load ${y}`,error:h.error,onRetry:h.retry,children:[(0,d.jsx)(P,{items:l,selected:c,block:f,onToggle:g,onEdit:_}),!h.searching&&l.length===0&&(0,d.jsx)(O,{query:r,itemLabel:v,itemsLabel:y,canCreate:!!x}),(0,d.jsx)(M,{count:l.length,total:p?h.total:l.length,isRemote:p,pageSize:m,remote:h,itemsLabel:y})]})})})}function L({query:e,onQuery:t,itemsLabel:n,isSearching:r,action:i,banner:a,isBusy:o,children:s}){let{ref:l,scrolled:u,onScroll:f,toTop:p}=F(),m=e=>{p(),t(e)};return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsxs)(`div`,{className:`ds-entry-picker__search`,"data-scrolled":u||void 0,children:[(0,d.jsx)(c.SearchField,{"aria-label":`Search ${n}`,value:e,isBusy:r,placeholder:`Search ${n}`,onChange:e=>m(e.target.value),onClear:()=>m(``)}),i]}),a&&(0,d.jsx)(`div`,{className:`ds-entry-picker__refresh`,children:a}),(0,d.jsx)(`div`,{className:`ds-entry-picker__scroll`,ref:l,onScroll:f,"aria-busy":o,children:s})]})}function R(e,t){return e===`single`||t===1}function z(e,t,n){return R(e,n)?{count:t,max:1,tone:`neutral`}:e===`multiple`&&n!==void 0?{count:t,max:n}:void 0}function B(e,t,n){return R(e,n)?void 0:t}function V(e,t,n,{itemLabel:r,itemsLabel:a}){let o=z(e,t,n),s=e===`multiple`&&o&&Number.isFinite(o.max)?o.max:void 0,c=`Choose as many ${a} as you need.`;return e===`single`||s===1?c=`Choose one ${r}.`:s!==void 0&&(c=`Choose up to ${s} ${a}.`),{limit:o,atMax:s!==void 0&&t>=s,description:c,reading:e===`multiple`&&i.r(o)?o:void 0}}var H=250;function U(e){return Array.from(new Map(e.map(e=>[e.id,e])).values())}var W={items:[],offset:0,total:0},G={...W,key:null,revision:void 0,status:`ready`,error:null};function K(e,t){let n=e?.status===`error`&&t;return{status:e?.status===`loading`?`loading`:n?`error`:`ready`,error:n?e.error??null:null,isAvailable:t}}function q(e,t){return{items:U([...e.items,...t.items]),offset:e.offset+t.items.length,total:t.items.length===0?Math.min(t.total,e.offset):t.total}}function J(e,t,n,r){return e.key!==t||e.offset!==n?e:{...e,...q(e,r)}}async function Y(e,t,n,r,i){let a=Math.max(1,Math.ceil(r/n)),o=await Promise.all(Array.from({length:a},(r,i)=>e({offset:i*n,limit:n},{query:t}))),s=W;for(let[e,t]of o.entries()){if(s.offset!==e*n)break;s=q(s,t)}for(;s.offset<r&&s.offset<s.total&&i();)s=q(s,await e({offset:s.offset,limit:n},{query:t}));return s}function X(e,t,n,r){let i=e!==null&&t.key===e,a=i&&Object.is(t.revision,n),o=e!==null&&!a&&(!i||t.status===`error`),s=o&&t.key!==null&&t.status===`ready`,c=o&&!s?`loading`:t.status===`error`?`error`:`ready`,l=t.status===`ready`&&t.offset<t.total,u=i&&!a&&t.status===`ready`,d=u&&r?.key===e&&Object.is(r.revision,n);return{loading:o,searching:s,status:c,hasMore:l,refresh:u?d?`error`:`loading`:`ready`,refreshFailed:d}}function Z(e,t,r,i,a,o){let s=n.u(e),c=n.u(a),l=n.u(o),[d,f]=(0,u.useState)(0),[p,m]=(0,u.useState)(G),[h,g]=(0,u.useState)(null),[_,v]=(0,u.useState)(null),[y,b]=(0,u.useState)(i);y!==i&&(b(i),i||(m(G),g(null),v(null),f(e=>e+1)));let S=r.trim(),C=e&&i?JSON.stringify([S,t,d]):null,w=n.u(p),T=(0,u.useRef)(null),E=(0,u.useRef)(S),{loading:D,searching:O,status:k,hasMore:A,refresh:j,refreshFailed:M}=X(C,p,o,_),N=!D&&j===`ready`,P=D?`load`:j===`loading`?`refresh`:null;(0,u.useEffect)(()=>{if(C===null)return;let e=P===`load`&&S!==E.current?H:0;if(E.current=S,P===null)return;let n=P===`refresh`?w.current.offset+(T.current?t:0):0,r=!0,i=window.setTimeout(()=>{let e=s.current;e&&Y(e,S,t,n,()=>r).then(e=>{r&&(T.current=null,m({...e,key:C,revision:o,status:`ready`,error:null}),g(null),v(null),c.current(e.items,o))},e=>{r&&(P===`refresh`?v({key:C,revision:o,error:x(e)}):(T.current=null,m({...G,key:C,revision:o,status:`error`,error:x(e)}),g(null)))})},e);return()=>{r=!1,window.clearTimeout(i)}},[C,P,o,S,t,s,c,w]);let F=()=>{let e=s.current,n=p.key,{offset:r}=p;if(!e||n===null||!N||!A||T.current)return;let i=Symbol(`load more`),a=o;T.current=i,g({token:i,status:`loading`,error:null});let u=()=>T.current===i&&w.current.key===n&&w.current.offset===r&&Object.is(l.current,a),d=e=>{T.current===i&&(T.current=null),g(t=>t?.token===i?e:t)};Promise.resolve().then(()=>e({offset:r,limit:t},{query:S})).then(e=>{u()&&(m(t=>J(t,n,r,e)),c.current(e.items,a)),d(null)},e=>d(u()?{token:i,status:`error`,error:x(e)}:null))};return{items:p.items,total:p.total,offset:p.offset,hasMore:A,pageRevision:p.revision,loading:D,searching:O,status:k,error:p.error,retry:()=>f(e=>e+1),more:{...K(h,N),load:F},refresh:{status:j,error:M?_?.error??null:null,retry:()=>v(null)}}}var Q=[];function $(e,t){return t?e.map(e=>{let n=e.isDisabled?void 0:t(e);return n?{...e,isDisabled:!0,disabledReason:n}:e}):e}function ee(e,t,n,{isOpen:r,isDisabled:i,itemLabel:a,itemsLabel:o,close:s,restrict:c}){let[l,d]=(0,u.useState)(``),{resolveItem:f,refreshKey:p,loadPage:m,pageSize:h=10,mode:g=`multiple`,max:_,onEditItem:v}=n,y=E(e,t,f,p),b=Z(m,h,l,r,y.remember,p),x=!!m,S=(0,u.useMemo)(()=>{let e=l.trim().toLowerCase();return x?Q:t.filter(t=>!e||[t.title,...t.keywords??[]].join(` `).toLowerCase().includes(e))},[x,t,l]),C=x?b.items:S,w=(0,u.useMemo)(()=>$(C,c),[C,c]),T=V(g,e.length,_,{itemLabel:a,itemsLabel:o}),D={isDisabled:i,searching:b.searching,atMax:T.atMax},O=v?e=>{v(e)===!1&&s()}:void 0;return{selection:y,remote:b,isRemote:x,results:w,cap:T,block:D,editItem:O,revision:x?b.pageRevision:p,choice:t=>{let n=w.find(e=>e.id===t);return n&&!N(n,e.includes(t),D)?n:void 0},dialog:{query:l,onQuery:d,selected:e,results:w,cap:T,block:D,isRemote:x,pageSize:h,remote:b,onEdit:O,itemLabel:a,itemsLabel:o}}}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return D}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return v}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return g}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return m}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return I}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return h}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return B}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return E}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return z}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return ee}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return _}});
|
|
2
|
+
//# sourceMappingURL=use-picker-session-C4FGinLN.cjs.map
|