@namroodinc/liquid-editorial 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/README.md +17 -7
  2. package/UPGRADING.md +70 -0
  3. package/dist/chunks/{Avatar-DPnrvkwd.cjs → Avatar-BY0dAItT.cjs} +2 -2
  4. package/dist/chunks/{Avatar-DPnrvkwd.cjs.map → Avatar-BY0dAItT.cjs.map} +1 -1
  5. package/dist/chunks/{Avatar-BK8IdL5W.js → Avatar-UjhjcHh5.js} +2 -2
  6. package/dist/chunks/{Avatar-BK8IdL5W.js.map → Avatar-UjhjcHh5.js.map} +1 -1
  7. package/dist/chunks/{CollectionView-DrszOUOt.cjs → CollectionView-CIJdNwcq.cjs} +2 -2
  8. package/dist/chunks/{CollectionView-DrszOUOt.cjs.map → CollectionView-CIJdNwcq.cjs.map} +1 -1
  9. package/dist/chunks/{CollectionView-B0ZJxkNK.js → CollectionView-JRNdXHti.js} +2 -2
  10. package/dist/chunks/{CollectionView-B0ZJxkNK.js.map → CollectionView-JRNdXHti.js.map} +1 -1
  11. package/dist/chunks/{ColourField-C39pcjkG.js → ColourField-BTj9NHgI.js} +146 -152
  12. package/dist/chunks/ColourField-BTj9NHgI.js.map +1 -0
  13. package/dist/chunks/ColourField-DuoVeXjG.cjs +2 -0
  14. package/dist/chunks/ColourField-DuoVeXjG.cjs.map +1 -0
  15. package/dist/chunks/{DatePicker-Dpvfomrm.cjs → DatePicker-BYpGsfL4.cjs} +2 -2
  16. package/dist/chunks/{DatePicker-Dpvfomrm.cjs.map → DatePicker-BYpGsfL4.cjs.map} +1 -1
  17. package/dist/chunks/{DatePicker-DDc1nDTb.js → DatePicker-Cb5WspIC.js} +21 -21
  18. package/dist/chunks/{DatePicker-DDc1nDTb.js.map → DatePicker-Cb5WspIC.js.map} +1 -1
  19. package/dist/chunks/{Drawer-C3mWT9Kh.js → Drawer-Ck5XKT_V.js} +3 -3
  20. package/dist/chunks/{Drawer-C3mWT9Kh.js.map → Drawer-Ck5XKT_V.js.map} +1 -1
  21. package/dist/chunks/{Drawer-DTKZptua.cjs → Drawer-DdIH9jpe.cjs} +2 -2
  22. package/dist/chunks/{Drawer-DTKZptua.cjs.map → Drawer-DdIH9jpe.cjs.map} +1 -1
  23. package/dist/chunks/{EntryPicker-CgWbgWnc.cjs → EntryPicker-CCCoJxbd.cjs} +2 -2
  24. package/dist/chunks/{EntryPicker-CgWbgWnc.cjs.map → EntryPicker-CCCoJxbd.cjs.map} +1 -1
  25. package/dist/chunks/{EntryPicker-DlEsVCvA.js → EntryPicker-DLCP4S-q.js} +3 -3
  26. package/dist/chunks/{EntryPicker-DlEsVCvA.js.map → EntryPicker-DLCP4S-q.js.map} +1 -1
  27. package/dist/chunks/{FormEditor-iACd0El-.cjs → FormEditor-ArvjKtJJ.cjs} +2 -2
  28. package/dist/chunks/{FormEditor-iACd0El-.cjs.map → FormEditor-ArvjKtJJ.cjs.map} +1 -1
  29. package/dist/chunks/{FormEditor-CLLOHKiO.js → FormEditor-DnNBv9Xf.js} +16 -16
  30. package/dist/chunks/{FormEditor-CLLOHKiO.js.map → FormEditor-DnNBv9Xf.js.map} +1 -1
  31. package/dist/chunks/{Message-CyLq9ef-.js → Message-C73sJfdo.js} +4 -8
  32. package/dist/chunks/{Message-CyLq9ef-.js.map → Message-C73sJfdo.js.map} +1 -1
  33. package/dist/chunks/{Message-D3b8HDhm.cjs → Message-CIKSTXp8.cjs} +2 -2
  34. package/dist/chunks/{Message-D3b8HDhm.cjs.map → Message-CIKSTXp8.cjs.map} +1 -1
  35. package/dist/chunks/RichTextEditor--kMao88d.cjs +2 -0
  36. package/dist/chunks/RichTextEditor--kMao88d.cjs.map +1 -0
  37. package/dist/chunks/{RichTextEditor-B0P53GFt.js → RichTextEditor-CvbboqJY.js} +391 -374
  38. package/dist/chunks/RichTextEditor-CvbboqJY.js.map +1 -0
  39. package/dist/chunks/{dialogLabel-D18maX-p.js → dialogLabel-DT7rCr3_.js} +19 -19
  40. package/dist/chunks/{dialogLabel-D18maX-p.js.map → dialogLabel-DT7rCr3_.js.map} +1 -1
  41. package/dist/chunks/{dialogLabel-2HRYMHbF.cjs → dialogLabel-_-MTckE_.cjs} +2 -2
  42. package/dist/chunks/{dialogLabel-2HRYMHbF.cjs.map → dialogLabel-_-MTckE_.cjs.map} +1 -1
  43. package/dist/chunks/overlayLayer-iGhuAByk.cjs +2 -0
  44. package/dist/chunks/overlayLayer-iGhuAByk.cjs.map +1 -0
  45. package/dist/chunks/{overlayLayer-IuoPVwTO.js → overlayLayer-lU4iWSjO.js} +32 -28
  46. package/dist/chunks/overlayLayer-lU4iWSjO.js.map +1 -0
  47. package/dist/chunks/{group-7Z_xRlQx.js → style-7Z_xRlQx.js} +1 -1
  48. package/dist/chunks/{group-7Z_xRlQx.js.map → style-7Z_xRlQx.js.map} +1 -1
  49. package/dist/chunks/{group-nulIa2_8.cjs → style-nulIa2_8.cjs} +1 -1
  50. package/dist/chunks/{group-nulIa2_8.cjs.map → style-nulIa2_8.cjs.map} +1 -1
  51. package/dist/chunks/{use-picker-session-DbfOJstX.cjs → use-picker-session-Bue5MJHQ.cjs} +2 -2
  52. package/dist/chunks/{use-picker-session-DbfOJstX.cjs.map → use-picker-session-Bue5MJHQ.cjs.map} +1 -1
  53. package/dist/chunks/{use-picker-session-BnMxbGAZ.js → use-picker-session-DUO4G8Cs.js} +2 -2
  54. package/dist/chunks/{use-picker-session-BnMxbGAZ.js.map → use-picker-session-DUO4G8Cs.js.map} +1 -1
  55. package/dist/chunks/{useTooltip-BXAvQwt4.cjs → useTooltip-C7ON4nkV.cjs} +2 -2
  56. package/dist/chunks/{useTooltip-BXAvQwt4.cjs.map → useTooltip-C7ON4nkV.cjs.map} +1 -1
  57. package/dist/chunks/{useTooltip-BrC7FdeH.js → useTooltip-DnJEFBLg.js} +2 -2
  58. package/dist/chunks/{useTooltip-BrC7FdeH.js.map → useTooltip-DnJEFBLg.js.map} +1 -1
  59. package/dist/components/AppShell/index.cjs +1 -1
  60. package/dist/components/AppShell/index.js +1 -1
  61. package/dist/components/Avatar/index.cjs +1 -1
  62. package/dist/components/Avatar/index.js +1 -1
  63. package/dist/components/Badge/style.css +9 -9
  64. package/dist/components/Banner/index.cjs +1 -1
  65. package/dist/components/Banner/index.js +1 -1
  66. package/dist/components/Board/style.css +3 -3
  67. package/dist/components/Button/style.css +4 -8
  68. package/dist/components/Choice/index.cjs +1 -1
  69. package/dist/components/Choice/index.cjs.map +1 -1
  70. package/dist/components/Choice/index.js +3 -3
  71. package/dist/components/Choice/index.js.map +1 -1
  72. package/dist/components/Choice/style.css +29 -18
  73. package/dist/components/CollectionView/index.cjs +1 -1
  74. package/dist/components/CollectionView/index.js +1 -1
  75. package/dist/components/ColourField/index.cjs +1 -1
  76. package/dist/components/ColourField/index.d.cts.map +1 -1
  77. package/dist/components/ColourField/index.d.ts.map +1 -1
  78. package/dist/components/ColourField/index.js +1 -1
  79. package/dist/components/ColourField/style.css +4 -4
  80. package/dist/components/DatePicker/index.cjs +1 -1
  81. package/dist/components/DatePicker/index.js +1 -1
  82. package/dist/components/Drawer/index.cjs +1 -1
  83. package/dist/components/Drawer/index.js +1 -1
  84. package/dist/components/Drawer/style.css +2 -4
  85. package/dist/components/EditLayout/index.cjs +1 -1
  86. package/dist/components/EditLayout/index.js +3 -3
  87. package/dist/components/EditLayout/style.css +1 -7
  88. package/dist/components/EntryPicker/index.cjs +1 -1
  89. package/dist/components/EntryPicker/index.js +1 -1
  90. package/dist/components/EntryPicker/style.css +3 -1
  91. package/dist/components/Field/style.css +1 -1
  92. package/dist/components/FormEditor/README.md +26 -33
  93. package/dist/components/FormEditor/index.cjs +1 -1
  94. package/dist/components/FormEditor/index.js +1 -1
  95. package/dist/components/FormEditor/style.css +1 -0
  96. package/dist/components/LimitReading/style.css +1 -1
  97. package/dist/components/Menu/index.cjs +1 -1
  98. package/dist/components/Menu/index.js +1 -1
  99. package/dist/components/Menu/style.css +3 -2
  100. package/dist/components/Modal/index.cjs +1 -1
  101. package/dist/components/Modal/index.js +2 -2
  102. package/dist/components/Modal/style.css +1 -3
  103. package/dist/components/Popover/index.cjs +1 -1
  104. package/dist/components/Popover/index.cjs.map +1 -1
  105. package/dist/components/Popover/index.d.cts.map +1 -1
  106. package/dist/components/Popover/index.d.ts.map +1 -1
  107. package/dist/components/Popover/index.js +58 -55
  108. package/dist/components/Popover/index.js.map +1 -1
  109. package/dist/components/RichTextEditor/index.cjs +1 -1
  110. package/dist/components/RichTextEditor/index.d.cts.map +1 -1
  111. package/dist/components/RichTextEditor/index.d.ts.map +1 -1
  112. package/dist/components/RichTextEditor/index.js +1 -1
  113. package/dist/components/RichTextEditor/storyblock-view.d.cts.map +1 -1
  114. package/dist/components/RichTextEditor/storyblock-view.d.ts.map +1 -1
  115. package/dist/components/RichTextEditor/style.css +91 -60
  116. package/dist/components/Select/index.cjs +1 -1
  117. package/dist/components/Select/index.js +1 -1
  118. package/dist/components/SelectionCard/index.cjs +1 -1
  119. package/dist/components/SelectionCard/index.cjs.map +1 -1
  120. package/dist/components/SelectionCard/index.d.cts.map +1 -1
  121. package/dist/components/SelectionCard/index.d.ts.map +1 -1
  122. package/dist/components/SelectionCard/index.js +2 -2
  123. package/dist/components/SelectionCard/index.js.map +1 -1
  124. package/dist/components/SelectionCard/style.css +20 -65
  125. package/dist/components/Skeleton/style.css +1 -1
  126. package/dist/components/Slider/style.css +12 -23
  127. package/dist/components/Switch/index.cjs +1 -1
  128. package/dist/components/Switch/index.cjs.map +1 -1
  129. package/dist/components/Switch/index.d.cts.map +1 -1
  130. package/dist/components/Switch/index.d.ts.map +1 -1
  131. package/dist/components/Switch/index.js +2 -1
  132. package/dist/components/Switch/index.js.map +1 -1
  133. package/dist/components/Switch/style.css +14 -2
  134. package/dist/components/TagsInput/style.css +3 -21
  135. package/dist/components/Time/index.cjs +1 -1
  136. package/dist/components/Time/index.js +1 -1
  137. package/dist/components/Toast/index.cjs +1 -1
  138. package/dist/components/Toast/index.js +1 -1
  139. package/dist/elements.css +2 -1
  140. package/dist/index.cjs +1 -1
  141. package/dist/index.js +29 -29
  142. package/dist/internal/dialogFocus.d.cts +2 -0
  143. package/dist/internal/dialogFocus.d.cts.map +1 -1
  144. package/dist/internal/dialogFocus.d.ts +2 -0
  145. package/dist/internal/dialogFocus.d.ts.map +1 -1
  146. package/dist/message.css +5 -3
  147. package/dist/tokens.css +83 -309
  148. package/package.json +1 -1
  149. package/dist/chunks/ColourField-BdobU76j.cjs +0 -2
  150. package/dist/chunks/ColourField-BdobU76j.cjs.map +0 -1
  151. package/dist/chunks/ColourField-C39pcjkG.js.map +0 -1
  152. package/dist/chunks/RichTextEditor-B0P53GFt.js.map +0 -1
  153. package/dist/chunks/RichTextEditor-Wu_yjvD7.cjs +0 -2
  154. package/dist/chunks/RichTextEditor-Wu_yjvD7.cjs.map +0 -1
  155. package/dist/chunks/overlayLayer-IuoPVwTO.js.map +0 -1
  156. package/dist/chunks/overlayLayer-seJG-EFn.cjs +0 -2
  157. package/dist/chunks/overlayLayer-seJG-EFn.cjs.map +0 -1
  158. package/dist/components/ColourField/focus.d.cts +0 -3
  159. package/dist/components/ColourField/focus.d.cts.map +0 -1
  160. package/dist/components/ColourField/focus.d.ts +0 -3
  161. package/dist/components/ColourField/focus.d.ts.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"RichTextEditor-CvbboqJY.js","names":["_jsx","Node","noItems","_Fragment","Icon","mergeRefs","cannotHoldFocus","focusAfterField","tabbableControls","focusNearest","PortalScopeContext","useLatest","moveHost","useMovableHost","useIsomorphicLayoutEffect","useLoadError","PickerDialog","EntryRow","useSelectedItems","chosenItems","usePickerSession","Fragment$1","Node$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","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","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","open","setOpen","hasFocus","setHasFocus","trigger","panel","panelId","visible","useOverlayOpen","isLocked","name","useEffect","dismissOutside","target","close","popup","controls","boundary","relatedTarget","isSelected","Popover","ButtonGroup","option","align","onAlign","onEdit","canReplace","onReplace","missing","MenuSeparator","onRemove","StoryblockBody","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","offered","resolve","edit","EmbedPicker","picker","action","itemLabel","useEmbeds","setSession","sessionIds","bookmark","picks","pickCount","setPickCount","sessionSource","sources","active","latest","current","appendedTransactions","origin","available","now","isReadOnly","commit","replacing","previous","chain","count","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","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 useId,\n useMemo,\n useRef,\n useState,\n type KeyboardEvent,\n type MouseEvent,\n} from \"react\";\nimport { NodeViewWrapper, type NodeViewProps } from \"@tiptap/react\";\nimport { focusAfterField, tabbableControls } from \"../../internal/dialogFocus\";\nimport { useOverlayOpen } from \"../../internal/overlayLayer\";\nimport { Button } from \"../Button\";\nimport { ButtonGroup } from \"../ButtonGroup\";\nimport { Badge } from \"../Badge\";\nimport { Icon } from \"../Icon\";\nimport { MenuSeparator } from \"../Menu\";\nimport { Popover } from \"../Popover\";\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: \"Left\" },\n { align: \"full\", icon: \"align-justify\", label: \"Full\" },\n { align: \"right\", icon: \"align-right\", label: \"Right\" },\n] as const;\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/** A selected block has one Tab stop, with the editing actions in its popover. */\nfunction StoryblockBar({\n kind,\n name,\n align,\n isSelected,\n isLocked,\n missing,\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 isLocked: boolean;\n missing: boolean;\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 [open, setOpen] = useState(false);\n const [hasFocus, setHasFocus] = useState(false);\n const trigger = useRef<HTMLButtonElement>(null);\n const panel = useRef<HTMLDivElement>(null);\n const panelId = useId();\n const visible = useOverlayOpen(open) && !isLocked;\n const label = `Block actions for ${name}`;\n if (open && isLocked) {\n setOpen(false);\n }\n\n useEffect(() => {\n if (!visible) {\n return;\n }\n panel.current?.querySelector<HTMLElement>('[aria-pressed=\"true\"]')?.focus({\n preventScroll: true,\n });\n\n const dismissOutside = (event: globalThis.MouseEvent) => {\n const target = event.target;\n if (\n target instanceof Node &&\n !trigger.current?.contains(target) &&\n !panel.current?.contains(target)\n ) {\n setOpen(false);\n }\n };\n document.addEventListener(\"mousedown\", dismissOutside);\n return () => document.removeEventListener(\"mousedown\", dismissOutside);\n }, [visible]);\n\n const close = () => {\n setOpen(false);\n trigger.current?.focus({ preventScroll: true });\n };\n\n const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {\n const popup = panel.current;\n if (!visible || !popup) {\n return;\n }\n if (event.key === \"Escape\" && !event.nativeEvent.isComposing) {\n event.preventDefault();\n event.stopPropagation();\n close();\n return;\n }\n if (event.key !== \"Tab\" || !(event.target instanceof Node) || !popup.contains(event.target)) {\n return;\n }\n const controls = tabbableControls(popup);\n const boundary = event.shiftKey ? controls[0] : controls.at(-1);\n if (event.target === popup && !event.shiftKey) {\n event.preventDefault();\n controls[0]?.focus({ preventScroll: true });\n } else if (event.target === boundary || event.target === popup) {\n event.preventDefault();\n if (event.shiftKey) {\n close();\n } else {\n setOpen(false);\n focusAfterField(event.currentTarget);\n }\n }\n };\n\n return (\n // Not a toolbar: the bar holds one control, which carries the block's name.\n // Key presses in the portalled popover reach this handler through React.\n <div\n className=\"ds-storyblock__bar ds-field-surface\"\n onKeyDown={onKeyDown}\n onBlur={({ relatedTarget }) => {\n if (\n visible &&\n relatedTarget &&\n relatedTarget !== trigger.current &&\n !panel.current?.contains(relatedTarget)\n ) {\n setOpen(false);\n }\n }}\n >\n <StoryblockHandle\n kind={kind}\n isMovable={!isLocked}\n onSelect={onSelect}\n />\n <Button\n ref={trigger}\n variant={visible ? \"active\" : \"simple\"}\n size=\"sm\"\n isIconOnly\n iconStart=\"more-horizontal\"\n isDisabled={isLocked}\n tabIndex={!isLocked && (isSelected || hasFocus || visible) ? 0 : -1}\n aria-label={label}\n aria-haspopup=\"dialog\"\n aria-expanded={visible}\n aria-controls={visible ? panelId : undefined}\n onFocus={() => setHasFocus(true)}\n onBlur={() => setHasFocus(false)}\n onClick={() => (visible ? close() : setOpen(true))}\n />\n <Popover\n anchorRef={trigger}\n panelRef={panel}\n isOpen={visible}\n align=\"end\"\n role=\"dialog\"\n tabIndex={-1}\n aria-label={label}\n id={panelId}\n className=\"ds-storyblock__popover ds-surface-raised ds-field-surface\"\n >\n <div className=\"ds-storyblock__popover-content\">\n <div className=\"ds-storyblock__popover-label\">Alignment</div>\n <ButtonGroup\n className=\"ds-storyblock__alignment\"\n aria-label=\"Alignment\"\n >\n {alignments.map((option) => (\n <Button\n key={option.align}\n size=\"sm\"\n iconStart={option.icon}\n aria-pressed={align === option.align}\n variant={align === option.align ? \"primary\" : \"neutral\"}\n onClick={() => onAlign(option.align)}\n >\n {option.label}\n </Button>\n ))}\n </ButtonGroup>\n {onEdit && (\n <Button\n className=\"ds-storyblock__action\"\n variant=\"simple\"\n size=\"sm\"\n iconStart=\"pencil\"\n onClick={() => {\n close();\n onEdit();\n }}\n >\n Edit {kind}\n </Button>\n )}\n {canReplace.isShown && (\n <Button\n className=\"ds-storyblock__action\"\n variant=\"simple\"\n size=\"sm\"\n iconStart=\"rotate-cw\"\n isDisabled={!canReplace.isEnabled}\n onClick={() => {\n close();\n onReplace();\n }}\n >\n {missing ? `Choose another ${kind}…` : \"Replace…\"}\n </Button>\n )}\n <MenuSeparator />\n <Button\n className=\"ds-storyblock__action\"\n variant=\"danger\"\n size=\"sm\"\n iconStart=\"trash\"\n onClick={() => {\n setOpen(false);\n onRemove();\n }}\n >\n Remove from field\n </Button>\n </div>\n </Popover>\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;\n // A portal bubbles through the node view in React, but its controls sit outside the editor.\n if (!(target instanceof Element) || !event.currentTarget.contains(target)) {\n return;\n }\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 ds-field-surface\"\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 ds-field-surface\">\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 missing={missing}\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 ? \"primary\" : \"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 ds-field-surface\"\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] ? \"primary\" : \"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 ? \"primary\" : \"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 data-invalid={invalid || 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-expanded={expansion.expanded || undefined}\n data-focused={isFocused || undefined}\n data-disabled={disabled || undefined}\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 ds-field-surface\"\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,SAASuB,GAAqB,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,IAAOZ,EAAe,cAAc,GACpC,CAACiB,GAAUC,KAAeC,EAAS,EAAK,GACxC,CAACC,GAAcC,KAAmBF,EAAS,CAAC,GA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BAAAtD,IAAA,EAAA,UAAA,CACE,kBAACyP,IAAD;IACU;IACD;IACG;IACH;IACO;IACJ;IACV,eAAea,EAAU;IACzB,cAAcyC,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,KAAUkQ,KAAiB,CAAClP,KAC3B,kBAACkM,IAAD;IACU;IACR,WAAWgD;IACX,SAASE;GACV,CAAA,CAEQ;;CACQ,CAAA;AAE3B,CACF"}
@@ -1,4 +1,4 @@
1
- import { d as e, f as t, g as n, h as r, p as i, u as a } from "./overlayLayer-IuoPVwTO.js";
1
+ import { _ as e, d as t, g as n, m as r, p as i, u as a } from "./overlayLayer-lU4iWSjO.js";
2
2
  import { t as o } from "./isComposing-8bRWyiLF.js";
3
3
  import { useEffect as s, useInsertionEffect as c, useRef as l, useState as u, useSyncExternalStore as d } from "react";
4
4
  //#region src/internal/movableHost.ts
@@ -15,9 +15,9 @@ function m(e, t) {
15
15
  function h(e, t, n = null) {
16
16
  return t ? e.parentNode !== t && (g(e, t, null, n), !0) : (e.remove(), !1);
17
17
  }
18
- function g(t, n, r, i = null) {
19
- let a = document.activeElement, o = a && t.contains(a) ? a : i, s = o instanceof HTMLElement && t.contains(o) && (o === a || e(a));
20
- n.insertBefore(t, r), s && o.focus({ preventScroll: !0 });
18
+ function g(e, n, r, i = null) {
19
+ let a = document.activeElement, o = a && e.contains(a) ? a : i, s = o instanceof HTMLElement && e.contains(o) && (o === a || t(a));
20
+ n.insertBefore(e, r), s && o.focus({ preventScroll: !0 });
21
21
  }
22
22
  //#endregion
23
23
  //#region src/internal/useDialogPortal.ts
@@ -105,19 +105,19 @@ function D(e, t) {
105
105
  r.top < e.top ? n.scrollTop -= e.top - r.top : r.bottom > e.bottom && (n.scrollTop += Math.min(r.bottom - e.bottom, r.top - e.top));
106
106
  }
107
107
  }
108
- function O(t, n, a, o) {
109
- n && t.contains(n) && !e(n) && n.focus({ preventScroll: !0 }), n && document.activeElement === n ? D(t, n) : i(t, document.activeElement) || (a?.() ?? r(t)[0] ?? t).focus(o);
108
+ function O(e, i, a, o) {
109
+ i && e.contains(i) && !t(i) && i.focus({ preventScroll: !0 }), i && document.activeElement === i ? D(e, i) : r(e, document.activeElement) || (a?.() ?? n(e)[0] ?? e).focus(o);
110
110
  }
111
- function k({ isOpen: r, isActive: c = !0, layer: d = 60, panelRef: f, onClose: p, initialFocus: m, preventScroll: h = !1, container: g }) {
111
+ function k({ isOpen: n, isActive: c = !0, layer: d = 60, panelRef: f, onClose: p, initialFocus: m, preventScroll: h = !1, container: g }) {
112
112
  let _ = a({
113
113
  onClose: p,
114
114
  initialFocus: m
115
115
  }), [v, y] = u(null), b = l(null);
116
- return v !== null !== r && y(r ? {
116
+ return v !== null !== n && y(n ? {
117
117
  opener: typeof document > "u" ? null : document.activeElement,
118
118
  order: S()
119
119
  } : null), s(() => {
120
- if (!r || !c || !v) return;
120
+ if (!n || !c || !v) return;
121
121
  let a = { preventScroll: h }, s = f.current, l = C(d, v.order), u = (e) => {
122
122
  e instanceof HTMLElement && (b.current = {
123
123
  order: v.order,
@@ -126,25 +126,25 @@ function k({ isOpen: r, isActive: c = !0, layer: d = 60, panelRef: f, onClose: p
126
126
  }, p = ({ target: e }) => u(e);
127
127
  s?.addEventListener("focusin", p);
128
128
  let m = document.activeElement;
129
- if (l.isTopmost() && s && !i(s, m)) {
129
+ if (l.isTopmost() && s && !r(s, m)) {
130
130
  let e = b.current;
131
131
  O(s, e?.order === v.order ? e.element : void 0, _.current.initialFocus, a);
132
132
  } else s?.contains(m) && u(m);
133
- let g = (e) => {
133
+ let g = (t) => {
134
134
  if (l.isTopmost()) {
135
- if (e.key === "Escape") {
136
- if (e.defaultPrevented || o(e)) return;
137
- e.preventDefault(), _.current.onClose();
138
- } else n(e, f.current);
135
+ if (t.key === "Escape") {
136
+ if (t.defaultPrevented || o(t)) return;
137
+ t.preventDefault(), _.current.onClose();
138
+ } else e(t, f.current);
139
139
  }
140
140
  };
141
141
  window.addEventListener("keydown", g);
142
142
  let y = E();
143
143
  return () => {
144
- s?.removeEventListener("focusin", p), window.removeEventListener("keydown", g), l.close(), y(), e(document.activeElement) && t(v.opener, a);
144
+ s?.removeEventListener("focusin", p), window.removeEventListener("keydown", g), l.close(), y(), t(document.activeElement) && i(v.opener, a);
145
145
  };
146
146
  }, [
147
- r,
147
+ n,
148
148
  c,
149
149
  d,
150
150
  v,
@@ -154,7 +154,7 @@ function k({ isOpen: r, isActive: c = !0, layer: d = 60, panelRef: f, onClose: p
154
154
  _
155
155
  ]), {
156
156
  onScrimMouseDown: (e) => {
157
- r && c && e.target === e.currentTarget && (e.preventDefault(), _.current.onClose());
157
+ n && c && e.target === e.currentTarget && (e.preventDefault(), _.current.onClose());
158
158
  },
159
159
  order: v?.order
160
160
  };
@@ -173,4 +173,4 @@ function A(e, t, n, r, i) {
173
173
  //#endregion
174
174
  export { h as a, f as i, k as n, m as o, y as r, A as t };
175
175
 
176
- //# sourceMappingURL=dialogLabel-D18maX-p.js.map
176
+ //# sourceMappingURL=dialogLabel-DT7rCr3_.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"dialogLabel-D18maX-p.js","names":["cannotHoldFocus","focusNearest","trapTabFocus","tabbableControls","panelHoldsFocus","useLatest","isComposing","createMovableHost","host","className","style","subscribe","useMovableHost","useState","hydrated","useSyncExternalStore","useInsertionEffect","moveHost","slot","insertHost","lastFocused","active","focused","refocus","before","ranks","placement","others","parent","child","isLater","other","rank","useDialogPortal","setRank","order","isPresent","container","inPlace","stack","openings","nextDialogOrder","openDialog","entry","layer","locks","previous","lockBodyScroll","body","width","documentElement","scrollbar","padding","released","revealInPanel","area","control","panel","view","box","focusPanel","initialFocus","options","useModalDialog","latest","opening","setOpening","useRef","isOpen","useEffect","isActive","focusOptions","panelRef","dialog","remember","element","rememberFocus","target","onKeyDown","event","unlockScroll","preventScroll","dialogAttributes","props","titleId","hasDescription","descriptionId"],"sources":["../../src/internal/movableHost.ts","../../src/internal/useDialogPortal.ts","../../src/internal/dialogStack.ts","../../src/internal/lockBodyScroll.ts","../../src/internal/useModalDialog.ts","../../src/internal/dialogLabel.ts"],"sourcesContent":["import { useInsertionEffect, useState, useSyncExternalStore } from \"react\";\nimport { cannotHoldFocus } from \"./dialogFocus\";\n\n/**\n * A detached element for portal content that moves between slots, so the tree\n * rendered into it never remounts. Null on the server.\n */\nexport function createMovableHost(className: string, style: Partial<CSSStyleDeclaration> = {}) {\n if (typeof document === \"undefined\") {\n return null;\n }\n const host = document.createElement(\"div\");\n host.className = className;\n Object.assign(host.style, style);\n return host;\n}\n\nconst subscribe = () => () => {};\n\n/**\n * A movable host for content that is also server rendered. It is null on the\n * server and while hydrating, so the first client render can match inline\n * server markup; client-only renders get the host on their first render.\n */\nexport function useMovableHost(className: string, style?: Partial<CSSStyleDeclaration>) {\n const [host] = useState(() => createMovableHost(className, style));\n const hydrated = useSyncExternalStore(\n subscribe,\n () => true,\n () => false,\n );\n // An insertion effect, which Strict Mode never replays: replaying a passive\n // cleanup would detach a host that an insertion effect placed.\n useInsertionEffect(() => () => host?.remove(), [host]);\n return hydrated ? host : null;\n}\n\n/**\n * Moves `host` into `slot`, or detaches it when there is no slot. A host already\n * in place is left alone: re-inserting it would reset scroll positions and drop\n * focus and the text selection. Returns whether the host moved.\n */\nexport function moveHost(\n host: HTMLElement,\n slot: Element | null,\n lastFocused: Element | null = null,\n) {\n if (!slot) {\n host.remove();\n return false;\n }\n if (host.parentNode === slot) {\n return false;\n }\n insertHost(host, slot, null, lastFocused);\n return true;\n}\n\n/**\n * Inserts `host` into `slot` before `before`, or at its end. Moving drops focus,\n * so the element inside the host that had it (or `lastFocused`, when an earlier\n * removal already dropped it) gets it back.\n */\nexport function insertHost(\n host: HTMLElement,\n slot: Element,\n before: Node | null,\n lastFocused: Element | null = null,\n) {\n const active = document.activeElement;\n const focused = active && host.contains(active) ? active : lastFocused;\n const refocus =\n focused instanceof HTMLElement &&\n host.contains(focused) &&\n (focused === active || cannotHoldFocus(active));\n slot.insertBefore(host, before);\n if (refocus) {\n focused.focus({ preventScroll: true });\n }\n}\n","import { useInsertionEffect, useState } from \"react\";\nimport { insertHost, useMovableHost } from \"./movableHost\";\n\n/** The opening order of each dialog's portal host. */\nconst ranks = new WeakMap<Element, number>();\n\n/**\n * Where `host` belongs among the other dialog hosts in `parent`: before the\n * first one opened later. It is in place when every host opened earlier comes\n * before it and every one opened later after it, whatever else lies between.\n */\nfunction placement(host: Element, parent: Element, rank: number) {\n const others = Array.from(parent.children).filter((child) => child !== host && ranks.has(child));\n const isLater = (other: Element) => (ranks.get(other) ?? 0) > rank;\n const inPlace =\n host.parentNode === parent &&\n others.every(\n (other) =>\n isLater(other) ===\n Boolean(host.compareDocumentPosition(other) & Node.DOCUMENT_POSITION_FOLLOWING),\n );\n return { inPlace, before: others.find(isLater) ?? null };\n}\n\n/**\n * A portal host that paints dialogs in opening order, as the dialog stack ranks\n * them, including a nested dialog that opens in the same commit as its parent\n * (React inserts that one's portal first). The host moves only when its order\n * is wrong, keeping focus, so a reopened dialog keeps its scroll and focus.\n * Null on the server and while hydrating.\n */\nexport function useDialogPortal(\n order: number | undefined,\n isPresent: boolean,\n container?: HTMLElement | null,\n) {\n // Kept through a closing transition, when the dialog no longer has an order.\n const [rank, setRank] = useState(order ?? 0);\n if (order !== undefined && order !== rank) {\n setRank(order);\n }\n // Contents only, so a contained drawer's container lays out the frame itself.\n const host = useMovableHost(\"ds-dialog-host\", { display: \"contents\" });\n // Before layout effects, so content measures and focuses inside the document.\n useInsertionEffect(() => {\n if (!host) {\n return;\n }\n if (!isPresent) {\n host.remove();\n return;\n }\n ranks.set(host, rank);\n const parent = container ?? document.body;\n const { inPlace, before } = placement(host, parent, rank);\n if (!inPlace) {\n insertHost(host, parent, before);\n }\n }, [host, rank, isPresent, container]);\n return host;\n}\n","interface Entry {\n layer: number;\n order: number;\n}\nconst stack = new Set<Entry>();\nlet openings = 0;\n\n/**\n * A dialog's place among those on its layer, taken as it opens and kept while\n * it is suspended. Taken during render, where a dialog renders before the ones\n * nested in it, so nested dialogs that open with it still come after it.\n */\nexport function nextDialogOrder() {\n openings += 1;\n return openings;\n}\n\n/**\n * Register an open modal dialog; only the topmost one handles keys. A higher\n * layer wins, then the later opening, matching paint order: portals append as\n * dialogs open. A dialog resuming from suspension keeps its opening order, so\n * it never jumps above dialogs opened while it was suspended.\n */\nexport function openDialog(layer: number, order: number) {\n const entry: Entry = { layer, order };\n stack.add(entry);\n return {\n isTopmost: () => {\n for (const other of stack) {\n if (other.layer > layer || (other.layer === layer && other.order > order)) {\n return false;\n }\n }\n return stack.has(entry);\n },\n close: () => {\n stack.delete(entry);\n },\n };\n}\n","let locks = 0;\nlet previous = { overflow: \"\", paddingRight: \"\" };\n\n/**\n * Nested dialogs may unmount in either order; restore scrolling after the last.\n * Hiding a classic scrollbar widens the page, so the body is padded by the\n * width it gave back and layouts that measure themselves keep their mode.\n */\nexport function lockBodyScroll() {\n const { body, documentElement } = document;\n if (locks === 0) {\n previous = { overflow: body.style.overflow, paddingRight: body.style.paddingRight };\n const width = documentElement.clientWidth;\n body.style.overflow = \"hidden\";\n const scrollbar = documentElement.clientWidth - width;\n if (scrollbar > 0) {\n const padding = parseFloat(getComputedStyle(body).paddingRight) || 0;\n body.style.paddingRight = `${padding + scrollbar}px`;\n }\n }\n locks += 1;\n let released = false;\n return () => {\n if (released) {\n return;\n }\n released = true;\n locks -= 1;\n if (locks > 0) {\n return;\n }\n body.style.overflow = previous.overflow;\n body.style.paddingRight = previous.paddingRight;\n };\n}\n","import { useEffect, useRef, useState, type MouseEvent, type RefObject } from \"react\";\nimport { nextDialogOrder, openDialog } from \"./dialogStack\";\nimport { lockBodyScroll } from \"./lockBodyScroll\";\nimport {\n cannotHoldFocus,\n focusNearest,\n panelHoldsFocus,\n tabbableControls,\n trapTabFocus,\n} from \"./dialogFocus\";\nimport { isComposing } from \"./isComposing\";\nimport { useLatest } from \"./useLatest\";\n\nexport interface ModalDialogOptions {\n isOpen: boolean;\n /** An inactive open dialog stays mounted but leaves keys, focus and scrim presses to others. */\n isActive?: boolean;\n layer?: number;\n panelRef: RefObject<HTMLElement | null>;\n /** Escape and a direct scrim press call this. Read when called, so it may change every render. */\n onClose: () => void;\n /** First focus when focus isn't already inside the panel. Defaults to the first tabbable control, then the panel. */\n initialFocus?: () => HTMLElement | null | undefined;\n /** Panels that slide in from off-screen must not scroll the page when focused. */\n preventScroll?: boolean;\n /** Registration restarts when this changes while open, such as a new portal container. */\n container?: unknown;\n}\n\ninterface Opening {\n opener: Element | null;\n order: number;\n}\n\n/** Scroll the panel's own scroll areas, never the page or the panel's host, until `control` shows. */\nfunction revealInPanel(panel: HTMLElement, control: HTMLElement) {\n for (let area = control.parentElement; area && panel.contains(area); area = area.parentElement) {\n if (area.scrollHeight > area.clientHeight) {\n const view = area.getBoundingClientRect();\n const box = control.getBoundingClientRect();\n if (box.top < view.top) {\n area.scrollTop -= view.top - box.top;\n } else if (box.bottom > view.bottom) {\n area.scrollTop += Math.min(box.bottom - view.bottom, box.top - view.top);\n }\n }\n }\n}\n\n/**\n * Return to the control focused last in this opening, else to the initial\n * focus. A suspended panel stays laid out, so its scroll areas keep their\n * positions; a restored control is still brought into view within the panel,\n * in case its content moved, leaving the page where it is.\n */\nfunction focusPanel(\n panel: HTMLElement,\n previous: HTMLElement | undefined,\n initialFocus: ModalDialogOptions[\"initialFocus\"],\n options: FocusOptions,\n) {\n if (previous && panel.contains(previous) && !cannotHoldFocus(previous)) {\n previous.focus({ preventScroll: true });\n }\n if (previous && document.activeElement === previous) {\n revealInPanel(panel, previous);\n } else if (!panelHoldsFocus(panel, document.activeElement)) {\n (initialFocus?.() ?? tabbableControls(panel)[0] ?? panel).focus(options);\n }\n}\n\n/**\n * Behaviour every modal overlay shares: one dialog-stack entry, a body scroll\n * lock, Escape and a Tab trap while topmost, initial focus, and focus returned\n * to the opener (or its nearest focusable container) when closing dropped it.\n */\nexport function useModalDialog({\n isOpen,\n isActive = true,\n layer = 60,\n panelRef,\n onClose,\n initialFocus,\n preventScroll = false,\n container,\n}: ModalDialogOptions) {\n const latest = useLatest({ onClose, initialFocus });\n // Captured as the dialog opens, before autoFocus or the caller moves focus\n // inside it, and before the dialogs nested in it render.\n const [opening, setOpening] = useState<Opening | null>(null);\n const lastFocused = useRef<{ order: number; element: HTMLElement } | null>(null);\n if ((opening !== null) !== isOpen) {\n setOpening(\n isOpen\n ? {\n opener: typeof document === \"undefined\" ? null : document.activeElement,\n order: nextDialogOrder(),\n }\n : null,\n );\n }\n\n useEffect(() => {\n if (!isOpen || !isActive || !opening) {\n return;\n }\n const focusOptions = { preventScroll };\n const panel = panelRef.current;\n const dialog = openDialog(layer, opening.order);\n // Remembered per opening, so a new opening starts from its initial focus.\n const remember = (element: EventTarget | null) => {\n if (element instanceof HTMLElement) {\n lastFocused.current = { order: opening.order, element };\n }\n };\n const rememberFocus = ({ target }: FocusEvent) => remember(target);\n panel?.addEventListener(\"focusin\", rememberFocus);\n const active = document.activeElement;\n // Leave focus that autoFocus, the caller, or a popup resuming inside the\n // panel (its effects run first) already placed there.\n if (dialog.isTopmost() && panel && !panelHoldsFocus(panel, active)) {\n const previous = lastFocused.current;\n focusPanel(\n panel,\n previous?.order === opening.order ? previous.element : undefined,\n latest.current.initialFocus,\n focusOptions,\n );\n } else if (panel?.contains(active)) {\n // Focus placed before the listener was attached.\n remember(active);\n }\n\n const onKeyDown = (event: KeyboardEvent) => {\n // A nested picker, drawer or modal handles keys until it closes.\n if (!dialog.isTopmost()) {\n return;\n }\n if (event.key === \"Escape\") {\n // A popup inside the panel (Menu, Select, DateField) claims its Escape first.\n if (event.defaultPrevented || isComposing(event)) {\n return;\n }\n event.preventDefault();\n latest.current.onClose();\n return;\n }\n trapTabFocus(event, panelRef.current);\n };\n // On window, so popup handlers on the document and inside the panel run first.\n window.addEventListener(\"keydown\", onKeyDown);\n const unlockScroll = lockBodyScroll();\n\n return () => {\n panel?.removeEventListener(\"focusin\", rememberFocus);\n window.removeEventListener(\"keydown\", onKeyDown);\n dialog.close();\n unlockScroll();\n // Restore focus only when closing dropped it; the caller may already have placed it.\n if (cannotHoldFocus(document.activeElement)) {\n focusNearest(opening.opener, focusOptions);\n }\n };\n }, [isOpen, isActive, layer, opening, panelRef, preventScroll, container, latest]);\n\n /** Presses on the scrim itself close the dialog without moving focus first. */\n const onScrimMouseDown = (event: MouseEvent) => {\n if (isOpen && isActive && event.target === event.currentTarget) {\n event.preventDefault();\n latest.current.onClose();\n }\n };\n return { onScrimMouseDown, order: opening?.order };\n}\n","import type { AriaAttributes } from \"react\";\n\n/** Keep naming and visibility consistent across dialog frames, including suspended panels. */\nexport function dialogAttributes(\n props: AriaAttributes,\n titleId: string,\n descriptionId: string,\n hasDescription: boolean,\n active: boolean,\n) {\n return {\n role: \"dialog\" as const,\n \"aria-modal\": active || undefined,\n \"aria-hidden\": active ? props[\"aria-hidden\"] : true,\n \"aria-labelledby\": props[\"aria-label\"] ? undefined : (props[\"aria-labelledby\"] ?? titleId),\n \"aria-describedby\": hasDescription ? descriptionId : props[\"aria-describedby\"],\n };\n}\n"],"mappings":";;;;AAOA,SAAgBO,EAAkB,GAAmB,IAAsC,CAAC,GAAG;CAC7F,IAAI,OAAO,WAAa,KACtB,OAAO;CAET,IAAMC,IAAO,SAAS,cAAc,KAAK;CAGzC,OAFA,EAAK,YAAYC,GACjB,OAAO,OAAOD,EAAK,OAAOE,CAAK,GACxBF;AACT;AAEA,IAAMG,gBAAwB,CAAC;AAO/B,SAAgBC,EAAe,GAAmB,GAAsC;CACtF,IAAM,CAACJ,KAAQK,QAAeN,EAAkBE,GAAWC,CAAK,CAAC,GAC3DI,IAAWC,EACfJ,SACM,UACA,EACR;CAIA,OADAK,cAA+BR,GAAM,OAAO,GAAG,CAACA,CAAI,CAAC,GAC9CM,IAAWN,IAAO;AA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AAS;CAAM;AACnD;;;AC1KA,SAAgBiB,EACd,GACA,GACA,GACA,GACA,GACA;CACA,OAAO;EACL,MAAM;EACN,cAAc7D,KAAU,KAAA;EACxB,eAAe,MAAS8D,EAAM;EAC9B,mBAAmBA,EAAM,gBAAgB,KAAA,IAAaA,EAAM,sBAAsBC;EAClF,oBAAoBC,IAAiBC,IAAgBH,EAAM;CAC7D;AACF"}
1
+ {"version":3,"file":"dialogLabel-DT7rCr3_.js","names":["trapTabFocus","cannotHoldFocus","tabbableControls","panelHoldsFocus","focusNearest","useLatest","isComposing","createMovableHost","host","className","style","subscribe","useMovableHost","useState","hydrated","useSyncExternalStore","useInsertionEffect","moveHost","slot","insertHost","lastFocused","active","focused","refocus","before","ranks","placement","others","parent","child","isLater","other","rank","useDialogPortal","setRank","order","isPresent","container","inPlace","stack","openings","nextDialogOrder","openDialog","entry","layer","locks","previous","lockBodyScroll","body","width","documentElement","scrollbar","padding","released","revealInPanel","area","control","panel","view","box","focusPanel","initialFocus","options","useModalDialog","latest","opening","setOpening","useRef","isOpen","useEffect","isActive","focusOptions","panelRef","dialog","remember","element","rememberFocus","target","onKeyDown","event","unlockScroll","preventScroll","dialogAttributes","props","titleId","hasDescription","descriptionId"],"sources":["../../src/internal/movableHost.ts","../../src/internal/useDialogPortal.ts","../../src/internal/dialogStack.ts","../../src/internal/lockBodyScroll.ts","../../src/internal/useModalDialog.ts","../../src/internal/dialogLabel.ts"],"sourcesContent":["import { useInsertionEffect, useState, useSyncExternalStore } from \"react\";\nimport { cannotHoldFocus } from \"./dialogFocus\";\n\n/**\n * A detached element for portal content that moves between slots, so the tree\n * rendered into it never remounts. Null on the server.\n */\nexport function createMovableHost(className: string, style: Partial<CSSStyleDeclaration> = {}) {\n if (typeof document === \"undefined\") {\n return null;\n }\n const host = document.createElement(\"div\");\n host.className = className;\n Object.assign(host.style, style);\n return host;\n}\n\nconst subscribe = () => () => {};\n\n/**\n * A movable host for content that is also server rendered. It is null on the\n * server and while hydrating, so the first client render can match inline\n * server markup; client-only renders get the host on their first render.\n */\nexport function useMovableHost(className: string, style?: Partial<CSSStyleDeclaration>) {\n const [host] = useState(() => createMovableHost(className, style));\n const hydrated = useSyncExternalStore(\n subscribe,\n () => true,\n () => false,\n );\n // An insertion effect, which Strict Mode never replays: replaying a passive\n // cleanup would detach a host that an insertion effect placed.\n useInsertionEffect(() => () => host?.remove(), [host]);\n return hydrated ? host : null;\n}\n\n/**\n * Moves `host` into `slot`, or detaches it when there is no slot. A host already\n * in place is left alone: re-inserting it would reset scroll positions and drop\n * focus and the text selection. Returns whether the host moved.\n */\nexport function moveHost(\n host: HTMLElement,\n slot: Element | null,\n lastFocused: Element | null = null,\n) {\n if (!slot) {\n host.remove();\n return false;\n }\n if (host.parentNode === slot) {\n return false;\n }\n insertHost(host, slot, null, lastFocused);\n return true;\n}\n\n/**\n * Inserts `host` into `slot` before `before`, or at its end. Moving drops focus,\n * so the element inside the host that had it (or `lastFocused`, when an earlier\n * removal already dropped it) gets it back.\n */\nexport function insertHost(\n host: HTMLElement,\n slot: Element,\n before: Node | null,\n lastFocused: Element | null = null,\n) {\n const active = document.activeElement;\n const focused = active && host.contains(active) ? active : lastFocused;\n const refocus =\n focused instanceof HTMLElement &&\n host.contains(focused) &&\n (focused === active || cannotHoldFocus(active));\n slot.insertBefore(host, before);\n if (refocus) {\n focused.focus({ preventScroll: true });\n }\n}\n","import { useInsertionEffect, useState } from \"react\";\nimport { insertHost, useMovableHost } from \"./movableHost\";\n\n/** The opening order of each dialog's portal host. */\nconst ranks = new WeakMap<Element, number>();\n\n/**\n * Where `host` belongs among the other dialog hosts in `parent`: before the\n * first one opened later. It is in place when every host opened earlier comes\n * before it and every one opened later after it, whatever else lies between.\n */\nfunction placement(host: Element, parent: Element, rank: number) {\n const others = Array.from(parent.children).filter((child) => child !== host && ranks.has(child));\n const isLater = (other: Element) => (ranks.get(other) ?? 0) > rank;\n const inPlace =\n host.parentNode === parent &&\n others.every(\n (other) =>\n isLater(other) ===\n Boolean(host.compareDocumentPosition(other) & Node.DOCUMENT_POSITION_FOLLOWING),\n );\n return { inPlace, before: others.find(isLater) ?? null };\n}\n\n/**\n * A portal host that paints dialogs in opening order, as the dialog stack ranks\n * them, including a nested dialog that opens in the same commit as its parent\n * (React inserts that one's portal first). The host moves only when its order\n * is wrong, keeping focus, so a reopened dialog keeps its scroll and focus.\n * Null on the server and while hydrating.\n */\nexport function useDialogPortal(\n order: number | undefined,\n isPresent: boolean,\n container?: HTMLElement | null,\n) {\n // Kept through a closing transition, when the dialog no longer has an order.\n const [rank, setRank] = useState(order ?? 0);\n if (order !== undefined && order !== rank) {\n setRank(order);\n }\n // Contents only, so a contained drawer's container lays out the frame itself.\n const host = useMovableHost(\"ds-dialog-host\", { display: \"contents\" });\n // Before layout effects, so content measures and focuses inside the document.\n useInsertionEffect(() => {\n if (!host) {\n return;\n }\n if (!isPresent) {\n host.remove();\n return;\n }\n ranks.set(host, rank);\n const parent = container ?? document.body;\n const { inPlace, before } = placement(host, parent, rank);\n if (!inPlace) {\n insertHost(host, parent, before);\n }\n }, [host, rank, isPresent, container]);\n return host;\n}\n","interface Entry {\n layer: number;\n order: number;\n}\nconst stack = new Set<Entry>();\nlet openings = 0;\n\n/**\n * A dialog's place among those on its layer, taken as it opens and kept while\n * it is suspended. Taken during render, where a dialog renders before the ones\n * nested in it, so nested dialogs that open with it still come after it.\n */\nexport function nextDialogOrder() {\n openings += 1;\n return openings;\n}\n\n/**\n * Register an open modal dialog; only the topmost one handles keys. A higher\n * layer wins, then the later opening, matching paint order: portals append as\n * dialogs open. A dialog resuming from suspension keeps its opening order, so\n * it never jumps above dialogs opened while it was suspended.\n */\nexport function openDialog(layer: number, order: number) {\n const entry: Entry = { layer, order };\n stack.add(entry);\n return {\n isTopmost: () => {\n for (const other of stack) {\n if (other.layer > layer || (other.layer === layer && other.order > order)) {\n return false;\n }\n }\n return stack.has(entry);\n },\n close: () => {\n stack.delete(entry);\n },\n };\n}\n","let locks = 0;\nlet previous = { overflow: \"\", paddingRight: \"\" };\n\n/**\n * Nested dialogs may unmount in either order; restore scrolling after the last.\n * Hiding a classic scrollbar widens the page, so the body is padded by the\n * width it gave back and layouts that measure themselves keep their mode.\n */\nexport function lockBodyScroll() {\n const { body, documentElement } = document;\n if (locks === 0) {\n previous = { overflow: body.style.overflow, paddingRight: body.style.paddingRight };\n const width = documentElement.clientWidth;\n body.style.overflow = \"hidden\";\n const scrollbar = documentElement.clientWidth - width;\n if (scrollbar > 0) {\n const padding = parseFloat(getComputedStyle(body).paddingRight) || 0;\n body.style.paddingRight = `${padding + scrollbar}px`;\n }\n }\n locks += 1;\n let released = false;\n return () => {\n if (released) {\n return;\n }\n released = true;\n locks -= 1;\n if (locks > 0) {\n return;\n }\n body.style.overflow = previous.overflow;\n body.style.paddingRight = previous.paddingRight;\n };\n}\n","import { useEffect, useRef, useState, type MouseEvent, type RefObject } from \"react\";\nimport { nextDialogOrder, openDialog } from \"./dialogStack\";\nimport { lockBodyScroll } from \"./lockBodyScroll\";\nimport {\n cannotHoldFocus,\n focusNearest,\n panelHoldsFocus,\n tabbableControls,\n trapTabFocus,\n} from \"./dialogFocus\";\nimport { isComposing } from \"./isComposing\";\nimport { useLatest } from \"./useLatest\";\n\nexport interface ModalDialogOptions {\n isOpen: boolean;\n /** An inactive open dialog stays mounted but leaves keys, focus and scrim presses to others. */\n isActive?: boolean;\n layer?: number;\n panelRef: RefObject<HTMLElement | null>;\n /** Escape and a direct scrim press call this. Read when called, so it may change every render. */\n onClose: () => void;\n /** First focus when focus isn't already inside the panel. Defaults to the first tabbable control, then the panel. */\n initialFocus?: () => HTMLElement | null | undefined;\n /** Panels that slide in from off-screen must not scroll the page when focused. */\n preventScroll?: boolean;\n /** Registration restarts when this changes while open, such as a new portal container. */\n container?: unknown;\n}\n\ninterface Opening {\n opener: Element | null;\n order: number;\n}\n\n/** Scroll the panel's own scroll areas, never the page or the panel's host, until `control` shows. */\nfunction revealInPanel(panel: HTMLElement, control: HTMLElement) {\n for (let area = control.parentElement; area && panel.contains(area); area = area.parentElement) {\n if (area.scrollHeight > area.clientHeight) {\n const view = area.getBoundingClientRect();\n const box = control.getBoundingClientRect();\n if (box.top < view.top) {\n area.scrollTop -= view.top - box.top;\n } else if (box.bottom > view.bottom) {\n area.scrollTop += Math.min(box.bottom - view.bottom, box.top - view.top);\n }\n }\n }\n}\n\n/**\n * Return to the control focused last in this opening, else to the initial\n * focus. A suspended panel stays laid out, so its scroll areas keep their\n * positions; a restored control is still brought into view within the panel,\n * in case its content moved, leaving the page where it is.\n */\nfunction focusPanel(\n panel: HTMLElement,\n previous: HTMLElement | undefined,\n initialFocus: ModalDialogOptions[\"initialFocus\"],\n options: FocusOptions,\n) {\n if (previous && panel.contains(previous) && !cannotHoldFocus(previous)) {\n previous.focus({ preventScroll: true });\n }\n if (previous && document.activeElement === previous) {\n revealInPanel(panel, previous);\n } else if (!panelHoldsFocus(panel, document.activeElement)) {\n (initialFocus?.() ?? tabbableControls(panel)[0] ?? panel).focus(options);\n }\n}\n\n/**\n * Behaviour every modal overlay shares: one dialog-stack entry, a body scroll\n * lock, Escape and a Tab trap while topmost, initial focus, and focus returned\n * to the opener (or its nearest focusable container) when closing dropped it.\n */\nexport function useModalDialog({\n isOpen,\n isActive = true,\n layer = 60,\n panelRef,\n onClose,\n initialFocus,\n preventScroll = false,\n container,\n}: ModalDialogOptions) {\n const latest = useLatest({ onClose, initialFocus });\n // Captured as the dialog opens, before autoFocus or the caller moves focus\n // inside it, and before the dialogs nested in it render.\n const [opening, setOpening] = useState<Opening | null>(null);\n const lastFocused = useRef<{ order: number; element: HTMLElement } | null>(null);\n if ((opening !== null) !== isOpen) {\n setOpening(\n isOpen\n ? {\n opener: typeof document === \"undefined\" ? null : document.activeElement,\n order: nextDialogOrder(),\n }\n : null,\n );\n }\n\n useEffect(() => {\n if (!isOpen || !isActive || !opening) {\n return;\n }\n const focusOptions = { preventScroll };\n const panel = panelRef.current;\n const dialog = openDialog(layer, opening.order);\n // Remembered per opening, so a new opening starts from its initial focus.\n const remember = (element: EventTarget | null) => {\n if (element instanceof HTMLElement) {\n lastFocused.current = { order: opening.order, element };\n }\n };\n const rememberFocus = ({ target }: FocusEvent) => remember(target);\n panel?.addEventListener(\"focusin\", rememberFocus);\n const active = document.activeElement;\n // Leave focus that autoFocus, the caller, or a popup resuming inside the\n // panel (its effects run first) already placed there.\n if (dialog.isTopmost() && panel && !panelHoldsFocus(panel, active)) {\n const previous = lastFocused.current;\n focusPanel(\n panel,\n previous?.order === opening.order ? previous.element : undefined,\n latest.current.initialFocus,\n focusOptions,\n );\n } else if (panel?.contains(active)) {\n // Focus placed before the listener was attached.\n remember(active);\n }\n\n const onKeyDown = (event: KeyboardEvent) => {\n // A nested picker, drawer or modal handles keys until it closes.\n if (!dialog.isTopmost()) {\n return;\n }\n if (event.key === \"Escape\") {\n // A popup inside the panel (Menu, Select, DateField) claims its Escape first.\n if (event.defaultPrevented || isComposing(event)) {\n return;\n }\n event.preventDefault();\n latest.current.onClose();\n return;\n }\n trapTabFocus(event, panelRef.current);\n };\n // On window, so popup handlers on the document and inside the panel run first.\n window.addEventListener(\"keydown\", onKeyDown);\n const unlockScroll = lockBodyScroll();\n\n return () => {\n panel?.removeEventListener(\"focusin\", rememberFocus);\n window.removeEventListener(\"keydown\", onKeyDown);\n dialog.close();\n unlockScroll();\n // Restore focus only when closing dropped it; the caller may already have placed it.\n if (cannotHoldFocus(document.activeElement)) {\n focusNearest(opening.opener, focusOptions);\n }\n };\n }, [isOpen, isActive, layer, opening, panelRef, preventScroll, container, latest]);\n\n /** Presses on the scrim itself close the dialog without moving focus first. */\n const onScrimMouseDown = (event: MouseEvent) => {\n if (isOpen && isActive && event.target === event.currentTarget) {\n event.preventDefault();\n latest.current.onClose();\n }\n };\n return { onScrimMouseDown, order: opening?.order };\n}\n","import type { AriaAttributes } from \"react\";\n\n/** Keep naming and visibility consistent across dialog frames, including suspended panels. */\nexport function dialogAttributes(\n props: AriaAttributes,\n titleId: string,\n descriptionId: string,\n hasDescription: boolean,\n active: boolean,\n) {\n return {\n role: \"dialog\" as const,\n \"aria-modal\": active || undefined,\n \"aria-hidden\": active ? props[\"aria-hidden\"] : true,\n \"aria-labelledby\": props[\"aria-label\"] ? undefined : (props[\"aria-labelledby\"] ?? titleId),\n \"aria-describedby\": hasDescription ? descriptionId : props[\"aria-describedby\"],\n };\n}\n"],"mappings":";;;;AAOA,SAAgBO,EAAkB,GAAmB,IAAsC,CAAC,GAAG;CAC7F,IAAI,OAAO,WAAa,KACtB,OAAO;CAET,IAAMC,IAAO,SAAS,cAAc,KAAK;CAGzC,OAFA,EAAK,YAAYC,GACjB,OAAO,OAAOD,EAAK,OAAOE,CAAK,GACxBF;AACT;AAEA,IAAMG,gBAAwB,CAAC;AAO/B,SAAgBC,EAAe,GAAmB,GAAsC;CACtF,IAAM,CAACJ,KAAQK,QAAeN,EAAkBE,GAAWC,CAAK,CAAC,GAC3DI,IAAWC,EACfJ,SACM,UACA,EACR;CAIA,OADAK,cAA+BR,GAAM,OAAO,GAAG,CAACA,CAAI,CAAC,GAC9CM,IAAWN,IAAO;AAC3B;AAOA,SAAgBS,EACd,GACA,GACA,IAA8B,MAC9B;CASA,OARKC,IAIDV,EAAK,eAAeU,MAGxBC,EAAWX,GAAMU,GAAM,MAAME,CAAW,GACjC,OAPLZ,EAAK,OAAO,GACL;AAOX;AAOA,SAAgBW,EACd,GACA,GACA,GACA,IAA8B,MAC9B;CACA,IAAME,IAAS,SAAS,eAClBC,IAAUD,KAAUb,EAAK,SAASa,CAAM,IAAIA,IAASD,GACrDG,IACJD,aAAmB,eACnBd,EAAK,SAASc,CAAO,MACpBA,MAAYD,KAAUpB,EAAgBoB,CAAM;CAE/C,AADAH,EAAK,aAAaV,GAAMgB,CAAM,GAC1BD,KACFD,EAAQ,MAAM,EAAE,eAAe,GAAK,CAAC;AAEzC;;;AC3EA,IAAMG,oBAAQ,IAAI,QAAyB;AAO3C,SAASC,EAAU,GAAe,GA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MAAyB;GAE1C,IAAKL,EAAO,UAAU,GAGtB;QAAIM,EAAM,QAAQ,UAAU;KAE1B,IAAIA,EAAM,oBAAoBzE,EAAYyE,CAAK,GAC7C;KAGF,AADAA,EAAM,eAAe,GACrBf,EAAO,QAAQ,QAAQ;IAEzB,OACA,EAAae,GAAOP,EAAS,OAAO;GADpC;EAEF;EAEA,OAAO,iBAAiB,WAAWM,CAAS;EAC5C,IAAME,IAAejC,EAAe;EAEpC,aAAa;GAMX,AALAU,GAAO,oBAAoB,WAAWmB,CAAa,GACnD,OAAO,oBAAoB,WAAWE,CAAS,GAC/CL,EAAO,MAAM,GACbO,EAAa,GAET/E,EAAgB,SAAS,aAAa,KACxCG,EAAa6D,EAAQ,QAAQM,CAAY;EAE7C;CACF,GAAG;EAACH;EAAQE;EAAU1B;EAAOqB;EAASO;EAAUS;EAAe5C;EAAW2B;CAAM,CAAC,GAS1E;EAAE,mBANiB,MAAsB;GAC9C,AAAII,KAAUE,KAAYS,EAAM,WAAWA,EAAM,kBAC/CA,EAAM,eAAe,GACrBf,EAAO,QAAQ,QAAQ;EAE3B;EAC2B,OAAOC,GAAS;CAAM;AACnD;;;AC1KA,SAAgBiB,EACd,GACA,GACA,GACA,GACA,GACA;CACA,OAAO;EACL,MAAM;EACN,cAAc7D,KAAU,KAAA;EACxB,eAAe,MAAS8D,EAAM;EAC9B,mBAAmBA,EAAM,gBAAgB,KAAA,IAAaA,EAAM,sBAAsBC;EAClF,oBAAoBC,IAAiBC,IAAgBH,EAAM;CAC7D;AACF"}
@@ -1,2 +1,2 @@
1
- const e=require("./overlayLayer-seJG-EFn.cjs"),t=require("./isComposing-BrBcAANm.cjs");let n=require("react");function r(e,t={}){if(typeof document>`u`)return null;let n=document.createElement(`div`);return n.className=e,Object.assign(n.style,t),n}var i=()=>()=>{};function a(e,t){let[a]=(0,n.useState)(()=>r(e,t)),o=(0,n.useSyncExternalStore)(i,()=>!0,()=>!1);return(0,n.useInsertionEffect)(()=>()=>a?.remove(),[a]),o?a:null}function o(e,t,n=null){return t?e.parentNode!==t&&(s(e,t,null,n),!0):(e.remove(),!1)}function s(t,n,r,i=null){let a=document.activeElement,o=a&&t.contains(a)?a:i,s=o instanceof HTMLElement&&t.contains(o)&&(o===a||e.d(a));n.insertBefore(t,r),s&&o.focus({preventScroll:!0})}var c=new WeakMap;function l(e,t,n){let r=Array.from(t.children).filter(t=>t!==e&&c.has(t)),i=e=>(c.get(e)??0)>n;return{inPlace:e.parentNode===t&&r.every(t=>i(t)===!!(e.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_FOLLOWING)),before:r.find(i)??null}}function u(e,t,r){let[i,o]=(0,n.useState)(e??0);e!==void 0&&e!==i&&o(e);let u=a(`ds-dialog-host`,{display:`contents`});return(0,n.useInsertionEffect)(()=>{if(!u)return;if(!t){u.remove();return}c.set(u,i);let e=r??document.body,{inPlace:n,before:a}=l(u,e,i);n||s(u,e,a)},[u,i,t,r]),u}var d=new Set,f=0;function p(){return f+=1,f}function m(e,t){let n={layer:e,order:t};return d.add(n),{isTopmost:()=>{for(let n of d)if(n.layer>e||n.layer===e&&n.order>t)return!1;return d.has(n)},close:()=>{d.delete(n)}}}var h=0,g={overflow:``,paddingRight:``};function _(){let{body:e,documentElement:t}=document;if(h===0){g={overflow:e.style.overflow,paddingRight:e.style.paddingRight};let n=t.clientWidth;e.style.overflow=`hidden`;let r=t.clientWidth-n;if(r>0){let t=parseFloat(getComputedStyle(e).paddingRight)||0;e.style.paddingRight=`${t+r}px`}}h+=1;let n=!1;return()=>{n||(n=!0,--h,!(h>0)&&(e.style.overflow=g.overflow,e.style.paddingRight=g.paddingRight))}}function v(e,t){for(let n=t.parentElement;n&&e.contains(n);n=n.parentElement)if(n.scrollHeight>n.clientHeight){let e=n.getBoundingClientRect(),r=t.getBoundingClientRect();r.top<e.top?n.scrollTop-=e.top-r.top:r.bottom>e.bottom&&(n.scrollTop+=Math.min(r.bottom-e.bottom,r.top-e.top))}}function y(t,n,r,i){n&&t.contains(n)&&!e.d(n)&&n.focus({preventScroll:!0}),n&&document.activeElement===n?v(t,n):e.p(t,document.activeElement)||(r?.()??e.h(t)[0]??t).focus(i)}function b({isOpen:r,isActive:i=!0,layer:a=60,panelRef:o,onClose:s,initialFocus:c,preventScroll:l=!1,container:u}){let d=e.u({onClose:s,initialFocus:c}),[f,h]=(0,n.useState)(null),g=(0,n.useRef)(null);return f!==null!==r&&h(r?{opener:typeof document>`u`?null:document.activeElement,order:p()}:null),(0,n.useEffect)(()=>{if(!r||!i||!f)return;let n={preventScroll:l},s=o.current,c=m(a,f.order),u=e=>{e instanceof HTMLElement&&(g.current={order:f.order,element:e})},p=({target:e})=>u(e);s?.addEventListener(`focusin`,p);let h=document.activeElement;if(c.isTopmost()&&s&&!e.p(s,h)){let e=g.current;y(s,e?.order===f.order?e.element:void 0,d.current.initialFocus,n)}else s?.contains(h)&&u(h);let v=n=>{if(c.isTopmost()){if(n.key===`Escape`){if(n.defaultPrevented||t.t(n))return;n.preventDefault(),d.current.onClose()}else e.g(n,o.current)}};window.addEventListener(`keydown`,v);let b=_();return()=>{s?.removeEventListener(`focusin`,p),window.removeEventListener(`keydown`,v),c.close(),b(),e.d(document.activeElement)&&e.f(f.opener,n)}},[r,i,a,f,o,l,u,d]),{onScrimMouseDown:e=>{r&&i&&e.target===e.currentTarget&&(e.preventDefault(),d.current.onClose())},order:f?.order}}function x(e,t,n,r,i){return{role:`dialog`,"aria-modal":i||void 0,"aria-hidden":!i||e[`aria-hidden`],"aria-labelledby":e[`aria-label`]?void 0:e[`aria-labelledby`]??t,"aria-describedby":r?n:e[`aria-describedby`]}}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return x}});
2
- //# sourceMappingURL=dialogLabel-2HRYMHbF.cjs.map
1
+ const e=require("./overlayLayer-iGhuAByk.cjs"),t=require("./isComposing-BrBcAANm.cjs");let n=require("react");function r(e,t={}){if(typeof document>`u`)return null;let n=document.createElement(`div`);return n.className=e,Object.assign(n.style,t),n}var i=()=>()=>{};function a(e,t){let[a]=(0,n.useState)(()=>r(e,t)),o=(0,n.useSyncExternalStore)(i,()=>!0,()=>!1);return(0,n.useInsertionEffect)(()=>()=>a?.remove(),[a]),o?a:null}function o(e,t,n=null){return t?e.parentNode!==t&&(s(e,t,null,n),!0):(e.remove(),!1)}function s(t,n,r,i=null){let a=document.activeElement,o=a&&t.contains(a)?a:i,s=o instanceof HTMLElement&&t.contains(o)&&(o===a||e.d(a));n.insertBefore(t,r),s&&o.focus({preventScroll:!0})}var c=new WeakMap;function l(e,t,n){let r=Array.from(t.children).filter(t=>t!==e&&c.has(t)),i=e=>(c.get(e)??0)>n;return{inPlace:e.parentNode===t&&r.every(t=>i(t)===!!(e.compareDocumentPosition(t)&Node.DOCUMENT_POSITION_FOLLOWING)),before:r.find(i)??null}}function u(e,t,r){let[i,o]=(0,n.useState)(e??0);e!==void 0&&e!==i&&o(e);let u=a(`ds-dialog-host`,{display:`contents`});return(0,n.useInsertionEffect)(()=>{if(!u)return;if(!t){u.remove();return}c.set(u,i);let e=r??document.body,{inPlace:n,before:a}=l(u,e,i);n||s(u,e,a)},[u,i,t,r]),u}var d=new Set,f=0;function p(){return f+=1,f}function m(e,t){let n={layer:e,order:t};return d.add(n),{isTopmost:()=>{for(let n of d)if(n.layer>e||n.layer===e&&n.order>t)return!1;return d.has(n)},close:()=>{d.delete(n)}}}var h=0,g={overflow:``,paddingRight:``};function _(){let{body:e,documentElement:t}=document;if(h===0){g={overflow:e.style.overflow,paddingRight:e.style.paddingRight};let n=t.clientWidth;e.style.overflow=`hidden`;let r=t.clientWidth-n;if(r>0){let t=parseFloat(getComputedStyle(e).paddingRight)||0;e.style.paddingRight=`${t+r}px`}}h+=1;let n=!1;return()=>{n||(n=!0,--h,!(h>0)&&(e.style.overflow=g.overflow,e.style.paddingRight=g.paddingRight))}}function v(e,t){for(let n=t.parentElement;n&&e.contains(n);n=n.parentElement)if(n.scrollHeight>n.clientHeight){let e=n.getBoundingClientRect(),r=t.getBoundingClientRect();r.top<e.top?n.scrollTop-=e.top-r.top:r.bottom>e.bottom&&(n.scrollTop+=Math.min(r.bottom-e.bottom,r.top-e.top))}}function y(t,n,r,i){n&&t.contains(n)&&!e.d(n)&&n.focus({preventScroll:!0}),n&&document.activeElement===n?v(t,n):e.m(t,document.activeElement)||(r?.()??e.g(t)[0]??t).focus(i)}function b({isOpen:r,isActive:i=!0,layer:a=60,panelRef:o,onClose:s,initialFocus:c,preventScroll:l=!1,container:u}){let d=e.u({onClose:s,initialFocus:c}),[f,h]=(0,n.useState)(null),g=(0,n.useRef)(null);return f!==null!==r&&h(r?{opener:typeof document>`u`?null:document.activeElement,order:p()}:null),(0,n.useEffect)(()=>{if(!r||!i||!f)return;let n={preventScroll:l},s=o.current,c=m(a,f.order),u=e=>{e instanceof HTMLElement&&(g.current={order:f.order,element:e})},p=({target:e})=>u(e);s?.addEventListener(`focusin`,p);let h=document.activeElement;if(c.isTopmost()&&s&&!e.m(s,h)){let e=g.current;y(s,e?.order===f.order?e.element:void 0,d.current.initialFocus,n)}else s?.contains(h)&&u(h);let v=n=>{if(c.isTopmost()){if(n.key===`Escape`){if(n.defaultPrevented||t.t(n))return;n.preventDefault(),d.current.onClose()}else e._(n,o.current)}};window.addEventListener(`keydown`,v);let b=_();return()=>{s?.removeEventListener(`focusin`,p),window.removeEventListener(`keydown`,v),c.close(),b(),e.d(document.activeElement)&&e.p(f.opener,n)}},[r,i,a,f,o,l,u,d]),{onScrimMouseDown:e=>{r&&i&&e.target===e.currentTarget&&(e.preventDefault(),d.current.onClose())},order:f?.order}}function x(e,t,n,r,i){return{role:`dialog`,"aria-modal":i||void 0,"aria-hidden":!i||e[`aria-hidden`],"aria-labelledby":e[`aria-label`]?void 0:e[`aria-labelledby`]??t,"aria-describedby":r?n:e[`aria-describedby`]}}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return b}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return x}});
2
+ //# sourceMappingURL=dialogLabel-_-MTckE_.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"dialogLabel-2HRYMHbF.cjs","names":["useState","useSyncExternalStore","cannotHoldFocus","useState","cannotHoldFocus","panelHoldsFocus","tabbableControls","useLatest","useState","useRef","isComposing","require_overlayLayer","require_isComposing","react","createMovableHost","host","className","style","subscribe","useMovableHost","hydrated","moveHost","slot","insertHost","lastFocused","active","focused","refocus","before","ranks","placement","others","parent","child","isLater","other","rank","useDialogPortal","setRank","order","isPresent","container","inPlace","stack","openings","nextDialogOrder","openDialog","entry","layer","locks","previous","lockBodyScroll","body","width","documentElement","scrollbar","padding","released","revealInPanel","area","control","panel","view","box","focusPanel","initialFocus","options","useModalDialog","latest","opening","setOpening","isOpen","isActive","focusOptions","panelRef","dialog","remember","element","rememberFocus","target","onKeyDown","event","unlockScroll","preventScroll","dialogAttributes","props","titleId","hasDescription","descriptionId"],"sources":["../../src/internal/movableHost.ts","../../src/internal/useDialogPortal.ts","../../src/internal/dialogStack.ts","../../src/internal/lockBodyScroll.ts","../../src/internal/useModalDialog.ts","../../src/internal/dialogLabel.ts"],"sourcesContent":["import { useInsertionEffect, useState, useSyncExternalStore } from \"react\";\nimport { cannotHoldFocus } from \"./dialogFocus\";\n\n/**\n * A detached element for portal content that moves between slots, so the tree\n * rendered into it never remounts. Null on the server.\n */\nexport function createMovableHost(className: string, style: Partial<CSSStyleDeclaration> = {}) {\n if (typeof document === \"undefined\") {\n return null;\n }\n const host = document.createElement(\"div\");\n host.className = className;\n Object.assign(host.style, style);\n return host;\n}\n\nconst subscribe = () => () => {};\n\n/**\n * A movable host for content that is also server rendered. It is null on the\n * server and while hydrating, so the first client render can match inline\n * server markup; client-only renders get the host on their first render.\n */\nexport function useMovableHost(className: string, style?: Partial<CSSStyleDeclaration>) {\n const [host] = useState(() => createMovableHost(className, style));\n const hydrated = useSyncExternalStore(\n subscribe,\n () => true,\n () => false,\n );\n // An insertion effect, which Strict Mode never replays: replaying a passive\n // cleanup would detach a host that an insertion effect placed.\n useInsertionEffect(() => () => host?.remove(), [host]);\n return hydrated ? host : null;\n}\n\n/**\n * Moves `host` into `slot`, or detaches it when there is no slot. A host already\n * in place is left alone: re-inserting it would reset scroll positions and drop\n * focus and the text selection. Returns whether the host moved.\n */\nexport function moveHost(\n host: HTMLElement,\n slot: Element | null,\n lastFocused: Element | null = null,\n) {\n if (!slot) {\n host.remove();\n return false;\n }\n if (host.parentNode === slot) {\n return false;\n }\n insertHost(host, slot, null, lastFocused);\n return true;\n}\n\n/**\n * Inserts `host` into `slot` before `before`, or at its end. Moving drops focus,\n * so the element inside the host that had it (or `lastFocused`, when an earlier\n * removal already dropped it) gets it back.\n */\nexport function insertHost(\n host: HTMLElement,\n slot: Element,\n before: Node | null,\n lastFocused: Element | null = null,\n) {\n const active = document.activeElement;\n const focused = active && host.contains(active) ? active : lastFocused;\n const refocus =\n focused instanceof HTMLElement &&\n host.contains(focused) &&\n (focused === active || cannotHoldFocus(active));\n slot.insertBefore(host, before);\n if (refocus) {\n focused.focus({ preventScroll: true });\n }\n}\n","import { useInsertionEffect, useState } from \"react\";\nimport { insertHost, useMovableHost } from \"./movableHost\";\n\n/** The opening order of each dialog's portal host. */\nconst ranks = new WeakMap<Element, number>();\n\n/**\n * Where `host` belongs among the other dialog hosts in `parent`: before the\n * first one opened later. It is in place when every host opened earlier comes\n * before it and every one opened later after it, whatever else lies between.\n */\nfunction placement(host: Element, parent: Element, rank: number) {\n const others = Array.from(parent.children).filter((child) => child !== host && ranks.has(child));\n const isLater = (other: Element) => (ranks.get(other) ?? 0) > rank;\n const inPlace =\n host.parentNode === parent &&\n others.every(\n (other) =>\n isLater(other) ===\n Boolean(host.compareDocumentPosition(other) & Node.DOCUMENT_POSITION_FOLLOWING),\n );\n return { inPlace, before: others.find(isLater) ?? null };\n}\n\n/**\n * A portal host that paints dialogs in opening order, as the dialog stack ranks\n * them, including a nested dialog that opens in the same commit as its parent\n * (React inserts that one's portal first). The host moves only when its order\n * is wrong, keeping focus, so a reopened dialog keeps its scroll and focus.\n * Null on the server and while hydrating.\n */\nexport function useDialogPortal(\n order: number | undefined,\n isPresent: boolean,\n container?: HTMLElement | null,\n) {\n // Kept through a closing transition, when the dialog no longer has an order.\n const [rank, setRank] = useState(order ?? 0);\n if (order !== undefined && order !== rank) {\n setRank(order);\n }\n // Contents only, so a contained drawer's container lays out the frame itself.\n const host = useMovableHost(\"ds-dialog-host\", { display: \"contents\" });\n // Before layout effects, so content measures and focuses inside the document.\n useInsertionEffect(() => {\n if (!host) {\n return;\n }\n if (!isPresent) {\n host.remove();\n return;\n }\n ranks.set(host, rank);\n const parent = container ?? document.body;\n const { inPlace, before } = placement(host, parent, rank);\n if (!inPlace) {\n insertHost(host, parent, before);\n }\n }, [host, rank, isPresent, container]);\n return host;\n}\n","interface Entry {\n layer: number;\n order: number;\n}\nconst stack = new Set<Entry>();\nlet openings = 0;\n\n/**\n * A dialog's place among those on its layer, taken as it opens and kept while\n * it is suspended. Taken during render, where a dialog renders before the ones\n * nested in it, so nested dialogs that open with it still come after it.\n */\nexport function nextDialogOrder() {\n openings += 1;\n return openings;\n}\n\n/**\n * Register an open modal dialog; only the topmost one handles keys. A higher\n * layer wins, then the later opening, matching paint order: portals append as\n * dialogs open. A dialog resuming from suspension keeps its opening order, so\n * it never jumps above dialogs opened while it was suspended.\n */\nexport function openDialog(layer: number, order: number) {\n const entry: Entry = { layer, order };\n stack.add(entry);\n return {\n isTopmost: () => {\n for (const other of stack) {\n if (other.layer > layer || (other.layer === layer && other.order > order)) {\n return false;\n }\n }\n return stack.has(entry);\n },\n close: () => {\n stack.delete(entry);\n },\n };\n}\n","let locks = 0;\nlet previous = { overflow: \"\", paddingRight: \"\" };\n\n/**\n * Nested dialogs may unmount in either order; restore scrolling after the last.\n * Hiding a classic scrollbar widens the page, so the body is padded by the\n * width it gave back and layouts that measure themselves keep their mode.\n */\nexport function lockBodyScroll() {\n const { body, documentElement } = document;\n if (locks === 0) {\n previous = { overflow: body.style.overflow, paddingRight: body.style.paddingRight };\n const width = documentElement.clientWidth;\n body.style.overflow = \"hidden\";\n const scrollbar = documentElement.clientWidth - width;\n if (scrollbar > 0) {\n const padding = parseFloat(getComputedStyle(body).paddingRight) || 0;\n body.style.paddingRight = `${padding + scrollbar}px`;\n }\n }\n locks += 1;\n let released = false;\n return () => {\n if (released) {\n return;\n }\n released = true;\n locks -= 1;\n if (locks > 0) {\n return;\n }\n body.style.overflow = previous.overflow;\n body.style.paddingRight = previous.paddingRight;\n };\n}\n","import { useEffect, useRef, useState, type MouseEvent, type RefObject } from \"react\";\nimport { nextDialogOrder, openDialog } from \"./dialogStack\";\nimport { lockBodyScroll } from \"./lockBodyScroll\";\nimport {\n cannotHoldFocus,\n focusNearest,\n panelHoldsFocus,\n tabbableControls,\n trapTabFocus,\n} from \"./dialogFocus\";\nimport { isComposing } from \"./isComposing\";\nimport { useLatest } from \"./useLatest\";\n\nexport interface ModalDialogOptions {\n isOpen: boolean;\n /** An inactive open dialog stays mounted but leaves keys, focus and scrim presses to others. */\n isActive?: boolean;\n layer?: number;\n panelRef: RefObject<HTMLElement | null>;\n /** Escape and a direct scrim press call this. Read when called, so it may change every render. */\n onClose: () => void;\n /** First focus when focus isn't already inside the panel. Defaults to the first tabbable control, then the panel. */\n initialFocus?: () => HTMLElement | null | undefined;\n /** Panels that slide in from off-screen must not scroll the page when focused. */\n preventScroll?: boolean;\n /** Registration restarts when this changes while open, such as a new portal container. */\n container?: unknown;\n}\n\ninterface Opening {\n opener: Element | null;\n order: number;\n}\n\n/** Scroll the panel's own scroll areas, never the page or the panel's host, until `control` shows. */\nfunction revealInPanel(panel: HTMLElement, control: HTMLElement) {\n for (let area = control.parentElement; area && panel.contains(area); area = area.parentElement) {\n if (area.scrollHeight > area.clientHeight) {\n const view = area.getBoundingClientRect();\n const box = control.getBoundingClientRect();\n if (box.top < view.top) {\n area.scrollTop -= view.top - box.top;\n } else if (box.bottom > view.bottom) {\n area.scrollTop += Math.min(box.bottom - view.bottom, box.top - view.top);\n }\n }\n }\n}\n\n/**\n * Return to the control focused last in this opening, else to the initial\n * focus. A suspended panel stays laid out, so its scroll areas keep their\n * positions; a restored control is still brought into view within the panel,\n * in case its content moved, leaving the page where it is.\n */\nfunction focusPanel(\n panel: HTMLElement,\n previous: HTMLElement | undefined,\n initialFocus: ModalDialogOptions[\"initialFocus\"],\n options: FocusOptions,\n) {\n if (previous && panel.contains(previous) && !cannotHoldFocus(previous)) {\n previous.focus({ preventScroll: true });\n }\n if (previous && document.activeElement === previous) {\n revealInPanel(panel, previous);\n } else if (!panelHoldsFocus(panel, document.activeElement)) {\n (initialFocus?.() ?? tabbableControls(panel)[0] ?? panel).focus(options);\n }\n}\n\n/**\n * Behaviour every modal overlay shares: one dialog-stack entry, a body scroll\n * lock, Escape and a Tab trap while topmost, initial focus, and focus returned\n * to the opener (or its nearest focusable container) when closing dropped it.\n */\nexport function useModalDialog({\n isOpen,\n isActive = true,\n layer = 60,\n panelRef,\n onClose,\n initialFocus,\n preventScroll = false,\n container,\n}: ModalDialogOptions) {\n const latest = useLatest({ onClose, initialFocus });\n // Captured as the dialog opens, before autoFocus or the caller moves focus\n // inside it, and before the dialogs nested in it render.\n const [opening, setOpening] = useState<Opening | null>(null);\n const lastFocused = useRef<{ order: number; element: HTMLElement } | null>(null);\n if ((opening !== null) !== isOpen) {\n setOpening(\n isOpen\n ? {\n opener: typeof document === \"undefined\" ? null : document.activeElement,\n order: nextDialogOrder(),\n }\n : null,\n );\n }\n\n useEffect(() => {\n if (!isOpen || !isActive || !opening) {\n return;\n }\n const focusOptions = { preventScroll };\n const panel = panelRef.current;\n const dialog = openDialog(layer, opening.order);\n // Remembered per opening, so a new opening starts from its initial focus.\n const remember = (element: EventTarget | null) => {\n if (element instanceof HTMLElement) {\n lastFocused.current = { order: opening.order, element };\n }\n };\n const rememberFocus = ({ target }: FocusEvent) => remember(target);\n panel?.addEventListener(\"focusin\", rememberFocus);\n const active = document.activeElement;\n // Leave focus that autoFocus, the caller, or a popup resuming inside the\n // panel (its effects run first) already placed there.\n if (dialog.isTopmost() && panel && !panelHoldsFocus(panel, active)) {\n const previous = lastFocused.current;\n focusPanel(\n panel,\n previous?.order === opening.order ? previous.element : undefined,\n latest.current.initialFocus,\n focusOptions,\n );\n } else if (panel?.contains(active)) {\n // Focus placed before the listener was attached.\n remember(active);\n }\n\n const onKeyDown = (event: KeyboardEvent) => {\n // A nested picker, drawer or modal handles keys until it closes.\n if (!dialog.isTopmost()) {\n return;\n }\n if (event.key === \"Escape\") {\n // A popup inside the panel (Menu, Select, DateField) claims its Escape first.\n if (event.defaultPrevented || isComposing(event)) {\n return;\n }\n event.preventDefault();\n latest.current.onClose();\n return;\n }\n trapTabFocus(event, panelRef.current);\n };\n // On window, so popup handlers on the document and inside the panel run first.\n window.addEventListener(\"keydown\", onKeyDown);\n const unlockScroll = lockBodyScroll();\n\n return () => {\n panel?.removeEventListener(\"focusin\", rememberFocus);\n window.removeEventListener(\"keydown\", onKeyDown);\n dialog.close();\n unlockScroll();\n // Restore focus only when closing dropped it; the caller may already have placed it.\n if (cannotHoldFocus(document.activeElement)) {\n focusNearest(opening.opener, focusOptions);\n }\n };\n }, [isOpen, isActive, layer, opening, panelRef, preventScroll, container, latest]);\n\n /** Presses on the scrim itself close the dialog without moving focus first. */\n const onScrimMouseDown = (event: MouseEvent) => {\n if (isOpen && isActive && event.target === event.currentTarget) {\n event.preventDefault();\n latest.current.onClose();\n }\n };\n return { onScrimMouseDown, order: opening?.order };\n}\n","import type { AriaAttributes } from \"react\";\n\n/** Keep naming and visibility consistent across dialog frames, including suspended panels. */\nexport function dialogAttributes(\n props: AriaAttributes,\n titleId: string,\n descriptionId: string,\n hasDescription: boolean,\n active: boolean,\n) {\n return {\n role: \"dialog\" as const,\n \"aria-modal\": active || undefined,\n \"aria-hidden\": active ? props[\"aria-hidden\"] : true,\n \"aria-labelledby\": props[\"aria-label\"] ? undefined : (props[\"aria-labelledby\"] ?? titleId),\n \"aria-describedby\": hasDescription ? descriptionId : props[\"aria-describedby\"],\n };\n}\n"],"mappings":"A,8GAOA,SAAgBc,EAAkB,EAAmB,EAAsC,CAAC,EAAG,CAC7F,GAAI,OAAO,SAAa,IACtB,OAAO,KAET,IAAMC,EAAO,SAAS,cAAc,KAAK,EAGzC,MAFA,GAAK,UAAYC,EACjB,OAAO,OAAOD,EAAK,MAAOE,CAAK,EACxBF,CACT,CAEA,IAAMG,UAAwB,CAAC,EAO/B,SAAgBC,EAAe,EAAmB,EAAsC,CACtF,GAAM,CAACJ,IAAA,EAAQf,EAAAA,SAAAA,KAAec,EAAkBE,EAAWC,CAAK,CAAC,EAC3DG,GAAA,EAAWnB,EAAAA,qBAAAA,CACfiB,MACM,OACA,EACR,EAIA,OADA,EAAAL,EAAA,mBAAA,SAA+BE,GAAM,OAAO,EAAG,CAACA,CAAI,CAAC,EAC9CK,EAAWL,EAAO,IAC3B,CAOA,SAAgBM,EACd,EACA,EACA,EAA8B,KAC9B,CASA,OARKC,EAIDP,EAAK,aAAeO,IAGxBC,EAAWR,EAAMO,EAAM,KAAME,CAAW,EACjC,KAPLT,EAAK,OAAO,EACL,GAOX,CAOA,SAAgBQ,EACd,EACA,EACA,EACA,EAA8B,KAC9B,CACA,IAAME,EAAS,SAAS,cAClBC,EAAUD,GAAUV,EAAK,SAASU,CAAM,EAAIA,EAASD,EACrDG,EACJD,aAAmB,aACnBX,EAAK,SA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C7D,CACF,C"}
1
+ {"version":3,"file":"dialogLabel-_-MTckE_.cjs","names":["useState","useSyncExternalStore","cannotHoldFocus","useState","cannotHoldFocus","panelHoldsFocus","tabbableControls","useLatest","useState","useRef","isComposing","require_overlayLayer","require_isComposing","react","createMovableHost","host","className","style","subscribe","useMovableHost","hydrated","moveHost","slot","insertHost","lastFocused","active","focused","refocus","before","ranks","placement","others","parent","child","isLater","other","rank","useDialogPortal","setRank","order","isPresent","container","inPlace","stack","openings","nextDialogOrder","openDialog","entry","layer","locks","previous","lockBodyScroll","body","width","documentElement","scrollbar","padding","released","revealInPanel","area","control","panel","view","box","focusPanel","initialFocus","options","useModalDialog","latest","opening","setOpening","isOpen","isActive","focusOptions","panelRef","dialog","remember","element","rememberFocus","target","onKeyDown","event","unlockScroll","preventScroll","dialogAttributes","props","titleId","hasDescription","descriptionId"],"sources":["../../src/internal/movableHost.ts","../../src/internal/useDialogPortal.ts","../../src/internal/dialogStack.ts","../../src/internal/lockBodyScroll.ts","../../src/internal/useModalDialog.ts","../../src/internal/dialogLabel.ts"],"sourcesContent":["import { useInsertionEffect, useState, useSyncExternalStore } from \"react\";\nimport { cannotHoldFocus } from \"./dialogFocus\";\n\n/**\n * A detached element for portal content that moves between slots, so the tree\n * rendered into it never remounts. Null on the server.\n */\nexport function createMovableHost(className: string, style: Partial<CSSStyleDeclaration> = {}) {\n if (typeof document === \"undefined\") {\n return null;\n }\n const host = document.createElement(\"div\");\n host.className = className;\n Object.assign(host.style, style);\n return host;\n}\n\nconst subscribe = () => () => {};\n\n/**\n * A movable host for content that is also server rendered. It is null on the\n * server and while hydrating, so the first client render can match inline\n * server markup; client-only renders get the host on their first render.\n */\nexport function useMovableHost(className: string, style?: Partial<CSSStyleDeclaration>) {\n const [host] = useState(() => createMovableHost(className, style));\n const hydrated = useSyncExternalStore(\n subscribe,\n () => true,\n () => false,\n );\n // An insertion effect, which Strict Mode never replays: replaying a passive\n // cleanup would detach a host that an insertion effect placed.\n useInsertionEffect(() => () => host?.remove(), [host]);\n return hydrated ? host : null;\n}\n\n/**\n * Moves `host` into `slot`, or detaches it when there is no slot. A host already\n * in place is left alone: re-inserting it would reset scroll positions and drop\n * focus and the text selection. Returns whether the host moved.\n */\nexport function moveHost(\n host: HTMLElement,\n slot: Element | null,\n lastFocused: Element | null = null,\n) {\n if (!slot) {\n host.remove();\n return false;\n }\n if (host.parentNode === slot) {\n return false;\n }\n insertHost(host, slot, null, lastFocused);\n return true;\n}\n\n/**\n * Inserts `host` into `slot` before `before`, or at its end. Moving drops focus,\n * so the element inside the host that had it (or `lastFocused`, when an earlier\n * removal already dropped it) gets it back.\n */\nexport function insertHost(\n host: HTMLElement,\n slot: Element,\n before: Node | null,\n lastFocused: Element | null = null,\n) {\n const active = document.activeElement;\n const focused = active && host.contains(active) ? active : lastFocused;\n const refocus =\n focused instanceof HTMLElement &&\n host.contains(focused) &&\n (focused === active || cannotHoldFocus(active));\n slot.insertBefore(host, before);\n if (refocus) {\n focused.focus({ preventScroll: true });\n }\n}\n","import { useInsertionEffect, useState } from \"react\";\nimport { insertHost, useMovableHost } from \"./movableHost\";\n\n/** The opening order of each dialog's portal host. */\nconst ranks = new WeakMap<Element, number>();\n\n/**\n * Where `host` belongs among the other dialog hosts in `parent`: before the\n * first one opened later. It is in place when every host opened earlier comes\n * before it and every one opened later after it, whatever else lies between.\n */\nfunction placement(host: Element, parent: Element, rank: number) {\n const others = Array.from(parent.children).filter((child) => child !== host && ranks.has(child));\n const isLater = (other: Element) => (ranks.get(other) ?? 0) > rank;\n const inPlace =\n host.parentNode === parent &&\n others.every(\n (other) =>\n isLater(other) ===\n Boolean(host.compareDocumentPosition(other) & Node.DOCUMENT_POSITION_FOLLOWING),\n );\n return { inPlace, before: others.find(isLater) ?? null };\n}\n\n/**\n * A portal host that paints dialogs in opening order, as the dialog stack ranks\n * them, including a nested dialog that opens in the same commit as its parent\n * (React inserts that one's portal first). The host moves only when its order\n * is wrong, keeping focus, so a reopened dialog keeps its scroll and focus.\n * Null on the server and while hydrating.\n */\nexport function useDialogPortal(\n order: number | undefined,\n isPresent: boolean,\n container?: HTMLElement | null,\n) {\n // Kept through a closing transition, when the dialog no longer has an order.\n const [rank, setRank] = useState(order ?? 0);\n if (order !== undefined && order !== rank) {\n setRank(order);\n }\n // Contents only, so a contained drawer's container lays out the frame itself.\n const host = useMovableHost(\"ds-dialog-host\", { display: \"contents\" });\n // Before layout effects, so content measures and focuses inside the document.\n useInsertionEffect(() => {\n if (!host) {\n return;\n }\n if (!isPresent) {\n host.remove();\n return;\n }\n ranks.set(host, rank);\n const parent = container ?? document.body;\n const { inPlace, before } = placement(host, parent, rank);\n if (!inPlace) {\n insertHost(host, parent, before);\n }\n }, [host, rank, isPresent, container]);\n return host;\n}\n","interface Entry {\n layer: number;\n order: number;\n}\nconst stack = new Set<Entry>();\nlet openings = 0;\n\n/**\n * A dialog's place among those on its layer, taken as it opens and kept while\n * it is suspended. Taken during render, where a dialog renders before the ones\n * nested in it, so nested dialogs that open with it still come after it.\n */\nexport function nextDialogOrder() {\n openings += 1;\n return openings;\n}\n\n/**\n * Register an open modal dialog; only the topmost one handles keys. A higher\n * layer wins, then the later opening, matching paint order: portals append as\n * dialogs open. A dialog resuming from suspension keeps its opening order, so\n * it never jumps above dialogs opened while it was suspended.\n */\nexport function openDialog(layer: number, order: number) {\n const entry: Entry = { layer, order };\n stack.add(entry);\n return {\n isTopmost: () => {\n for (const other of stack) {\n if (other.layer > layer || (other.layer === layer && other.order > order)) {\n return false;\n }\n }\n return stack.has(entry);\n },\n close: () => {\n stack.delete(entry);\n },\n };\n}\n","let locks = 0;\nlet previous = { overflow: \"\", paddingRight: \"\" };\n\n/**\n * Nested dialogs may unmount in either order; restore scrolling after the last.\n * Hiding a classic scrollbar widens the page, so the body is padded by the\n * width it gave back and layouts that measure themselves keep their mode.\n */\nexport function lockBodyScroll() {\n const { body, documentElement } = document;\n if (locks === 0) {\n previous = { overflow: body.style.overflow, paddingRight: body.style.paddingRight };\n const width = documentElement.clientWidth;\n body.style.overflow = \"hidden\";\n const scrollbar = documentElement.clientWidth - width;\n if (scrollbar > 0) {\n const padding = parseFloat(getComputedStyle(body).paddingRight) || 0;\n body.style.paddingRight = `${padding + scrollbar}px`;\n }\n }\n locks += 1;\n let released = false;\n return () => {\n if (released) {\n return;\n }\n released = true;\n locks -= 1;\n if (locks > 0) {\n return;\n }\n body.style.overflow = previous.overflow;\n body.style.paddingRight = previous.paddingRight;\n };\n}\n","import { useEffect, useRef, useState, type MouseEvent, type RefObject } from \"react\";\nimport { nextDialogOrder, openDialog } from \"./dialogStack\";\nimport { lockBodyScroll } from \"./lockBodyScroll\";\nimport {\n cannotHoldFocus,\n focusNearest,\n panelHoldsFocus,\n tabbableControls,\n trapTabFocus,\n} from \"./dialogFocus\";\nimport { isComposing } from \"./isComposing\";\nimport { useLatest } from \"./useLatest\";\n\nexport interface ModalDialogOptions {\n isOpen: boolean;\n /** An inactive open dialog stays mounted but leaves keys, focus and scrim presses to others. */\n isActive?: boolean;\n layer?: number;\n panelRef: RefObject<HTMLElement | null>;\n /** Escape and a direct scrim press call this. Read when called, so it may change every render. */\n onClose: () => void;\n /** First focus when focus isn't already inside the panel. Defaults to the first tabbable control, then the panel. */\n initialFocus?: () => HTMLElement | null | undefined;\n /** Panels that slide in from off-screen must not scroll the page when focused. */\n preventScroll?: boolean;\n /** Registration restarts when this changes while open, such as a new portal container. */\n container?: unknown;\n}\n\ninterface Opening {\n opener: Element | null;\n order: number;\n}\n\n/** Scroll the panel's own scroll areas, never the page or the panel's host, until `control` shows. */\nfunction revealInPanel(panel: HTMLElement, control: HTMLElement) {\n for (let area = control.parentElement; area && panel.contains(area); area = area.parentElement) {\n if (area.scrollHeight > area.clientHeight) {\n const view = area.getBoundingClientRect();\n const box = control.getBoundingClientRect();\n if (box.top < view.top) {\n area.scrollTop -= view.top - box.top;\n } else if (box.bottom > view.bottom) {\n area.scrollTop += Math.min(box.bottom - view.bottom, box.top - view.top);\n }\n }\n }\n}\n\n/**\n * Return to the control focused last in this opening, else to the initial\n * focus. A suspended panel stays laid out, so its scroll areas keep their\n * positions; a restored control is still brought into view within the panel,\n * in case its content moved, leaving the page where it is.\n */\nfunction focusPanel(\n panel: HTMLElement,\n previous: HTMLElement | undefined,\n initialFocus: ModalDialogOptions[\"initialFocus\"],\n options: FocusOptions,\n) {\n if (previous && panel.contains(previous) && !cannotHoldFocus(previous)) {\n previous.focus({ preventScroll: true });\n }\n if (previous && document.activeElement === previous) {\n revealInPanel(panel, previous);\n } else if (!panelHoldsFocus(panel, document.activeElement)) {\n (initialFocus?.() ?? tabbableControls(panel)[0] ?? panel).focus(options);\n }\n}\n\n/**\n * Behaviour every modal overlay shares: one dialog-stack entry, a body scroll\n * lock, Escape and a Tab trap while topmost, initial focus, and focus returned\n * to the opener (or its nearest focusable container) when closing dropped it.\n */\nexport function useModalDialog({\n isOpen,\n isActive = true,\n layer = 60,\n panelRef,\n onClose,\n initialFocus,\n preventScroll = false,\n container,\n}: ModalDialogOptions) {\n const latest = useLatest({ onClose, initialFocus });\n // Captured as the dialog opens, before autoFocus or the caller moves focus\n // inside it, and before the dialogs nested in it render.\n const [opening, setOpening] = useState<Opening | null>(null);\n const lastFocused = useRef<{ order: number; element: HTMLElement } | null>(null);\n if ((opening !== null) !== isOpen) {\n setOpening(\n isOpen\n ? {\n opener: typeof document === \"undefined\" ? null : document.activeElement,\n order: nextDialogOrder(),\n }\n : null,\n );\n }\n\n useEffect(() => {\n if (!isOpen || !isActive || !opening) {\n return;\n }\n const focusOptions = { preventScroll };\n const panel = panelRef.current;\n const dialog = openDialog(layer, opening.order);\n // Remembered per opening, so a new opening starts from its initial focus.\n const remember = (element: EventTarget | null) => {\n if (element instanceof HTMLElement) {\n lastFocused.current = { order: opening.order, element };\n }\n };\n const rememberFocus = ({ target }: FocusEvent) => remember(target);\n panel?.addEventListener(\"focusin\", rememberFocus);\n const active = document.activeElement;\n // Leave focus that autoFocus, the caller, or a popup resuming inside the\n // panel (its effects run first) already placed there.\n if (dialog.isTopmost() && panel && !panelHoldsFocus(panel, active)) {\n const previous = lastFocused.current;\n focusPanel(\n panel,\n previous?.order === opening.order ? previous.element : undefined,\n latest.current.initialFocus,\n focusOptions,\n );\n } else if (panel?.contains(active)) {\n // Focus placed before the listener was attached.\n remember(active);\n }\n\n const onKeyDown = (event: KeyboardEvent) => {\n // A nested picker, drawer or modal handles keys until it closes.\n if (!dialog.isTopmost()) {\n return;\n }\n if (event.key === \"Escape\") {\n // A popup inside the panel (Menu, Select, DateField) claims its Escape first.\n if (event.defaultPrevented || isComposing(event)) {\n return;\n }\n event.preventDefault();\n latest.current.onClose();\n return;\n }\n trapTabFocus(event, panelRef.current);\n };\n // On window, so popup handlers on the document and inside the panel run first.\n window.addEventListener(\"keydown\", onKeyDown);\n const unlockScroll = lockBodyScroll();\n\n return () => {\n panel?.removeEventListener(\"focusin\", rememberFocus);\n window.removeEventListener(\"keydown\", onKeyDown);\n dialog.close();\n unlockScroll();\n // Restore focus only when closing dropped it; the caller may already have placed it.\n if (cannotHoldFocus(document.activeElement)) {\n focusNearest(opening.opener, focusOptions);\n }\n };\n }, [isOpen, isActive, layer, opening, panelRef, preventScroll, container, latest]);\n\n /** Presses on the scrim itself close the dialog without moving focus first. */\n const onScrimMouseDown = (event: MouseEvent) => {\n if (isOpen && isActive && event.target === event.currentTarget) {\n event.preventDefault();\n latest.current.onClose();\n }\n };\n return { onScrimMouseDown, order: opening?.order };\n}\n","import type { AriaAttributes } from \"react\";\n\n/** Keep naming and visibility consistent across dialog frames, including suspended panels. */\nexport function dialogAttributes(\n props: AriaAttributes,\n titleId: string,\n descriptionId: string,\n hasDescription: boolean,\n active: boolean,\n) {\n return {\n role: \"dialog\" as const,\n \"aria-modal\": active || undefined,\n \"aria-hidden\": active ? props[\"aria-hidden\"] : true,\n \"aria-labelledby\": props[\"aria-label\"] ? undefined : (props[\"aria-labelledby\"] ?? titleId),\n \"aria-describedby\": hasDescription ? descriptionId : props[\"aria-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