@blocknote/core 0.55.0 → 0.56.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/BlockNoteExtension-DjEkXkR5.cjs +2 -0
- package/dist/BlockNoteExtension-DjEkXkR5.cjs.map +1 -0
- package/dist/{BlockNoteExtension-CbvDA0F7.js → BlockNoteExtension-TsTGtIeX.js} +34 -27
- package/dist/BlockNoteExtension-TsTGtIeX.js.map +1 -0
- package/dist/{UserStore-mj3fXW4D.cjs → UserStore-CTVzVGh-.cjs} +2 -2
- package/dist/{UserStore-mj3fXW4D.cjs.map → UserStore-CTVzVGh-.cjs.map} +1 -1
- package/dist/{UserStore-C4TzkGEn.js → UserStore-OZJP3K8T.js} +2 -2
- package/dist/{UserStore-C4TzkGEn.js.map → UserStore-OZJP3K8T.js.map} +1 -1
- package/dist/blocknote.cjs +1 -1
- package/dist/blocknote.js +6 -6
- package/dist/blocks-COVwe5Cf.cjs +12 -0
- package/dist/blocks-COVwe5Cf.cjs.map +1 -0
- package/dist/{blocks-DaEUT0O1.js → blocks-COYcDVg7.js} +1572 -1156
- package/dist/blocks-COYcDVg7.js.map +1 -0
- package/dist/blocks.cjs +1 -1
- package/dist/blocks.js +2 -2
- package/dist/comments.cjs +1 -1
- package/dist/comments.js +12 -12
- package/dist/{en-BAn9gxr-.js → en-Ch-vvt5e.js} +36 -2
- package/dist/en-Ch-vvt5e.js.map +1 -0
- package/dist/en-N5lu0-j8.cjs +2 -0
- package/dist/en-N5lu0-j8.cjs.map +1 -0
- package/dist/extensions-BbM81hHa.js +3069 -0
- package/dist/extensions-BbM81hHa.js.map +1 -0
- package/dist/extensions-D_WkAfSt.cjs +58 -0
- package/dist/extensions-D_WkAfSt.cjs.map +1 -0
- package/dist/extensions.cjs +1 -1
- package/dist/extensions.js +4 -4
- package/dist/locales.cjs +1 -1
- package/dist/locales.cjs.map +1 -1
- package/dist/locales.js +771 -23
- package/dist/locales.js.map +1 -1
- package/dist/src-4OQT3z5S.cjs +23 -0
- package/dist/src-4OQT3z5S.cjs.map +1 -0
- package/dist/{src-D5w0XAHX.js → src-BmLsLZfE.js} +1390 -1278
- package/dist/src-BmLsLZfE.js.map +1 -0
- package/dist/style.css +1 -1
- package/dist/webpack-stats.json +1 -1
- package/dist/y.cjs +1 -1
- package/dist/y.cjs.map +1 -1
- package/dist/y.js +1284 -554
- package/dist/y.js.map +1 -1
- package/dist/yjs.cjs +1 -1
- package/dist/yjs.cjs.map +1 -1
- package/dist/yjs.js +189 -148
- package/dist/yjs.js.map +1 -1
- package/package.json +8 -8
- package/src/api/blockManipulation/commands/insertBlocks/insertBlocks.ts +45 -6
- package/src/api/blockManipulation/commands/insertBlocks/insertPlacement.test.ts +217 -0
- package/src/api/blockManipulation/commands/mergeBlocks/mergeBlocks.test.ts +113 -9
- package/src/api/blockManipulation/commands/mergeBlocks/mergeBlocks.ts +151 -163
- package/src/api/blockManipulation/commands/moveBlocks/moveBlocks.test.ts +47 -31
- package/src/api/blockManipulation/commands/moveBlocks/moveBlocks.ts +122 -181
- package/src/api/blockManipulation/commands/nestBlock/nestBlock.test.ts +256 -0
- package/src/api/blockManipulation/commands/nestBlock/nestBlock.ts +80 -40
- package/src/api/blockManipulation/commands/replaceBlocks/replaceBlocks.test.ts +71 -0
- package/src/api/blockManipulation/commands/replaceBlocks/replaceBlocks.ts +39 -31
- package/src/api/blockManipulation/commands/splitBlock/splitBlock.test.ts +221 -8
- package/src/api/blockManipulation/commands/splitBlock/splitBlock.ts +40 -8
- package/src/api/blockManipulation/commands/updateBlock/updateBlock.test.ts +272 -40
- package/src/api/blockManipulation/commands/updateBlock/updateBlock.ts +138 -117
- package/src/api/blockManipulation/getBlock/getBlock.ts +4 -11
- package/src/api/blockManipulation/layoutBlocks/fixLayoutBlock.ts +173 -0
- package/src/api/blockManipulation/layoutBlocks/layoutBlocks.browser.test.ts +293 -0
- package/src/api/blockManipulation/layoutBlocks/layoutBlocks.fixture.ts +145 -0
- package/src/api/blockManipulation/layoutBlocks/layoutBlocks.test.ts +783 -0
- package/src/api/blockManipulation/layoutBlocks/plainBlocks.test.ts +180 -0
- package/src/api/blockManipulation/layoutBlocks/titledBlocks.test.ts +365 -0
- package/src/api/blockManipulation/selections/selection.ts +20 -53
- package/src/api/blockManipulation/selections/textCursorPosition.ts +17 -72
- package/src/api/blockManipulation/setupTestEnv.ts +38 -6
- package/src/api/clipboard/fromClipboard/handleFileInsertion.ts +4 -4
- package/src/api/clipboard/toClipboard/copyExtension.ts +3 -3
- package/src/api/combineTransactionSteps.ts +22 -0
- package/src/api/exporters/html/externalHTMLExporter.ts +1 -1
- package/src/api/exporters/html/internalHTMLSerializer.ts +4 -4
- package/src/api/exporters/html/util/serializeBlocksExternalHTML.ts +111 -36
- package/src/api/exporters/html/util/serializeBlocksInternalHTML.ts +51 -21
- package/src/api/exporters/markdown/htmlToMarkdown.ts +12 -1
- package/src/api/exporters/markdown/markdownExporter.ts +1 -1
- package/src/api/getBlockInfoFromPos.test.ts +428 -3
- package/src/api/getBlockInfoFromPos.ts +531 -129
- package/src/api/getBlocksChangedByTransaction.test.ts +7 -7
- package/src/api/getBlocksChangedByTransaction.ts +3 -3
- package/src/api/{getChangedRange.ts → getChangedRangeWithAttrs.ts} +2 -2
- package/src/api/getChangedRanges.test.ts +391 -0
- package/src/api/getChangedRanges.ts +368 -0
- package/src/api/nodeConversions/blockToNode.ts +44 -16
- package/src/api/nodeConversions/fragmentToBlocks.ts +29 -44
- package/src/api/nodeConversions/nodeToBlock.ts +120 -68
- package/src/api/nodeUtil.ts +1 -1
- package/src/api/parsers/markdown/autolink.ts +23 -0
- package/src/api/parsers/markdown/markdownToHtml.ts +115 -11
- package/src/blocks/Code/block.test.ts +4 -4
- package/src/blocks/Code/helpers/extensions/CodeKeyboardShortcutsExtension.ts +6 -1
- package/src/blocks/Heading/block.ts +54 -15
- package/src/blocks/ListItem/BulletListItem/block.ts +6 -4
- package/src/blocks/ListItem/CheckListItem/block.test.ts +2 -2
- package/src/blocks/ListItem/CheckListItem/block.ts +6 -4
- package/src/blocks/ListItem/NumberedListItem/IndexingPlugin.ts +14 -17
- package/src/blocks/ListItem/NumberedListItem/block.ts +6 -4
- package/src/blocks/ListItem/ToggleListItem/block.ts +23 -12
- package/src/blocks/Table/block.ts +2 -10
- package/src/blocks/ToggleWrapper/createToggleFrame.ts +126 -0
- package/src/blocks/ToggleWrapper/toggleBlocks.browser.test.ts +1056 -0
- package/src/blocks/defaultBlockTypeItems.test.ts +70 -0
- package/src/blocks/defaultBlockTypeItems.ts +99 -0
- package/src/blocks/defaultBlocks.test.ts +67 -0
- package/src/blocks/defaultBlocks.ts +7 -1
- package/src/blocks/index.ts +2 -1
- package/src/editor/Block.css +286 -154
- package/src/editor/BlockNoteEditor.node.test.ts +35 -0
- package/src/editor/BlockNoteEditor.test.ts +2 -2
- package/src/editor/BlockNoteEditor.ts +71 -9
- package/src/editor/BlockNoteExtension.ts +5 -5
- package/src/editor/blockColors.browser.test.ts +127 -0
- package/src/editor/editor.css +60 -0
- package/src/editor/managers/BlockManager.ts +4 -3
- package/src/editor/managers/ExtensionManager/ExtensionManager.browser.test.ts +45 -0
- package/src/editor/managers/ExtensionManager/ExtensionManager.node.test.ts +209 -0
- package/src/editor/managers/ExtensionManager/extensions.ts +10 -1
- package/src/editor/managers/ExtensionManager/index.ts +135 -68
- package/src/editor/managers/StateManager.ts +14 -4
- package/src/editor/transformPasted.ts +14 -13
- package/src/exporter/Exporter.test.ts +70 -1
- package/src/exporter/Exporter.ts +34 -4
- package/src/exporter/mapping.ts +41 -10
- package/src/extensions/DropCursor/DropCursor.ts +119 -6
- package/src/extensions/DropCursor/dropIntoChildren.ts +80 -0
- package/src/extensions/FormattingToolbar/FormattingToolbar.ts +7 -1
- package/src/extensions/NodeSelectionKeyboard/NodeSelectionKeyboard.test.ts +190 -0
- package/src/extensions/NodeSelectionKeyboard/NodeSelectionKeyboard.ts +41 -4
- package/src/extensions/Placeholder/Placeholder.test.ts +23 -0
- package/src/extensions/Placeholder/Placeholder.ts +8 -7
- package/src/extensions/PreviousBlockType/PreviousBlockType.test.ts +36 -0
- package/src/extensions/PreviousBlockType/PreviousBlockType.ts +8 -4
- package/src/extensions/ReadOnly/ReadOnly.test.ts +181 -0
- package/src/extensions/ReadOnly/ReadOnly.ts +73 -0
- package/src/extensions/SideMenu/SideMenu.ts +401 -764
- package/src/extensions/SideMenu/blockDropHandling.ts +372 -0
- package/src/extensions/SideMenu/blockGeometry.browser.test.ts +148 -0
- package/src/extensions/SideMenu/blockGeometry.test.ts +46 -0
- package/src/extensions/SideMenu/blockGeometry.ts +53 -0
- package/src/extensions/SideMenu/dragging.ts +19 -32
- package/src/extensions/SideMenu/sideMenuHover.test.ts +36 -0
- package/src/extensions/SideMenu/sideMenuHover.ts +270 -0
- package/src/extensions/SourceBlockWithPreview/SourceBlockWithPreview.ts +5 -4
- package/src/extensions/SuggestionMenu/SuggestionMenu.ts +10 -1
- package/src/extensions/SuggestionMenu/getDefaultSlashMenuItems.ts +36 -136
- package/src/extensions/SyntaxHighlighting/SyntaxHighlighting.test.ts +14 -4
- package/src/extensions/SyntaxHighlighting/SyntaxHighlighting.ts +1 -1
- package/src/extensions/SyntaxHighlighting/shiki.ts +1 -1
- package/src/extensions/TableHandles/TableHandles.ts +4 -6
- package/src/extensions/Versioning/Versioning.browser.test.ts +151 -0
- package/src/extensions/Versioning/Versioning.node.test.ts +177 -0
- package/src/extensions/Versioning/Versioning.ts +145 -612
- package/src/extensions/Versioning/__test__/result.ts +12 -0
- package/src/extensions/Versioning/comparison.test.ts +40 -0
- package/src/extensions/Versioning/createVersioning.test.ts +867 -0
- package/src/extensions/Versioning/createVersioning.ts +499 -0
- package/src/extensions/Versioning/formatVersionDate.ts +24 -0
- package/src/extensions/Versioning/inMemoryVersioning.test.ts +533 -430
- package/src/extensions/Versioning/inMemoryVersioning.ts +246 -251
- package/src/extensions/Versioning/index.ts +4 -0
- package/src/extensions/Versioning/scrollScheduling.test.ts +51 -0
- package/src/extensions/Versioning/scrollToFirstChange.test.ts +320 -0
- package/src/extensions/Versioning/scrollToFirstChange.ts +139 -0
- package/src/extensions/Versioning/types.ts +219 -0
- package/src/extensions/Versioning/versioningState.ts +154 -0
- package/src/extensions/blockDOM.browser.test.ts +102 -0
- package/src/extensions/blockDOM.test.ts +178 -0
- package/src/extensions/blockDOM.ts +135 -0
- package/src/extensions/index.ts +2 -0
- package/src/extensions/tiptap-extensions/KeyboardShortcuts/KeyboardShortcutsExtension.test.ts +1719 -53
- package/src/extensions/tiptap-extensions/KeyboardShortcuts/KeyboardShortcutsExtension.ts +645 -531
- package/src/extensions/tiptap-extensions/KeyboardShortcuts/blockIdentity.browser.test.ts +152 -0
- package/src/extensions/tiptap-extensions/Link/helpers/autolink.ts +4 -9
- package/src/extensions/tiptap-extensions/UniqueID/UniqueID.test.ts +10 -24
- package/src/extensions/tiptap-extensions/UniqueID/UniqueID.ts +22 -19
- package/src/fonts/inter.browser.test.ts +57 -0
- package/src/fonts/inter.css +111 -0
- package/src/i18n/locales/ar.ts +32 -0
- package/src/i18n/locales/de.ts +32 -0
- package/src/i18n/locales/en.ts +32 -0
- package/src/i18n/locales/es.ts +32 -0
- package/src/i18n/locales/fa.ts +32 -0
- package/src/i18n/locales/fr.ts +32 -0
- package/src/i18n/locales/he.ts +32 -0
- package/src/i18n/locales/hr.ts +32 -0
- package/src/i18n/locales/is.ts +32 -0
- package/src/i18n/locales/it.ts +32 -0
- package/src/i18n/locales/ja.ts +32 -0
- package/src/i18n/locales/ko.ts +32 -0
- package/src/i18n/locales/nl.ts +32 -0
- package/src/i18n/locales/no.ts +32 -0
- package/src/i18n/locales/pl.ts +32 -0
- package/src/i18n/locales/pt.ts +32 -0
- package/src/i18n/locales/ru.ts +32 -0
- package/src/i18n/locales/sk.ts +32 -0
- package/src/i18n/locales/uk.ts +32 -0
- package/src/i18n/locales/uz.ts +32 -0
- package/src/i18n/locales/vi.ts +32 -0
- package/src/i18n/locales/zh-tw.ts +32 -0
- package/src/i18n/locales/zh.ts +32 -0
- package/src/index.ts +13 -3
- package/src/pm-nodes/BlockContainer.test.ts +101 -0
- package/src/pm-nodes/BlockContainer.ts +110 -1
- package/src/pm-nodes/BlockGroup.ts +2 -1
- package/src/pm-nodes/README.md +2 -0
- package/src/schema/blocks/children.test.ts +288 -0
- package/src/schema/blocks/children.ts +136 -0
- package/src/schema/blocks/createSpec.browser.test.ts +176 -0
- package/src/schema/blocks/createSpec.test.ts +231 -0
- package/src/schema/blocks/createSpec.ts +493 -267
- package/src/schema/blocks/frame.test.ts +112 -0
- package/src/schema/blocks/frame.ts +337 -0
- package/src/schema/blocks/internal.ts +50 -17
- package/src/schema/blocks/keyboard.ts +154 -0
- package/src/schema/blocks/layoutBlockAttributes.ts +29 -0
- package/src/schema/blocks/meta.test.ts +53 -0
- package/src/schema/blocks/meta.ts +35 -0
- package/src/schema/blocks/renderFrame.test.ts +691 -0
- package/src/schema/blocks/types.ts +285 -21
- package/src/schema/blocks/validateChildren.ts +156 -0
- package/src/schema/dataAttributes.test.ts +72 -0
- package/src/schema/dataAttributes.ts +69 -0
- package/src/schema/index.ts +3 -0
- package/src/schema/inlineContent/internal.ts +7 -12
- package/src/schema/markGroups.ts +34 -2
- package/src/schema/schema.ts +8 -1
- package/src/user/userColors.test.ts +108 -0
- package/src/user/userColors.ts +42 -13
- package/src/y/comments/RESTYjsThreadStore.ts +1 -1
- package/src/y/comments/YjsThreadStore.test.ts +1 -1
- package/src/y/comments/YjsThreadStore.ts +27 -27
- package/src/y/comments/YjsThreadStoreBase.ts +2 -2
- package/src/y/comments/yjsHelpers.ts +11 -11
- package/src/y/extensions/AttributionExtension.test.ts +271 -2
- package/src/y/extensions/AttributionExtension.ts +146 -123
- package/src/y/extensions/DiffVersioningExtension.test.ts +67 -18
- package/src/y/extensions/DiffVersioningExtension.ts +95 -123
- package/src/y/extensions/EmptyDocBinding.test.ts +282 -0
- package/src/y/extensions/ForkYDoc.node.test.ts +77 -0
- package/src/y/extensions/ForkYDoc.test.ts +93 -2
- package/src/y/extensions/ForkYDoc.ts +22 -13
- package/src/y/extensions/History.test.ts +125 -0
- package/src/y/extensions/RelativePositionMapping.test.ts +35 -0
- package/src/y/extensions/RelativePositionMapping.ts +7 -11
- package/src/y/extensions/Versioning.node.test.ts +126 -0
- package/src/y/extensions/Versioning.test.ts +110 -401
- package/src/y/extensions/Versioning.ts +66 -107
- package/src/y/extensions/YAttributionMarks.ts +111 -9
- package/src/y/extensions/YCursorPlugin.ts +3 -0
- package/src/y/extensions/YSync.node.test.ts +75 -0
- package/src/y/extensions/YSync.ts +76 -4
- package/src/y/extensions/YSyncRemount.test.ts +99 -0
- package/src/y/extensions/blockMatchNodes.ts +20 -29
- package/src/y/extensions/index.ts +10 -26
- package/src/y/extensions/legacyYjsDocBinding.test.ts +652 -0
- package/src/y/extensions/nestingChanges.test.ts +326 -0
- package/src/y/extensions/persistentBlockGroups.test.ts +1709 -0
- package/src/y/extensions/persistentBlockGroups.ts +953 -0
- package/src/y/extensions/snapshotCodec.test.ts +105 -0
- package/src/y/extensions/snapshotCodec.ts +39 -0
- package/src/y/extensions/snapshotPreview.test.ts +201 -0
- package/src/y/extensions/snapshotPreview.ts +292 -0
- package/src/y/extensions/tableReshape.test.ts +121 -0
- package/src/y/extensions/v1BindingSnapshotDiff.test.ts +121 -0
- package/src/y/extensions/versionDiffAttribution.test.ts +944 -0
- package/src/y/extensions/versionDiffPerformance.test.ts +101 -0
- package/src/y/index.ts +1 -0
- package/src/y/utils.test.ts +289 -22
- package/src/y/utils.ts +167 -43
- package/src/y/versioning/__test__/fixtures/activity-all-after.json +5 -5
- package/src/y/versioning/__test__/fixtures/activity-all.json +3 -3
- package/src/y/versioning/__test__/fixtures/activity-filtered-after.json +2 -2
- package/src/y/versioning/__test__/yhub.test.ts +902 -721
- package/src/y/versioning/index.ts +6 -1
- package/src/y/versioning/yhub.ts +316 -603
- package/src/y/versioning/yhubClient.ts +345 -0
- package/src/yjs/comments/RESTYjsThreadStore.test.ts +10 -0
- package/src/yjs/extensions/FixUpSchema.ts +11 -0
- package/src/yjs/extensions/ForkYDoc.browser.test.ts +84 -0
- package/src/yjs/extensions/ForkYDoc.node.test.ts +231 -0
- package/src/yjs/extensions/ForkYDoc.test.ts +68 -1
- package/src/yjs/extensions/ForkYDoc.ts +57 -39
- package/src/yjs/extensions/Versioning.test.ts +345 -530
- package/src/yjs/extensions/Versioning.ts +111 -68
- package/src/yjs/extensions/index.ts +1 -1
- package/src/yjs/index.ts +4 -0
- package/types/src/api/blockManipulation/commands/insertBlocks/insertBlocks.d.ts +2 -1
- package/types/src/api/blockManipulation/commands/mergeBlocks/mergeBlocks.d.ts +24 -24
- package/types/src/api/blockManipulation/commands/nestBlock/nestBlock.d.ts +3 -2
- package/types/src/api/blockManipulation/commands/replaceBlocks/replaceBlocks.d.ts +1 -1
- package/types/src/api/blockManipulation/commands/splitBlock/splitBlock.d.ts +2 -2
- package/types/src/api/blockManipulation/layoutBlocks/fixLayoutBlock.d.ts +34 -0
- package/types/src/api/blockManipulation/layoutBlocks/layoutBlocks.browser.test.d.ts +1 -0
- package/types/src/api/blockManipulation/layoutBlocks/layoutBlocks.fixture.d.ts +460 -0
- package/types/src/api/blockManipulation/layoutBlocks/layoutBlocks.test.d.ts +1 -0
- package/types/src/api/blockManipulation/layoutBlocks/plainBlocks.test.d.ts +1 -0
- package/types/src/api/blockManipulation/layoutBlocks/titledBlocks.test.d.ts +1 -0
- package/types/src/api/blockManipulation/setupTestEnv.d.ts +15 -69
- package/types/src/api/combineTransactionSteps.d.ts +12 -0
- package/types/src/api/getBlockInfoFromPos.d.ts +218 -44
- package/types/src/api/{getChangedRange.d.ts → getChangedRangeWithAttrs.d.ts} +1 -1
- package/types/src/api/getChangedRanges.d.ts +23 -0
- package/types/src/api/getChangedRanges.test.d.ts +1 -0
- package/types/src/api/nodeConversions/fragmentToBlocks.d.ts +0 -3
- package/types/src/api/parsers/markdown/autolink.d.ts +5 -0
- package/types/src/blocks/ToggleWrapper/createToggleFrame.d.ts +29 -0
- package/types/src/blocks/ToggleWrapper/toggleBlocks.browser.test.d.ts +1 -0
- package/types/src/blocks/defaultBlockTypeItems.d.ts +37 -0
- package/types/src/blocks/defaultBlockTypeItems.test.d.ts +1 -0
- package/types/src/blocks/defaultBlocks.test.d.ts +1 -0
- package/types/src/blocks/index.d.ts +2 -1
- package/types/src/editor/BlockNoteEditor.d.ts +36 -8
- package/types/src/editor/BlockNoteEditor.node.test.d.ts +1 -0
- package/types/src/editor/blockColors.browser.test.d.ts +1 -0
- package/types/src/editor/managers/BlockManager.d.ts +4 -3
- package/types/src/editor/managers/ExtensionManager/ExtensionManager.browser.test.d.ts +1 -0
- package/types/src/editor/managers/ExtensionManager/ExtensionManager.node.test.d.ts +1 -0
- package/types/src/editor/managers/ExtensionManager/index.d.ts +15 -3
- package/types/src/editor/managers/StateManager.d.ts +1 -1
- package/types/src/editor/transformPasted.d.ts +1 -1
- package/types/src/exporter/Exporter.d.ts +11 -4
- package/types/src/exporter/mapping.d.ts +13 -1
- package/types/src/extensions/DropCursor/DropCursor.d.ts +1 -1
- package/types/src/extensions/DropCursor/dropIntoChildren.d.ts +38 -0
- package/types/src/extensions/NodeSelectionKeyboard/NodeSelectionKeyboard.d.ts +1 -1
- package/types/src/extensions/NodeSelectionKeyboard/NodeSelectionKeyboard.test.d.ts +1 -0
- package/types/src/extensions/Placeholder/Placeholder.test.d.ts +1 -0
- package/types/src/extensions/ReadOnly/ReadOnly.d.ts +21 -0
- package/types/src/extensions/ReadOnly/ReadOnly.test.d.ts +1 -0
- package/types/src/extensions/SideMenu/SideMenu.d.ts +49 -88
- package/types/src/extensions/SideMenu/blockDropHandling.d.ts +11 -0
- package/types/src/extensions/SideMenu/blockGeometry.browser.test.d.ts +1 -0
- package/types/src/extensions/SideMenu/blockGeometry.d.ts +22 -0
- package/types/src/extensions/SideMenu/blockGeometry.test.d.ts +1 -0
- package/types/src/extensions/SideMenu/dragging.d.ts +0 -4
- package/types/src/extensions/SideMenu/sideMenuHover.d.ts +58 -0
- package/types/src/extensions/SideMenu/sideMenuHover.test.d.ts +1 -0
- package/types/src/extensions/Versioning/Versioning.browser.test.d.ts +1 -0
- package/types/src/extensions/Versioning/Versioning.d.ts +34 -311
- package/types/src/extensions/Versioning/Versioning.node.test.d.ts +1 -0
- package/types/src/extensions/Versioning/__test__/result.d.ts +3 -0
- package/types/src/extensions/Versioning/comparison.test.d.ts +1 -0
- package/types/src/extensions/Versioning/createVersioning.d.ts +32 -0
- package/types/src/extensions/Versioning/createVersioning.test.d.ts +1 -0
- package/types/src/extensions/Versioning/formatVersionDate.d.ts +7 -0
- package/types/src/extensions/Versioning/inMemoryVersioning.d.ts +64 -36
- package/types/src/extensions/Versioning/index.d.ts +4 -0
- package/types/src/extensions/Versioning/scrollScheduling.test.d.ts +1 -0
- package/types/src/extensions/Versioning/scrollToFirstChange.d.ts +18 -0
- package/types/src/extensions/Versioning/scrollToFirstChange.test.d.ts +1 -0
- package/types/src/extensions/Versioning/types.d.ts +239 -0
- package/types/src/extensions/Versioning/versioningState.d.ts +43 -0
- package/types/src/extensions/blockDOM.browser.test.d.ts +1 -0
- package/types/src/extensions/blockDOM.d.ts +37 -0
- package/types/src/extensions/blockDOM.test.d.ts +1 -0
- package/types/src/extensions/index.d.ts +2 -0
- package/types/src/extensions/tiptap-extensions/KeyboardShortcuts/KeyboardShortcutsExtension.d.ts +1 -0
- package/types/src/extensions/tiptap-extensions/KeyboardShortcuts/KeyboardShortcutsExtension.test.d.ts +3 -0
- package/types/src/extensions/tiptap-extensions/KeyboardShortcuts/blockIdentity.browser.test.d.ts +1 -0
- package/types/src/fonts/inter.browser.test.d.ts +2 -0
- package/types/src/i18n/locales/en.d.ts +32 -0
- package/types/src/i18n/locales/fa.d.ts +32 -0
- package/types/src/i18n/locales/sk.d.ts +32 -0
- package/types/src/index.d.ts +6 -3
- package/types/src/pm-nodes/BlockContainer.d.ts +6 -0
- package/types/src/pm-nodes/BlockContainer.test.d.ts +1 -0
- package/types/src/schema/blocks/children.d.ts +39 -0
- package/types/src/schema/blocks/children.test.d.ts +1 -0
- package/types/src/schema/blocks/createSpec.browser.test.d.ts +1 -0
- package/types/src/schema/blocks/createSpec.d.ts +13 -0
- package/types/src/schema/blocks/frame.d.ts +109 -0
- package/types/src/schema/blocks/frame.test.d.ts +1 -0
- package/types/src/schema/blocks/internal.d.ts +6 -0
- package/types/src/schema/blocks/keyboard.d.ts +111 -0
- package/types/src/schema/blocks/layoutBlockAttributes.d.ts +9 -0
- package/types/src/schema/blocks/meta.d.ts +14 -0
- package/types/src/schema/blocks/meta.test.d.ts +1 -0
- package/types/src/schema/blocks/renderFrame.test.d.ts +1 -0
- package/types/src/schema/blocks/types.d.ts +228 -15
- package/types/src/schema/blocks/validateChildren.d.ts +5 -0
- package/types/src/schema/dataAttributes.d.ts +19 -0
- package/types/src/schema/dataAttributes.test.d.ts +1 -0
- package/types/src/schema/index.d.ts +3 -0
- package/types/src/schema/markGroups.d.ts +8 -0
- package/types/src/user/userColors.d.ts +24 -3
- package/types/src/user/userColors.test.d.ts +1 -0
- package/types/src/y/comments/RESTYjsThreadStore.d.ts +1 -1
- package/types/src/y/comments/YjsThreadStore.d.ts +1 -1
- package/types/src/y/comments/YjsThreadStoreBase.d.ts +2 -2
- package/types/src/y/comments/yjsHelpers.d.ts +5 -5
- package/types/src/y/extensions/AttributionExtension.d.ts +19 -21
- package/types/src/y/extensions/DiffVersioningExtension.d.ts +9 -4
- package/types/src/y/extensions/EmptyDocBinding.test.d.ts +1 -0
- package/types/src/y/extensions/ForkYDoc.d.ts +3 -1
- package/types/src/y/extensions/ForkYDoc.node.test.d.ts +1 -0
- package/types/src/y/extensions/History.test.d.ts +1 -0
- package/types/src/y/extensions/Versioning.d.ts +4 -15
- package/types/src/y/extensions/Versioning.node.test.d.ts +1 -0
- package/types/src/y/extensions/YAttributionMarks.d.ts +13 -2
- package/types/src/y/extensions/YCursorPlugin.d.ts +1 -0
- package/types/src/y/extensions/YSync.d.ts +4 -18
- package/types/src/y/extensions/YSync.node.test.d.ts +1 -0
- package/types/src/y/extensions/YSyncRemount.test.d.ts +1 -0
- package/types/src/y/extensions/blockMatchNodes.d.ts +0 -22
- package/types/src/y/extensions/index.d.ts +27 -44
- package/types/src/y/extensions/legacyYjsDocBinding.test.d.ts +1 -0
- package/types/src/y/extensions/nestingChanges.test.d.ts +1 -0
- package/types/src/y/extensions/persistentBlockGroups.d.ts +189 -0
- package/types/src/y/extensions/persistentBlockGroups.test.d.ts +1 -0
- package/types/src/y/extensions/snapshotCodec.d.ts +13 -0
- package/types/src/y/extensions/snapshotCodec.test.d.ts +1 -0
- package/types/src/y/extensions/snapshotPreview.d.ts +21 -0
- package/types/src/y/extensions/snapshotPreview.test.d.ts +1 -0
- package/types/src/y/extensions/tableReshape.test.d.ts +1 -0
- package/types/src/y/extensions/v1BindingSnapshotDiff.test.d.ts +1 -0
- package/types/src/y/extensions/versionDiffAttribution.test.d.ts +1 -0
- package/types/src/y/extensions/versionDiffPerformance.test.d.ts +1 -0
- package/types/src/y/index.d.ts +1 -0
- package/types/src/y/utils.d.ts +39 -19
- package/types/src/y/versioning/index.d.ts +1 -1
- package/types/src/y/versioning/yhub.d.ts +69 -86
- package/types/src/y/versioning/yhubClient.d.ts +67 -0
- package/types/src/yjs/extensions/ForkYDoc.browser.test.d.ts +1 -0
- package/types/src/yjs/extensions/ForkYDoc.d.ts +2 -0
- package/types/src/yjs/extensions/ForkYDoc.node.test.d.ts +1 -0
- package/types/src/yjs/extensions/Versioning.d.ts +36 -22
- package/types/src/yjs/extensions/index.d.ts +2 -1
- package/types/src/yjs/index.d.ts +1 -0
- package/dist/BlockNoteExtension-BJCLnwrE.cjs +0 -2
- package/dist/BlockNoteExtension-BJCLnwrE.cjs.map +0 -1
- package/dist/BlockNoteExtension-CbvDA0F7.js.map +0 -1
- package/dist/blocks-DLgTreVu.cjs +0 -12
- package/dist/blocks-DLgTreVu.cjs.map +0 -1
- package/dist/blocks-DaEUT0O1.js.map +0 -1
- package/dist/en-BAn9gxr-.js.map +0 -1
- package/dist/en-CHnrV5l8.cjs +0 -2
- package/dist/en-CHnrV5l8.cjs.map +0 -1
- package/dist/extensions-B1JQURVF.js +0 -2138
- package/dist/extensions-B1JQURVF.js.map +0 -1
- package/dist/extensions-CZkqKzJO.cjs +0 -58
- package/dist/extensions-CZkqKzJO.cjs.map +0 -1
- package/dist/src-D5w0XAHX.js.map +0 -1
- package/dist/src-th5uZEvx.cjs +0 -23
- package/dist/src-th5uZEvx.cjs.map +0 -1
- package/src/api/blockManipulation/commands/replaceBlocks/util/fixColumnList.ts +0 -173
- package/src/blocks/ListItem/ListItemKeyboardShortcuts.ts +0 -63
- package/src/blocks/ToggleWrapper/createToggleWrapper.ts +0 -197
- package/src/blocks/utils/listItemEnterHandler.ts +0 -43
- package/src/extensions/Versioning/Versioning.test.ts +0 -435
- package/src/extensions/getDraggableBlockFromElement.ts +0 -19
- package/types/src/api/blockManipulation/commands/replaceBlocks/util/fixColumnList.d.ts +0 -32
- package/types/src/blocks/ListItem/ListItemKeyboardShortcuts.d.ts +0 -2
- package/types/src/blocks/ToggleWrapper/createToggleWrapper.d.ts +0 -15
- package/types/src/blocks/utils/listItemEnterHandler.d.ts +0 -2
- package/types/src/extensions/getDraggableBlockFromElement.d.ts +0 -5
- /package/types/src/{extensions/Versioning/Versioning.test.d.ts → api/blockManipulation/commands/insertBlocks/insertPlacement.test.d.ts} +0 -0
package/dist/y.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"y.js","names":[],"sources":["../src/y/extensions/YAttributionMarks.ts","../src/y/extensions/AttributionExtension.ts","../src/y/extensions/RelativePositionMapping.ts","../src/y/extensions/blockMatchNodes.ts","../src/y/extensions/YSync.ts","../src/y/utils.ts","../src/y/extensions/Suggestions.ts","../src/y/extensions/Versioning.ts","../src/y/extensions/YCursorPlugin.ts","../src/y/extensions/DiffVersioningExtension.ts","../src/y/extensions/index.ts","../src/y/comments/yjsHelpers.ts","../src/y/comments/YjsThreadStoreBase.ts","../src/y/comments/RESTYjsThreadStore.ts","../src/y/comments/YjsThreadStore.ts","../src/y/versioning/yhub.ts"],"sourcesContent":["import { Mark } from \"@tiptap/core\";\nimport { Mark as PMMark, MarkSpec } from \"prosemirror-model\";\nimport {\n createExtension,\n type ExtensionOptions,\n} from \"../../editor/BlockNoteExtension.js\";\nimport type { BlockNoteEditor } from \"../../editor/BlockNoteEditor.js\";\nimport { BLOCK_LEVEL_SUGGESTION_GROUP } from \"../../pm-nodes/suggestionMarks.js\";\nimport { NON_FORMATTING_MARK_GROUP } from \"../../schema/markGroups.js\";\nimport {\n fallbackColorForUserId,\n userColorPalette,\n userColorVarNames,\n} from \"../../user/index.js\";\n\n/**\n * Describes a suggestion mark to {@link GetAttributionMarkClassName}: whether it\n * wraps inline content or a whole block, and which kind of change it represents.\n * `modificationType: \"format\"` corresponds to the `y-attributed-format`\n * (modification) mark.\n */\nexport type AttributionMarkStyleInfo = {\n contentType: \"inline-content\" | \"block\";\n modificationType: \"insert\" | \"delete\" | \"format\";\n};\n\n/**\n * The class name(s) an app returns to style a suggestion mark. Either:\n * - a single string applied to *both* the mark content and its hover tooltip, or\n * - `{ content, tooltip }` to style the mark content and the tooltip\n * independently.\n */\nexport type AttributionMarkClassNames =\n | string\n | { content: string; tooltip: string };\n\n/**\n * Optional callback to override suggestion-mark styling. Given a mark's\n * {@link AttributionMarkStyleInfo}, it returns the class name(s) to apply (see\n * {@link AttributionMarkClassNames}). When a class is returned, the default\n * per-user color (the `--user-color-*` custom properties and the built-in\n * `.bn-suggestion-mark` / `.bn-suggestion-node` styling) is *not* applied to the\n * mark content, so the class fully controls its appearance — letting an app\n * color suggestions by change type (e.g. green insertions, red deletions)\n * instead of by author.\n */\nexport type GetAttributionMarkClassName = (\n info: AttributionMarkStyleInfo,\n) => AttributionMarkClassNames;\n\n/**\n * Resolve the {@link AttributionMarkClassNames} returned by a\n * {@link GetAttributionMarkClassName} callback to the class name for a single\n * target (the mark `content` or its `tooltip`).\n */\nexport const resolveAttributionMarkClassName = (\n result: AttributionMarkClassNames | undefined,\n target: \"content\" | \"tooltip\",\n): string | undefined =>\n result === undefined\n ? undefined\n : typeof result === \"string\"\n ? result\n : result[target];\n\n/**\n * Shared mark view for the attribution marks (insert / delete / modification).\n * It renders the marked content and tags the wrapper with the author(s) via\n * `data-*` attributes. The attribution tooltip shown on hover is handled\n * separately by the `AttributionExtension`, which reads those attributes\n * straight from the DOM — keeping this mark view purely presentational and the\n * tooltip state off of module scope.\n *\n * Author colors are *not* baked into the (deterministic) mark attrs. Instead the\n * wrapper sets the generic `--user-color-*` custom properties the Block.css rules\n * read, sourcing them from the author's *per-user* CSS variable via\n * `var(--user-color-<id>-*, <fallback>)`. Those per-user variables are populated\n * on the editor root by `AttributionExtension` once the user resolves, so a mark\n * shows the deterministic palette fallback immediately and recolors to the\n * author's own color purely through the CSS cascade — no decoration, no doc\n * transaction. See `userColors.ts`.\n */\nconst createAttributionMarkView =\n (\n type: \"insert\" | \"delete\" | \"modification\",\n options?: {\n editor?: BlockNoteEditor<any, any, any>;\n getAttributionMarkClassName?: GetAttributionMarkClassName;\n },\n ) =>\n ({ mark, inline }: { mark: PMMark; inline: boolean }) => {\n const editor = options?.editor;\n // `<ins>`/`<del>` are semantic elements. The modification mark has no\n // dedicated element, so it renders as a `<span>` inline or a `<div>` over a\n // block, matching its `parseDOM` rules.\n const tag =\n type === \"insert\"\n ? \"ins\"\n : type === \"delete\"\n ? \"del\"\n : inline\n ? \"span\"\n : \"div\";\n const dom = document.createElement(tag);\n\n Object.assign(dom.dataset, {\n userIds: JSON.stringify(mark.attrs[\"userIds\"]),\n inline: String(inline),\n });\n if (type === \"modification\") {\n dom.dataset[\"type\"] = \"modification\";\n dom.dataset[\"format\"] = JSON.stringify(mark.attrs[\"format\"]);\n }\n\n // Optional app-provided override: `y-attributed-format` is exposed as\n // `\"format\"`. When a class is returned it's applied to the content element\n // *instead of* the built-in `.bn-suggestion-mark` / `.bn-suggestion-node`\n // classes, and the per-user `--user-color-*` properties are omitted, so the\n // class fully controls the appearance (background, text color, etc.) with no\n // per-user color leaking through (see the type doc).\n const contentClassName = resolveAttributionMarkClassName(\n options?.getAttributionMarkClassName?.({\n contentType: inline ? \"inline-content\" : \"block\",\n modificationType: type === \"modification\" ? \"format\" : type,\n }),\n \"content\",\n );\n\n // The wrapper is always `display: contents` so it never generates a box of\n // its own — an inline `<ins>`/`<del>` around block/table content (e.g. a\n // suggestion spanning table cells) would otherwise break the normal layout.\n // Because a `display: contents` element paints nothing, the highlight is\n // applied to the inner content span (see `.bn-suggestion-mark` in Block.css)\n // using the `--user-color-*` custom properties, which cascade down from here.\n // They're sourced from the author's per-user variable (populated on the\n // editor root by `AttributionExtension`) with the deterministic palette as a\n // fallback, so a mark is colored before the user resolves and recolors via\n // the cascade afterward. When an override class owns the styling, no per-user\n // color is applied at all.\n const userIds = (mark.attrs[\"userIds\"] as string[] | null) ?? [];\n const firstId = userIds[0];\n const fallback = firstId\n ? fallbackColorForUserId(firstId)\n : userColorPalette[0];\n if (contentClassName) {\n dom.style.cssText = \"display: contents\";\n } else {\n const light = firstId\n ? `var(${userColorVarNames(firstId).light}, ${fallback.light})`\n : fallback.light;\n const dark = firstId\n ? `var(${userColorVarNames(firstId).dark}, ${fallback.dark})`\n : fallback.dark;\n dom.style.cssText =\n \"display: contents\" +\n `; --user-color-light: ${light}; --user-color-dark: ${dark}`;\n }\n\n const contentDOM = document.createElement(\"span\");\n if (inline) {\n // Inline content: the span is a real inline box that carries the highlight\n // (default path) or the app-provided override class.\n contentDOM.className =\n contentClassName ??\n (type === \"delete\"\n ? \"bn-suggestion-mark bn-suggestion-mark--delete\"\n : \"bn-suggestion-mark\");\n } else {\n // Block-level marks wrap block/table structure (e.g. <tr>/<td>/<p>). The\n // span must be `display: contents` so it doesn't inject an inline box into\n // the table layout (which triggers the browser's anonymous-table fixup and\n // breaks the table). Such a span has no box to paint a background on, so\n // the `.bn-suggestion-node` rule highlights its children (the wrapped\n // nodes) instead. An override class is applied to the same span, so it\n // should likewise target its children (e.g. `.my-class > *`).\n contentDOM.style.display = \"contents\";\n contentDOM.className =\n contentClassName ??\n (type === \"delete\"\n ? \"bn-suggestion-node bn-suggestion-node--delete\"\n : \"bn-suggestion-node\");\n if (type === \"delete\") {\n // A deleted block shows a localized \"Deleted\" badge via a `::before`\n // (see Block.css). The badge text is passed down as a CSS string token\n // in `--deleted-label` so the stylesheet stays locale-agnostic; the\n // wrapper is `display: contents` and can't paint a pseudo-element of its\n // own, so the rule renders the badge on the wrapped node instead, which\n // inherits this custom property.\n const label = editor?.dictionary.suggestion_changes.deleted;\n if (label) {\n contentDOM.style.setProperty(\n \"--deleted-label\",\n JSON.stringify(label),\n );\n }\n }\n }\n dom.appendChild(contentDOM);\n\n return {\n dom,\n contentDOM,\n };\n };\n\nexport const YAttributedInsertion = Mark.create<{\n getAttributionMarkClassName?: GetAttributionMarkClassName;\n}>({\n name: \"y-attributed-insert\",\n inclusive: false,\n excludes: \"\",\n // Two groups: `BLOCK_LEVEL_SUGGESTION_GROUP` lets the mark sit on block nodes\n // (see `suggestionMarks`), so a whole block can be marked as inserted in\n // suggestion mode; `NON_FORMATTING_MARK_GROUP` lets it annotate text inside\n // `\"plain\"` blocks (e.g. code blocks) — see `nonFormattingMarks`.\n group: `${BLOCK_LEVEL_SUGGESTION_GROUP} ${NON_FORMATTING_MARK_GROUP}`,\n addAttributes() {\n return {\n userIds: { default: null },\n };\n },\n addMarkView() {\n return createAttributionMarkView(\"insert\", {\n getAttributionMarkClassName: this.options.getAttributionMarkClassName,\n });\n },\n extendMarkSchema(extension) {\n if (extension.name !== this.name) {\n return {};\n }\n return {\n blocknoteIgnore: true,\n } satisfies MarkSpec;\n },\n});\n\nexport const YAttributedDeletion = Mark.create<{\n editor?: BlockNoteEditor<any, any, any>;\n getAttributionMarkClassName?: GetAttributionMarkClassName;\n}>({\n name: \"y-attributed-delete\",\n inclusive: false,\n excludes: \"\",\n group: `${BLOCK_LEVEL_SUGGESTION_GROUP} ${NON_FORMATTING_MARK_GROUP}`,\n addAttributes() {\n return {\n userIds: { default: null },\n };\n },\n addMarkView() {\n return createAttributionMarkView(\"delete\", {\n editor: this.options.editor,\n getAttributionMarkClassName: this.options.getAttributionMarkClassName,\n });\n },\n extendMarkSchema(extension) {\n if (extension.name !== this.name) {\n return {};\n }\n return {\n blocknoteIgnore: true,\n } satisfies MarkSpec;\n },\n});\n\nexport const YAttributedFormat = Mark.create<{\n getAttributionMarkClassName?: GetAttributionMarkClassName;\n}>({\n name: \"y-attributed-format\",\n inclusive: false,\n excludes: \"\",\n group: `${BLOCK_LEVEL_SUGGESTION_GROUP} ${NON_FORMATTING_MARK_GROUP}`,\n addAttributes() {\n return {\n userIds: { default: null },\n format: { default: null },\n };\n },\n addMarkView() {\n return createAttributionMarkView(\"modification\", {\n getAttributionMarkClassName: this.options.getAttributionMarkClassName,\n });\n },\n extendMarkSchema(extension) {\n if (extension.name !== this.name) {\n return {};\n }\n return {\n blocknoteIgnore: true,\n } satisfies MarkSpec;\n },\n});\n\n/**\n * Bundles the three `y-attributed-*` suggestion marks into a single BlockNote\n * extension, so they can be registered wherever they're actually needed (the\n * Yjs collaboration extension, or a test that exercises suggestions) instead of\n * living in the default schema. The marks opt into being allowed on block nodes\n * via their `blockLevelSuggestion` option — see `suggestionMarks`.\n */\nexport const YAttributionMarksExtension = createExtension(\n ({\n options,\n }: ExtensionOptions<\n { getAttributionMarkClassName?: GetAttributionMarkClassName } | undefined\n >) => ({\n key: \"yAttributionMarks\",\n tiptapExtensions: [\n YAttributedInsertion.configure({\n getAttributionMarkClassName: options?.getAttributionMarkClassName,\n }),\n YAttributedDeletion.configure({\n getAttributionMarkClassName: options?.getAttributionMarkClassName,\n }),\n YAttributedFormat.configure({\n getAttributionMarkClassName: options?.getAttributionMarkClassName,\n }),\n ],\n }),\n);\n","import { getChangedRanges } from \"@tiptap/core\";\nimport { Plugin, PluginKey, type Transaction } from \"prosemirror-state\";\nimport {\n createExtension,\n createStore,\n type ExtensionOptions,\n} from \"../../editor/BlockNoteExtension.js\";\nimport {\n colorsForUserIds,\n userColorVarNames,\n normalizeToUserStore,\n type UserStoreOrResolver,\n} from \"../../user/index.js\";\nimport {\n resolveAttributionMarkClassName,\n YAttributionMarksExtension,\n type GetAttributionMarkClassName,\n} from \"./YAttributionMarks.js\";\n\n/** The attribution marks, mapped to their `modificationType`. */\nconst ATTRIBUTION_MARK_TYPES = {\n \"y-attributed-insert\": \"insert\",\n \"y-attributed-delete\": \"delete\",\n \"y-attributed-format\": \"format\",\n} as const;\n\nconst ATTRIBUTION_LOAD_PLUGIN_KEY = new PluginKey(\"attributionLoadUsers\");\n\n/** Wrapper of an attribution mark; carries its author(s) in `data-user-ids`. */\nconst ATTRIBUTION_MARK_SELECTOR = \"[data-user-ids]\";\n\n/** Parse the JSON-encoded `data-user-ids` attribute; `[]` if missing/malformed. */\nconst parseUserIds = (userIdsJSON: string | undefined): string[] => {\n if (!userIdsJSON) {\n return [];\n }\n let userIds: unknown;\n try {\n userIds = JSON.parse(userIdsJSON);\n } catch {\n return [];\n }\n return Array.isArray(userIds) ? userIds.map(String) : [];\n};\n\n/**\n * The changed format keys from a modification mark's `data-format` (e.g.\n * `[\"bold\", \"italic\"]`); `[]` if missing/malformed or an empty change. This is\n * the raw change context — turning it into a localized label (e.g.\n * `\"Bold, Italic\"`) is a view concern owned by the React layer's\n * `formatChangeLabel`, so core stays i18n-agnostic here.\n */\nconst parseFormatKeys = (formatJSON: string | undefined): string[] => {\n if (!formatJSON) {\n return [];\n }\n let format: unknown;\n try {\n format = JSON.parse(formatJSON);\n } catch {\n return [];\n }\n if (typeof format !== \"object\" || format === null) {\n return [];\n }\n return Object.keys(format);\n};\n\n/**\n * The element with a real box to anchor the tooltip to. The wrapper is\n * `display: contents` (no box of its own), so use its content span child,\n * falling back further for block marks.\n */\nconst getReferenceElement = (wrapper: Element): Element => {\n const content = wrapper.firstElementChild ?? wrapper;\n const rect = content.getBoundingClientRect();\n if (rect.width || rect.height) {\n return content;\n }\n return content.firstElementChild ?? content;\n};\n\n/**\n * The box the tooltip anchors to. The wrapper is `display: contents` (no box of\n * its own), so use its content span child, falling back further for block marks.\n * Exported for the React controller's floating-ui `getBoundingClientRect`.\n */\nexport const getReferenceRect = (wrapper: Element): DOMRect =>\n getReferenceElement(wrapper).getBoundingClientRect();\n\n/**\n * The per-line client rects of the reference element, for floating-ui's\n * `inline()` middleware — it needs one rect per line to position off a\n * multi-line mark, and virtual elements don't get a default `getClientRects`.\n */\nexport const getReferenceClientRects = (wrapper: Element): DOMRectList =>\n getReferenceElement(wrapper).getClientRects();\n\n/**\n * State for the currently-hovered suggestion mark's tooltip (`undefined` when\n * none). The extension computes it; a React controller renders + positions it\n * (see `AttributionTooltipController`).\n */\nexport type AttributionTooltipState = {\n /** The wrapper element the tooltip anchors to (floating-ui reference). */\n anchor: HTMLElement;\n /** Per-user background color, resolved from the user store (default path). */\n color: string;\n /** The kind of change — `format` is the modification mark. */\n modificationType: \"insert\" | \"delete\" | \"format\";\n /** Whether the mark wraps inline content or a whole block. */\n contentType: \"inline-content\" | \"block\";\n /** Resolved usernames (falls back to raw ids), for custom renderers. */\n users: string[];\n /**\n * The changed format keys (e.g. `[\"bold\", \"italic\"]`), present only for\n * `format` marks. This is the raw change context — the view layer turns it\n * into a localized label via its `formatChangeLabel`.\n */\n format?: string[];\n /**\n * Class name from the `getAttributionMarkClassName` callback (override path).\n * When present, the tooltip applies this and skips the inline `color`.\n */\n className?: string;\n};\n\n/**\n * Resolves the attribution tooltip state for suggestion marks on hover (exposed\n * via a store for React), and loads each mark's author so its color/username\n * resolves. Marks nest, so a single delegated `mouseover` listener picks the\n * `closest` wrapper to the pointer — the innermost mark wins.\n */\nexport const AttributionExtension = createExtension(\n ({\n options,\n }: ExtensionOptions<\n | {\n /** Resolves authors to usernames. Optional; unresolved ids show raw. */\n resolveUsers?: UserStoreOrResolver;\n /** See {@link GetAttributionMarkClassName}. */\n getAttributionMarkClassName?: GetAttributionMarkClassName;\n }\n | undefined\n >) => {\n const userStore = normalizeToUserStore(options?.resolveUsers);\n const getAttributionMarkClassName = options?.getAttributionMarkClassName;\n\n const store = createStore<AttributionTooltipState | undefined>(undefined);\n\n // Load the authors of the attribution marks in `tr`'s changed ranges, so\n // their colors/usernames resolve (colors then flow to marks via `syncRootVars`).\n // `getChangedRanges` covers mark-only steps too — which suggestion mode adds\n // over existing text and `tr.changedRange()` would miss.\n const loadChangedUsers = (tr: Transaction) => {\n const ranges = getChangedRanges(tr);\n if (ranges.length === 0) {\n return;\n }\n // Most changes are local (often several steps in one small span), so scan a\n // single range spanning all of them rather than each range individually.\n let from = Infinity;\n let to = -Infinity;\n for (const { newRange } of ranges) {\n from = Math.min(from, newRange.from);\n to = Math.max(to, newRange.to);\n }\n\n const ids = new Set<string>();\n tr.doc.nodesBetween(from, to, (node) => {\n for (const mark of node.marks) {\n if (\n ATTRIBUTION_MARK_TYPES[\n mark.type.name as keyof typeof ATTRIBUTION_MARK_TYPES\n ]\n ) {\n const userIds = mark.attrs[\"userIds\"] as string[] | null;\n userIds?.forEach((id) => ids.add(id));\n }\n }\n return true;\n });\n if (ids.size > 0) {\n void userStore.loadUsers(Array.from(ids));\n }\n };\n\n return {\n key: \"attribution\",\n userStore,\n store,\n prosemirrorPlugins: [\n // Marks arrive in a transaction (suggestion mode, viewing suggestions,\n // version preview), so resolve their authors as the doc changes.\n new Plugin({\n key: ATTRIBUTION_LOAD_PLUGIN_KEY,\n state: {\n init: () => null,\n apply: (tr) => {\n if (tr.docChanged) {\n loadChangedUsers(tr);\n }\n return null;\n },\n },\n }),\n ],\n mount({ dom, root, signal }) {\n // Write each resolved author's color to the editor root as per-user CSS\n // variables (`--user-color-<id>-{light,dark}`) that the mark wrappers read\n // via `var(..., <fallback>)`, so the cascade recolors marks once a color\n // resolves. Color-less users have theirs removed so the fallback applies.\n const syncRootVars = () => {\n for (const [id, user] of userStore.store.state) {\n const { light, dark } = userColorVarNames(id);\n if (user.color && user.colorLight) {\n dom.style.setProperty(light, user.colorLight);\n dom.style.setProperty(dark, user.color);\n } else {\n dom.style.removeProperty(light);\n dom.style.removeProperty(dark);\n }\n }\n };\n\n // The wrapper currently showing a tooltip, so we don't re-emit on every\n // `mouseover` over the same mark.\n let activeAnchor: HTMLElement | undefined;\n\n // The mark's authors as usernames, falling back to the raw id when not\n // cached (`getUser` is cache-only; ids load on hover, see `onPointerOver`).\n const usersLabelArray = (userIdsJSON: string | undefined): string[] =>\n parseUserIds(userIdsJSON).map(\n (id) => userStore.getUser(id)?.username ?? id,\n );\n\n // A stable identity string for a wrapper (empty if unattributed), used to\n // (a) test whether a mark is attributed and (b) group adjacent marks with\n // the *same* attribution under one tooltip. It's an internal grouping key,\n // not the displayed text — that's composed in the view from `users` and\n // the format label — so it's built from raw `data-*` (ids + format keys)\n // and stays free of i18n/username resolution.\n const attributionIdentity = (wrapper: HTMLElement) => {\n const ids = parseUserIds(wrapper.dataset[\"userIds\"]);\n if (ids.length === 0) {\n return \"\";\n }\n const format = parseFormatKeys(wrapper.dataset[\"format\"]);\n return `${format.join(\",\")}:${ids.join(\",\")}`;\n };\n\n // Build the tooltip state from a wrapper's `data-*` attributes.\n const buildState = (anchor: HTMLElement): AttributionTooltipState => {\n const isModification = anchor.dataset[\"format\"] !== undefined;\n const modificationType: AttributionTooltipState[\"modificationType\"] =\n isModification\n ? \"format\"\n : anchor.tagName === \"INS\"\n ? \"insert\"\n : \"delete\";\n const contentType: AttributionTooltipState[\"contentType\"] =\n anchor.dataset[\"inline\"] === \"false\" ? \"block\" : \"inline-content\";\n\n return {\n anchor,\n // The tooltip is portaled outside the editor root, so it can't read\n // the cascaded per-user vars — resolve a concrete color from the store.\n color: colorsForUserIds(\n userStore,\n parseUserIds(anchor.dataset[\"userIds\"]),\n ).dark,\n modificationType,\n contentType,\n users: usersLabelArray(anchor.dataset[\"userIds\"]),\n format: isModification\n ? parseFormatKeys(anchor.dataset[\"format\"])\n : undefined,\n className: resolveAttributionMarkClassName(\n getAttributionMarkClassName?.({ contentType, modificationType }),\n \"tooltip\",\n ),\n };\n };\n\n const hideTooltip = () => {\n if (!activeAnchor) {\n return;\n }\n activeAnchor = undefined;\n store.setState(undefined);\n };\n\n // The innermost attributed mark at or above `el`, skipping unattributed\n // wrappers so an attributed ancestor still wins.\n const innermostAttributed = (\n el: Element | null,\n ): HTMLElement | undefined => {\n while (el) {\n const wrapper = el.closest<HTMLElement>(ATTRIBUTION_MARK_SELECTOR);\n if (!wrapper) {\n return undefined;\n }\n if (attributionIdentity(wrapper)) {\n return wrapper;\n }\n el = wrapper.parentElement;\n }\n return undefined;\n };\n\n const onPointerOver = (event: Event) => {\n const target = event.target instanceof Element ? event.target : null;\n const innermost = innermostAttributed(target);\n if (!innermost) {\n // Not over an attributed mark — drop the current tooltip.\n hideTooltip();\n return;\n }\n\n const identity = attributionIdentity(innermost);\n // Anchor on the outermost ancestor with the *same* attribution so one\n // tooltip covers the whole region; a differently-attributed ancestor\n // breaks the chain, and unattributed ones are climbed past.\n let anchor = innermost;\n let el: Element | null = innermost.parentElement;\n while (el) {\n const ancestor = el.closest<HTMLElement>(ATTRIBUTION_MARK_SELECTOR);\n if (!ancestor) {\n break;\n }\n const ancestorIdentity = attributionIdentity(ancestor);\n if (ancestorIdentity === identity) {\n anchor = ancestor;\n } else if (ancestorIdentity) {\n break;\n }\n el = ancestor.parentElement;\n }\n\n if (activeAnchor === anchor) {\n return;\n }\n\n activeAnchor = anchor;\n store.setState(buildState(anchor));\n\n // First hover renders raw ids (cache-only); load the authors and refresh\n // the resolved usernames once loaded, if this mark is still active.\n const ids = parseUserIds(anchor.dataset[\"userIds\"]);\n if (ids.length > 0) {\n void userStore.loadUsers(ids).then(() => {\n if (activeAnchor !== anchor) {\n return;\n }\n store.setState(buildState(anchor));\n });\n }\n };\n\n root.addEventListener(\"mouseover\", onPointerOver, { signal });\n signal.addEventListener(\"abort\", hideTooltip);\n\n // Seed from the cache, then keep the vars in sync as users resolve.\n syncRootVars();\n const unsubscribe = userStore.store.subscribe(syncRootVars);\n signal.addEventListener(\"abort\", unsubscribe);\n },\n\n // The `y-attributed-*` marks aren't in the default schema — register them\n // here so the block specs can allow them (collaboration-only).\n blockNoteExtensions: [\n YAttributionMarksExtension({\n getAttributionMarkClassName: options?.getAttributionMarkClassName,\n }),\n ],\n };\n },\n);\n","import { relativePositionStore, ySyncPluginKey } from \"@y/prosemirror\";\nimport { createExtension } from \"../../editor/BlockNoteExtension.js\";\n\nexport const RelativePositionMappingExtension = createExtension(\n ({ editor }) => {\n return {\n key: \"yPositionMapping\",\n mapPosition: (position: number, side: \"left\" | \"right\" = \"left\") => {\n const ySyncPluginState = ySyncPluginKey.getState(\n editor.prosemirrorState,\n );\n if (!ySyncPluginState?.ytype) {\n throw new Error(\"YSync plugin state not found\");\n }\n\n // 0 is a special case & always should map to itself\n if (position === 0) {\n return () => 0;\n }\n\n const posStore = relativePositionStore(\n editor.prosemirrorState.doc.resolve(\n position + (side === \"right\" ? 1 : -1),\n ),\n ySyncPluginState.ytype,\n ySyncPluginState.renderer,\n );\n\n return () => {\n const curYSyncPluginState = ySyncPluginKey.getState(\n editor.prosemirrorState,\n ) as typeof ySyncPluginState;\n const pos = posStore(\n editor.prosemirrorState.doc,\n curYSyncPluginState.ytype,\n curYSyncPluginState.renderer,\n );\n\n // This can happen if the element is garbage collected\n if (pos === null) {\n throw new Error(\"Position not found, cannot track positions\");\n }\n\n return pos + (side === \"right\" ? -1 : 1);\n };\n },\n } as const;\n },\n);\n","import { $prosemirrorDelta } from \"@y/prosemirror\";\nimport * as delta from \"lib0/delta\";\nimport * as schema from \"lib0/schema\";\n\n/**\n * Canonical name of a content delta's first block child (the child carried by an\n * insert op), or `null`. For a BlockNote `blockContainer` (content\n * `blockContent blockGroup?`) this is its block-content type (paragraph,\n * heading, image, ...).\n */\nconst firstChild = (\n d: schema.Unwrap<typeof $prosemirrorDelta>,\n): schema.Unwrap<typeof $prosemirrorDelta> | null => {\n for (const op of (d as any).children) {\n if (delta.$insertOp.check(op)) {\n for (const it of op.insert) {\n if (delta.$deltaAny.check(it)) {\n return it;\n }\n }\n }\n }\n return null;\n};\n\n/**\n * Whether a `blockContainer` delta carries a child `blockGroup` — i.e. the block\n * has nested children. A container's content is `blockContent blockGroup?`, so\n * this is what tells a leaf block apart from a parent.\n */\nconst hasBlockGroup = (d: schema.Unwrap<typeof $prosemirrorDelta>): boolean => {\n for (const op of (d as any).children) {\n if (delta.$insertOp.check(op)) {\n for (const it of op.insert) {\n if (delta.$deltaAny.check(it) && it.name === \"blockGroup\") {\n return true;\n }\n }\n }\n }\n return false;\n};\n\nfunction getTableDimensions(\n d: schema.Unwrap<typeof $prosemirrorDelta>,\n): { rows: number; cols: number } | null {\n if (d.name !== \"table\") {\n return null;\n }\n\n // Collect all rows with their cells' colspan/rowspan values.\n const rows: Array<Array<{ colspan: number; rowspan: number }>> = [];\n for (const op of (d as any).children) {\n if (delta.$insertOp.check(op)) {\n for (const tr of op.insert as Array<\n schema.Unwrap<typeof $prosemirrorDelta>\n >) {\n if (tr.name !== \"tableRow\") {\n return null;\n }\n const cells: Array<{ colspan: number; rowspan: number }> = [];\n for (const trOp of (tr as any).children) {\n if (delta.$insertOp.check(trOp)) {\n for (const td of trOp.insert as Array<\n schema.Unwrap<typeof $prosemirrorDelta>\n >) {\n if (td.name !== \"tableCell\" && td.name !== \"tableHeader\") {\n return null;\n }\n cells.push({\n colspan: Number(td.attrs.colspan) || 1,\n rowspan: Number(td.attrs.rowspan) || 1,\n });\n }\n }\n }\n rows.push(cells);\n }\n }\n }\n\n if (rows.length === 0) {\n return null;\n }\n\n // Build an occupancy grid to determine the true column count.\n // Each entry in `grid[r]` tracks which columns are already occupied\n // (by a cell from a previous row with rowspan > 1).\n const grid: boolean[][] = [];\n for (let r = 0; r < rows.length; r++) {\n if (!grid[r]) {\n grid[r] = [];\n }\n let col = 0;\n for (const cell of rows[r]) {\n // Skip columns already occupied by a rowspan from above.\n while (grid[r][col]) {\n col++;\n }\n // Mark all slots this cell occupies.\n for (let dr = 0; dr < cell.rowspan; dr++) {\n if (!grid[r + dr]) {\n grid[r + dr] = [];\n }\n for (let dc = 0; dc < cell.colspan; dc++) {\n grid[r + dr][col + dc] = true;\n }\n }\n col += cell.colspan;\n }\n }\n\n const numCols = Math.max(...grid.map((row) => row.length));\n return { rows: rows.length, cols: numCols };\n}\n\n/**\n * BlockNote's node-pairing policy for y-prosemirror's `matchNodes` option\n * (forwarded to `lib0/delta.diff`). This is the schema-specific bit that lives\n * in userland - the binding itself stays schema-agnostic.\n *\n * A `blockContainer` holds exactly one block content (`blockContent\n * blockGroup?`). Diffing a *type change* of that content as an in-place child\n * delete+insert would, under a suggestion, tombstone the old content next to the\n * new one => two block-contents in one container => schema-invalid. So we\n * declare a container's identity to be its first block-content child's type:\n * when that changes, the two containers are reported as *different*, the PM->Y\n * diff replaces the whole container, and the deleted + inserted containers sit\n * as siblings in the blockGroup (`blockGroupChild+` allows that). Each carries\n * the `y-attributed-*` node mark - which `blockContainer` already whitelists -\n * so no schema change and no storage transform are needed. A plain text edit\n * keeps the same first-child type => same identity => the diff descends and\n * merges as usual.\n *\n * @param a removed (old) node\n * @param b inserted (new) node\n * @returns whether `a` and `b` are the same node (diff in place) vs different (replace)\n */\nexport const blockMatchNodes = (\n a: schema.Unwrap<typeof $prosemirrorDelta>,\n b: schema.Unwrap<typeof $prosemirrorDelta>,\n): boolean => {\n if (a.name !== b.name) {\n return false;\n }\n\n if (a.name !== \"blockContainer\") {\n return true;\n }\n\n const childA = firstChild(a);\n const childB = firstChild(b);\n\n if (childA?.name !== childB?.name) {\n return false;\n }\n\n // A change in nesting is structural too: if one container gains or loses a\n // child `blockGroup`, diffing it in place would insert/delete the blockGroup as\n // a sibling of the block content inside a single container — schema-invalid.\n // Treat it as different so the whole container is replaced instead, same as a\n // content-type change. Keeps concurrent nesting merges (e.g. two users nesting\n // a block under the same parent) from producing a lopsided in-place result.\n if (hasBlockGroup(a) !== hasBlockGroup(b)) {\n return false;\n }\n\n if (childA?.name === \"table\" && childB?.name === \"table\") {\n const dimA = getTableDimensions(childA);\n const dimB = getTableDimensions(childB);\n if (\n dimA !== null &&\n dimB !== null &&\n dimA.rows !== dimB.rows &&\n dimA.cols !== dimB.cols\n ) {\n return false;\n }\n }\n\n return true;\n};\n","import { configureYProsemirror, syncPlugin } from \"@y/prosemirror\";\nimport {\n type ExtensionOptions,\n createExtension,\n} from \"../../editor/BlockNoteExtension.js\";\nimport { blockMatchNodes } from \"./blockMatchNodes.js\";\nimport { CollaborationOptions } from \"./index.js\";\n\n/**\n * Maps a Y attribution to BlockNote's `y-attributed-*` mark attrs.\n *\n * The mapper must be deterministic in `(format, attribution)` and emit attrs\n * that exactly match the declared mark schema in YAttributionMarks.ts. Any\n * mismatch causes the sync plugin to fire phantom reconcile dispatches in a\n * loop. See ATTRIBUTION.md in @y/prosemirror.\n *\n * Crucially the marks carry only stable identity (`userIds`, plus `format` for\n * the modification mark) — *not* user colors. Colors resolve asynchronously\n * from the {@link UserStore}, so baking them in here would make the mapper's\n * output change under a fixed `(format, attribution)` once a user loads, which\n * is exactly the non-determinism that triggers the reconcile loop. Instead the\n * `AttributionExtension` applies colors as a decoration layer that can\n * update independently of the mark representation.\n */\nexport const mapAttributionToMark = (\n format: Record<string, unknown> | null,\n attribution: {\n insert?: readonly string[];\n delete?: readonly string[];\n format?: Record<string, readonly string[]>;\n insertAt?: number;\n deleteAt?: number;\n formatAt?: number;\n },\n): Record<string, unknown> => {\n const out: Record<string, unknown> = { ...format };\n\n if (attribution.insert) {\n out[\"y-attributed-insert\"] = { userIds: attribution.insert };\n }\n\n if (attribution.delete) {\n out[\"y-attributed-delete\"] = { userIds: attribution.delete };\n }\n\n if (attribution.format) {\n const userIds = [...new Set(Object.values(attribution.format).flat())];\n out[\"y-attributed-format\"] = { userIds, format: attribution.format };\n }\n\n return out;\n};\n\nexport const YSyncExtension = createExtension(\n ({\n options,\n editor,\n }: ExtensionOptions<\n Pick<\n CollaborationOptions,\n | \"fragment\"\n | \"renderer\"\n | \"suggestionDoc\"\n | \"provider\"\n | \"getAttributionMarkClassName\"\n >\n >) => {\n return {\n key: \"ySync\",\n fragment: options.fragment,\n mount: () => {\n const configure = () => {\n editor.exec(\n configureYProsemirror({\n ytype: options.fragment,\n // purposefully not passing `renderer` here, this is only for syncing the main doc, not switching to suggestion mode\n // In the future, we may want view suggestion mode to be the default, and then we can decide how to indicate that through the options.\n // For now though, we are leaving suggestion mode as experimental and must be explicitly enabled through the SuggestionsExtension.\n }),\n );\n };\n\n if (\n options.provider &&\n \"synced\" in options.provider &&\n typeof options.provider.synced === \"boolean\"\n ) {\n if (options.provider[\"synced\"]) {\n configure();\n } else if (\n \"on\" in options.provider &&\n typeof options.provider.on === \"function\"\n ) {\n options.provider.on(\"synced\", (synced: boolean) => {\n if (synced) {\n configure();\n }\n });\n } else {\n throw new Error(\n \"YSyncExtension: provider must have a 'synced' boolean or an 'on' method to listen for 'sync'\",\n );\n }\n } else {\n configure();\n }\n },\n prosemirrorPlugins: [\n syncPlugin({\n suggestionDoc: options.suggestionDoc,\n mapAttributionToMark,\n // Node-pairing policy for the PM->Y diff: a `blockContainer` whose\n // block-content type changes is treated as a *different* node, so the\n // diff replaces the whole container (deleted + inserted siblings in\n // the blockGroup) instead of producing two block-contents in one\n // container => schema-invalid. No schema change / storage transform\n // needed; `blockContainer` already whitelists the `y-attributed-*`\n // marks. See blockMatchNodes.ts.\n customCompare: blockMatchNodes,\n }),\n ],\n runsBefore: [\"default\"],\n } as const;\n },\n);\n","import {\n deltaAttributionToFormat,\n deltaToPNode,\n deltaToPSteps,\n docToDelta,\n nodeToDelta,\n pmToFragment,\n} from \"@y/prosemirror\";\nimport * as d from \"lib0/delta\";\nimport { Node } from \"prosemirror-model\";\nimport { Transaction } from \"prosemirror-state\";\nimport {\n type Block,\n type BlockNoteEditor,\n type BlockSchema,\n type InlineContentSchema,\n type PartialBlock,\n type StyleSchema,\n blockToNode,\n docToBlocks,\n} from \"../index.js\";\nimport { blockMatchNodes } from \"./extensions/blockMatchNodes.js\";\nimport { mapAttributionToMark } from \"./extensions/YSync.js\";\n\nimport * as Y from \"@y/y\";\n\n/**\n * Find the equivalent of a Y.Type in another Y.Doc.\n *\n * For root types this looks up the matching shared key; for sub-types it\n * locates the item by its client/clock ID in the target doc's store.\n */\nexport function findTypeInOtherYdoc<T extends Y.Type<any>>(\n ytype: T,\n otherYdoc: Y.Doc,\n): T {\n const ydoc = ytype.doc;\n if (!ydoc) {\n throw new Error(\"type does not have a ydoc\");\n }\n if (ytype._item === null) {\n /**\n * If is a root type, we need to find the root key in the original ydoc\n * and use it to get the type in the other ydoc.\n */\n const rootKey = Array.from(ydoc.share.keys()).find(\n (key) => ydoc.share.get(key) === ytype,\n );\n if (rootKey == null) {\n throw new Error(\"type does not exist in other ydoc\");\n }\n return otherYdoc.get(rootKey as string, ytype.constructor as any) as T;\n } else {\n /**\n * If it is a sub type, we use the item id to find the history type.\n */\n const ytypeItem = ytype._item;\n const otherStructs = otherYdoc.store.clients.get(ytypeItem.id.client) ?? [];\n const itemIndex = Y.findIndexSS(otherStructs, ytypeItem.id.clock);\n const otherItem = otherStructs[itemIndex] as Y.Item | undefined;\n if (!otherItem) {\n throw new Error(\"type does not exist in other ydoc\");\n }\n const otherContent = otherItem.content as Y.ContentType | undefined;\n if (!otherContent) {\n throw new Error(\"type does not exist in other ydoc\");\n }\n return otherContent.type as T;\n }\n}\n\n/**\n * Turn Prosemirror JSON to BlockNote style JSON\n * @param editor BlockNote editor\n * @param json Prosemirror JSON\n * @returns BlockNote style JSON\n */\nexport function _prosemirrorJSONToBlocks<\n BSchema extends BlockSchema,\n ISchema extends InlineContentSchema,\n SSchema extends StyleSchema,\n>(editor: BlockNoteEditor<BSchema, ISchema, SSchema>, json: any) {\n // note: theoretically this should also be possible without creating prosemirror nodes,\n // but this is definitely the easiest way\n const doc = editor.pmSchema.nodeFromJSON(json);\n return docToBlocks<BSchema, ISchema, SSchema>(doc);\n}\n\n/**\n * Turn BlockNote JSON to Prosemirror node / state\n * @param editor BlockNote editor\n * @param blocks BlockNote blocks\n * @returns Prosemirror root node\n */\nexport function _blocksToProsemirrorNode<\n BSchema extends BlockSchema,\n ISchema extends InlineContentSchema,\n SSchema extends StyleSchema,\n>(\n editor: BlockNoteEditor<BSchema, ISchema, SSchema>,\n blocks: PartialBlock<BSchema, ISchema, SSchema>[],\n) {\n const pmNodes = blocks.map((b) => blockToNode(b, editor.pmSchema));\n\n const doc = editor.pmSchema.topNodeType.create(\n null,\n editor.pmSchema.nodes[\"blockGroup\"].create(null, pmNodes),\n );\n return doc;\n}\n\n/** YJS / BLOCKNOTE conversions */\n\n/**\n * Turn a Y.Type collaborative doc into a BlockNote document (BlockNote style JSON of all blocks)\n * @param editor BlockNote editor\n * @param fragment Y.Type\n * @returns BlockNote document (BlockNote style JSON of all blocks)\n */\nexport function yfragmentToBlocks<\n BSchema extends BlockSchema,\n ISchema extends InlineContentSchema,\n SSchema extends StyleSchema,\n>(editor: BlockNoteEditor<BSchema, ISchema, SSchema>, fragment: Y.Type) {\n const pmNode = deltaToPNode(fragment.toDeltaDeep(), editor.pmSchema, null);\n if (pmNode === null) {\n return [];\n }\n return docToBlocks<BSchema, ISchema, SSchema>(pmNode);\n}\n\n/**\n * Convert blocks to a Y.Type\n *\n * This can be used when importing existing content to Y.Doc for the first time,\n * note that this should not be used to rehydrate a Y.Doc from a database once\n * collaboration has begun as all history will be lost\n *\n * @param editor BlockNote editor\n * @param blocks the blocks to convert\n * @param fragment XML fragment name\n * @returns Y.Type\n */\nexport function blocksToYType<\n BSchema extends BlockSchema,\n ISchema extends InlineContentSchema,\n SSchema extends StyleSchema,\n>(\n editor: BlockNoteEditor<BSchema, ISchema, SSchema>,\n blocks: Block<BSchema, ISchema, SSchema>[],\n fragment?: Y.Type,\n) {\n if (!fragment) {\n fragment = new Y.Doc().get(\"prosemirror\");\n }\n return pmToFragment(_blocksToProsemirrorNode(editor, blocks), fragment);\n}\n\n/**\n * Turn a Y.Doc collaborative doc into a BlockNote document (BlockNote style JSON of all blocks)\n * @param editor BlockNote editor\n * @param ydoc Y.Doc\n * @param fragment XML fragment name\n * @returns BlockNote document (BlockNote style JSON of all blocks)\n */\nexport function yDocToBlocks<\n BSchema extends BlockSchema,\n ISchema extends InlineContentSchema,\n SSchema extends StyleSchema,\n>(\n editor: BlockNoteEditor<BSchema, ISchema, SSchema>,\n ydoc: Y.Doc,\n fragment = \"prosemirror\",\n) {\n return yfragmentToBlocks(editor, ydoc.get(fragment));\n}\n\n/**\n * This can be used when importing existing content to Y.Doc for the first time,\n * note that this should not be used to rehydrate a Y.Doc from a database once\n * collaboration has begun as all history will be lost\n *\n * @param editor BlockNote editor\n * @param blocks the blocks to convert\n * @param fragment XML fragment name\n */\nexport function blocksToYDoc<\n BSchema extends BlockSchema,\n ISchema extends InlineContentSchema,\n SSchema extends StyleSchema,\n>(\n editor: BlockNoteEditor<BSchema, ISchema, SSchema>,\n blocks: PartialBlock<BSchema, ISchema, SSchema>[],\n fragment = \"prosemirror\",\n) {\n const delta = docToDelta(_blocksToProsemirrorNode(editor, blocks));\n const doc = new Y.Doc();\n doc.get(fragment).applyDelta(delta);\n return doc;\n}\n\n/**\n * Diff two ProseMirror documents into a delta, using BlockNote's node-pairing\n * policy ({@link blockMatchNodes}) so a block's content-type change is reported\n * as a replace rather than a schema-invalid in-place edit.\n */\nexport function docDiffToDelta(previousDoc: Node, newDoc: Node) {\n const initialDelta = nodeToDelta(previousDoc);\n const finalDelta = nodeToDelta(newDoc);\n return d.diff(initialDelta.done(), finalDelta.done(), {\n compare: blockMatchNodes,\n });\n}\n\n/**\n * Build a ProseMirror transaction that turns `tr.doc` into the content of a\n * Y.Type `fragment`, applying the `renderer`'s authorship as\n * `y-attributed-*` marks. Used to render a (read-only) diff of a snapshot / a\n * version comparison into the editor.\n */\nexport function getProseMirrorTrFromYFragment({\n tr,\n fragment,\n renderer,\n}: {\n tr: Transaction;\n fragment: Y.Type;\n renderer?: Y.AbstractRenderer | null;\n}): Transaction {\n const ycontent = deltaAttributionToFormat(\n fragment.toDeltaDeep({ renderer }),\n mapAttributionToMark,\n );\n // @todo it is preferred to apply the minimal diff - at least for debugging purposes. the\n // document replacal is more reliable though\n\n const pcontent = nodeToDelta(tr.doc, undefined, true);\n const diff = d.diff(pcontent.done(), ycontent.done(), {\n compare: blockMatchNodes,\n });\n return deltaToPSteps(tr, diff, undefined, undefined);\n}\n","import { getMarkRange, posToDOMRect } from \"@tiptap/core\";\n\nimport {\n createExtension,\n ExtensionOptions,\n} from \"../../editor/BlockNoteExtension.js\";\nimport {\n acceptChanges,\n rejectAllChanges,\n rejectChanges,\n configureYProsemirror,\n acceptAllChanges,\n} from \"@y/prosemirror\";\nimport { CollaborationOptions } from \"./index.js\";\nimport { findTypeInOtherYdoc } from \"../utils.js\";\nimport { normalizeToUserStore } from \"../../user/index.js\";\n\nexport const SuggestionsExtension = createExtension(\n ({ editor, options }: ExtensionOptions<CollaborationOptions>) => {\n const suggestionDoc = options.suggestionDoc;\n if (!suggestionDoc) {\n throw new Error(\"Suggestion doc not found\");\n }\n // Shared with the rest of collaboration; the collaboration extension passes\n // an already-built store here.\n const userStore = normalizeToUserStore(options.resolveUsers);\n\n function getSuggestionElementAtPos(pos: number) {\n let currentNode = editor.prosemirrorView.nodeDOM(pos);\n while (currentNode && currentNode.parentElement) {\n if (currentNode.nodeName === \"INS\" || currentNode.nodeName === \"DEL\") {\n return currentNode as HTMLElement;\n }\n currentNode = currentNode.parentElement;\n }\n return null;\n }\n\n function getMarkAtPos(pos: number, markType: string) {\n return editor.transact((tr) => {\n const resolvedPos = tr.doc.resolve(pos);\n const mark = resolvedPos\n .marks()\n .find((mark) => mark.type.name === markType);\n\n if (!mark) {\n return;\n }\n\n const markRange = getMarkRange(resolvedPos, mark.type);\n if (!markRange) {\n return;\n }\n\n return {\n range: markRange,\n mark,\n get text() {\n return tr.doc.textBetween(markRange.from, markRange.to);\n },\n get position() {\n // to minimize re-renders, we convert to JSON, which is the same shape anyway\n return posToDOMRect(\n editor.prosemirrorView,\n markRange.from,\n markRange.to,\n ).toJSON() as DOMRect;\n },\n };\n });\n }\n\n function getSuggestionAtSelection() {\n return editor.transact((tr) => {\n const selection = tr.selection;\n if (!selection.empty) {\n return undefined;\n }\n return (\n getMarkAtPos(selection.anchor, \"insertion\") ||\n getMarkAtPos(selection.anchor, \"deletion\") ||\n getMarkAtPos(selection.anchor, \"modification\")\n );\n });\n }\n\n return {\n key: \"suggestions\",\n userStore,\n runsBefore: [\"ySync\"],\n viewSuggestions: () => {\n if (options.renderer) {\n options.renderer.suggestionMode = false;\n }\n editor.exec(\n configureYProsemirror({\n ytype: findTypeInOtherYdoc(options.fragment, suggestionDoc),\n renderer: options.renderer,\n }),\n );\n },\n enableSuggestions: () => {\n if (options.renderer) {\n options.renderer.suggestionMode = true;\n }\n editor.exec(\n configureYProsemirror({\n ytype: findTypeInOtherYdoc(options.fragment, suggestionDoc),\n renderer: options.renderer,\n }),\n );\n },\n disableSuggestions: () => {\n editor.exec(\n configureYProsemirror({\n ytype: options.fragment,\n renderer: null,\n }),\n );\n },\n applyAllSuggestions: () => {\n return editor.exec(acceptAllChanges());\n },\n applySuggestion: (start: number, end?: number) => {\n return editor.exec(acceptChanges(start, end));\n },\n revertSuggestion: (start: number, end?: number) => {\n return editor.exec(rejectChanges(start, end));\n },\n revertAllSuggestions: () => {\n return editor.exec(rejectAllChanges());\n },\n\n getSuggestionElementAtPos,\n getMarkAtPos,\n getSuggestionAtSelection,\n getSuggestionAtCoords: (coords: { left: number; top: number }) => {\n return editor.transact(() => {\n const posAtCoords = editor.prosemirrorView.posAtCoords(coords);\n if (posAtCoords === null || posAtCoords?.inside === -1) {\n return undefined;\n }\n\n return (\n getMarkAtPos(posAtCoords.pos, \"y-attributed-insert\") ||\n getMarkAtPos(posAtCoords.pos, \"y-attributed-delete\") ||\n getMarkAtPos(posAtCoords.pos, \"y-attributed-format\")\n );\n });\n },\n checkUnresolvedSuggestions: () => {\n let hasUnresolvedSuggestions = false;\n\n editor.prosemirrorState.doc.descendants((node) => {\n if (hasUnresolvedSuggestions) {\n return false;\n }\n\n hasUnresolvedSuggestions =\n node.marks.findIndex(\n (mark) =>\n mark.type.name === \"y-attributed-insert\" ||\n mark.type.name === \"y-attributed-delete\" ||\n mark.type.name === \"y-attributed-format\",\n ) !== -1;\n\n return true;\n });\n\n return hasUnresolvedSuggestions;\n },\n } as const;\n },\n);\n","import { configureYProsemirror, pauseSync } from \"@y/prosemirror\";\nimport * as Y from \"@y/y\";\n\nimport type { BlockNoteEditor } from \"../../editor/BlockNoteEditor.js\";\nimport type { PreviewController } from \"../../extensions/Versioning/index.js\";\nimport {\n findTypeInOtherYdoc,\n getProseMirrorTrFromYFragment,\n} from \"../utils.js\";\n\n/**\n * Empties the document before a {@link configureYProsemirror} refill so\n * ProseMirror rebuilds every node view instead of reusing a stale-positioned one\n * (BlockNote node views resolve their block eagerly via `getPos()` and throw on\n * a moved node). Sync is paused first so the clear never reaches the Y.Doc.\n *\n * TODO: remove once `configureYProsemirror` applies a minimal diff.\n */\nfunction clearDocumentForConfigure(editor: BlockNoteEditor<any, any, any>) {\n // Pause sync (ytype -> null) so the deletion below stays local.\n editor.exec(pauseSync);\n editor.removeBlocks(editor.document);\n}\n\n/**\n * Creates a Yjs-specific adapter that provides the {@link PreviewController}\n * and `getCurrentDocument` callback required by the base\n * {@link VersioningExtension}.\n *\n * This is wired automatically by the {@link CollaborationExtension} when\n * `versioningEndpoints` is provided. You only need to call this directly if\n * you're using the `VersioningExtension` outside of the collaboration wrapper.\n */\nexport function createYjsVersioningAdapter(\n editor: BlockNoteEditor<any, any, any>,\n fragment: Y.Type,\n): {\n preview: PreviewController<Uint8Array, Y.ContentMap>;\n getCurrentDocument: () => Y.Type;\n serializeCurrentContent: () => Uint8Array;\n} {\n return {\n getCurrentDocument: () => fragment,\n // Serialise the live document as a V2 update — the same format that\n // `getContent` returns (via `convertUpdateFormatV1ToV2`) and that\n // `enterPreview` consumes (`applyUpdateV2`). Used to render a read-only\n // diff of the live document against a snapshot.\n serializeCurrentContent: () => Y.encodeStateAsUpdateV2(fragment.doc!),\n preview: {\n enterPreview: (\n snapshotContent: Uint8Array,\n compareToContent?: Uint8Array,\n attributions?: Y.ContentMap,\n ) => {\n let prevSnapshot: { fragment: Y.Type } | undefined;\n if (compareToContent) {\n const compareToDoc = new Y.Doc({ isSuggestionDoc: true });\n Y.applyUpdateV2(compareToDoc, compareToContent);\n prevSnapshot = {\n fragment: findTypeInOtherYdoc(fragment, compareToDoc),\n };\n }\n\n const doc = new Y.Doc();\n Y.applyUpdateV2(doc, snapshotContent);\n // Empty the document before reconfiguring so ProseMirror rebuilds node\n // views from scratch instead of reusing stale-positioned ones. See\n // clearDocumentForConfigure.\n clearDocumentForConfigure(editor);\n\n editor.exec((state, dispatch) => {\n const tr = getProseMirrorTrFromYFragment({\n tr: state.tr,\n fragment: findTypeInOtherYdoc(fragment, doc),\n // Pass the optional content map as `attrs` so the diff renderer\n // knows who/when authored each change. Without it, the renderer\n // only produces \"what changed\" (empty userIds, null timestamps) and\n // downstream mark tooltips show \"unknown / unknown time\".\n renderer: prevSnapshot\n ? Y.createDiffRenderer(\n prevSnapshot.fragment.doc!,\n doc,\n attributions ? { attrs: attributions } : undefined,\n )\n : undefined,\n });\n if (dispatch) {\n dispatch(tr);\n }\n return true;\n });\n },\n exitPreview: () => {\n // Empty the document before reconfiguring so ProseMirror rebuilds node\n // views from scratch instead of reusing stale-positioned ones. See\n // clearDocumentForConfigure.\n clearDocumentForConfigure(editor);\n editor.exec(configureYProsemirror({ ytype: fragment }));\n },\n applyRestore: (_snapshotContent: Uint8Array) => {\n // For Yjs-backed versioning, restoration happens on the server (e.g.\n // YHub's `/rollback` endpoint) which publishes a reverting update to\n // the document's room. That update propagates back to this client over\n // the live sync connection and updates `fragment` automatically, so\n // there is nothing to apply locally — we only need to leave preview\n // mode. `exitPreview` is already called by the base extension before\n // this runs, so this is a no-op.\n //\n // Note: this assumes `endpoints.restore` performs the server-side\n // restore. The default in-memory adapter has no server, which is why\n // this is specific to the Yjs collaboration setup.\n },\n },\n };\n}\n","import { defaultSelectionBuilder, yCursorPlugin } from \"@y/prosemirror\";\nimport {\n createExtension,\n ExtensionOptions,\n} from \"../../editor/BlockNoteExtension.js\";\nimport { CollaborationOptions } from \"./index.js\";\n\nexport type CollaborationUser = {\n id?: string;\n name: string;\n color: string;\n [key: string]: unknown;\n};\n\n/**\n * Determine whether the foreground color should be white or black based on a provided background color\n * Inspired by: https://stackoverflow.com/a/3943023\n */\nfunction isDarkColor(bgColor: string): boolean {\n const color = bgColor.charAt(0) === \"#\" ? bgColor.substring(1, 7) : bgColor;\n const r = parseInt(color.substring(0, 2), 16); // hexToR\n const g = parseInt(color.substring(2, 4), 16); // hexToG\n const b = parseInt(color.substring(4, 6), 16); // hexToB\n const uicolors = [r / 255, g / 255, b / 255];\n const c = uicolors.map((col) => {\n if (col <= 0.03928) {\n return col / 12.92;\n }\n return Math.pow((col + 0.055) / 1.055, 2.4);\n });\n const L = 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];\n return L <= 0.179;\n}\n\nfunction defaultCursorRender(user: CollaborationUser) {\n const cursorElement = document.createElement(\"span\");\n\n cursorElement.classList.add(\"bn-collaboration-cursor__base\");\n\n const caretElement = document.createElement(\"span\");\n caretElement.setAttribute(\"contentedEditable\", \"false\");\n caretElement.classList.add(\"bn-collaboration-cursor__caret\");\n caretElement.setAttribute(\n \"style\",\n `background-color: ${user.color}; color: ${\n isDarkColor(user.color) ? \"white\" : \"black\"\n }`,\n );\n\n const labelElement = document.createElement(\"span\");\n\n labelElement.classList.add(\"bn-collaboration-cursor__label\");\n labelElement.setAttribute(\n \"style\",\n `background-color: ${user.color}; color: ${\n isDarkColor(user.color) ? \"white\" : \"black\"\n }`,\n );\n labelElement.insertBefore(document.createTextNode(user.name), null);\n\n caretElement.insertBefore(labelElement, null);\n\n cursorElement.insertBefore(document.createTextNode(\"\\u2060\"), null); // Non-breaking space\n cursorElement.insertBefore(caretElement, null);\n cursorElement.insertBefore(document.createTextNode(\"\\u2060\"), null); // Non-breaking space\n\n return cursorElement;\n}\n\nexport const YCursorExtension = createExtension(\n ({ options }: ExtensionOptions<CollaborationOptions>) => {\n const recentlyUpdatedCursors = new Map();\n const awareness =\n options.provider &&\n \"awareness\" in options.provider &&\n typeof options.provider.awareness === \"object\"\n ? options.provider.awareness\n : undefined;\n if (awareness) {\n if (\n \"setLocalStateField\" in awareness &&\n typeof awareness.setLocalStateField === \"function\"\n ) {\n awareness.setLocalStateField(\"user\", options.user);\n }\n if (\"on\" in awareness && typeof awareness.on === \"function\") {\n if (options.showCursorLabels !== \"always\") {\n awareness.on(\n \"change\",\n ({\n updated,\n }: {\n added: Array<number>;\n updated: Array<number>;\n removed: Array<number>;\n }) => {\n for (const clientID of updated) {\n const cursor = recentlyUpdatedCursors.get(clientID);\n\n if (cursor) {\n setTimeout(() => {\n cursor.element.setAttribute(\"data-active\", \"\");\n }, 10);\n\n if (cursor.hideTimeout) {\n clearTimeout(cursor.hideTimeout);\n }\n\n recentlyUpdatedCursors.set(clientID, {\n element: cursor.element,\n hideTimeout: setTimeout(() => {\n cursor.element.removeAttribute(\"data-active\");\n }, 2000),\n });\n }\n }\n },\n );\n }\n }\n }\n\n return {\n key: \"yCursor\",\n prosemirrorPlugins: [\n awareness\n ? yCursorPlugin(awareness, {\n selectionBuilder: defaultSelectionBuilder,\n cursorBuilder(user, clientID) {\n let cursorData = recentlyUpdatedCursors.get(clientID);\n\n if (!cursorData) {\n const cursorElement = (\n options.renderCursor ?? defaultCursorRender\n )(user as CollaborationUser);\n\n if (options.showCursorLabels !== \"always\") {\n cursorElement.addEventListener(\"mouseenter\", () => {\n const cursor = recentlyUpdatedCursors.get(clientID)!;\n cursor.element.setAttribute(\"data-active\", \"\");\n\n if (cursor.hideTimeout) {\n clearTimeout(cursor.hideTimeout);\n recentlyUpdatedCursors.set(clientID, {\n element: cursor.element,\n hideTimeout: undefined,\n });\n }\n });\n\n cursorElement.addEventListener(\"mouseleave\", () => {\n const cursor = recentlyUpdatedCursors.get(clientID)!;\n\n recentlyUpdatedCursors.set(clientID, {\n element: cursor.element,\n hideTimeout: setTimeout(() => {\n cursor.element.removeAttribute(\"data-active\");\n }, 2000),\n });\n });\n }\n\n cursorData = {\n element: cursorElement,\n hideTimeout: undefined,\n };\n\n recentlyUpdatedCursors.set(clientID, cursorData);\n }\n\n return cursorData.element;\n },\n })\n : undefined,\n ].filter((a) => a !== undefined),\n dependsOn: [\"ySync\"],\n updateUser(user: CollaborationUser) {\n awareness?.setLocalStateField(\"user\", user);\n },\n getUser(): CollaborationUser | undefined {\n const state = awareness?.getLocalState();\n if (!state) {\n return undefined;\n }\n return state[\"user\"];\n },\n } as const;\n },\n);\n","import { docToDelta } from \"@y/prosemirror\";\nimport * as Y from \"@y/y\";\n\nimport type { Block } from \"../../blocks/defaultBlocks.js\";\nimport type { BlockNoteEditor } from \"../../editor/BlockNoteEditor.js\";\nimport { createExtension } from \"../../editor/BlockNoteExtension.js\";\nimport type { User } from \"../../user/index.js\";\nimport {\n _blocksToProsemirrorNode,\n docDiffToDelta,\n findTypeInOtherYdoc,\n getProseMirrorTrFromYFragment,\n} from \"../utils.js\";\nimport { AttributionExtension } from \"./AttributionExtension.js\";\nimport type { GetAttributionMarkClassName } from \"./YAttributionMarks.js\";\n\n/**\n * A version diff has a single \"author\" — the version that introduced the changes\n * — not a real user, so all `y-attributed-*` marks carry one synthetic id. That\n * id is derived from the version's label (see {@link diffAuthorId}) so it's stable\n * per version: the user store caches resolved users by id, so a per-label id keeps\n * each version's tooltip showing its own name instead of a stale cached one.\n */\nconst DIFF_AUTHOR_ID_PREFIX = \"version:\";\n\n/** The synthetic author id for a given version label. */\nconst diffAuthorId = (label: string) => DIFF_AUTHOR_ID_PREFIX + label;\n\n/** Fallback label used when a diff is rendered without a version name. */\nconst DEFAULT_DIFF_LABEL = \"This version\";\n\n/** Color used for the version diff marks. */\nconst DIFF_AUTHOR_COLOR = \"#4363d8\";\n\nexport type DiffVersioningExtensionOptions = {\n /**\n * The color used for the diff's attribution marks. Defaults to a blue.\n */\n color?: string;\n /**\n * See {@link GetAttributionMarkClassName}. Forwarded to the underlying\n * {@link AttributionExtension} to override mark styling by change type.\n */\n getAttributionMarkClassName?: GetAttributionMarkClassName;\n};\n\n/**\n * Records the author of each transaction on `doc` into a mutable\n * {@link Y.Attributions}, so the resulting attribution marks carry a non-empty\n * `userIds` (and therefore resolve to a color/name). The listener must be\n * attached *before* the attributed transaction runs. Mirrors the store used by\n * the suggestion gallery example (`createAttributionStore`).\n */\nfunction attributeTransactionsTo(doc: Y.Doc, userId: string): Y.Attributions {\n const attrs = new Y.Attributions();\n doc.on(\"beforeObserverCalls\", (tr) => {\n if (!tr.insertSet.isEmpty()) {\n Y.insertIntoIdMap(\n attrs.inserts,\n Y.createIdMapFromIdSet(tr.insertSet, [\n Y.createContentAttribute(\"insert\", userId),\n ]),\n );\n }\n if (!tr.deleteSet.isEmpty()) {\n Y.insertIntoIdMap(\n attrs.deletes,\n Y.createIdMapFromIdSet(tr.deleteSet, [\n Y.createContentAttribute(\"delete\", userId),\n ]),\n );\n }\n });\n return attrs;\n}\n\n/**\n * An opt-in extension that renders a read-only diff between two BlockNote\n * documents (`Block[]`) directly in the editor, marking insertions/deletions\n * with the `y-attributed-*` suggestion marks — the same visual result the Yjs\n * collaboration adapter produces, but driven from two plain block arrays with\n * no server and no live Yjs sync.\n *\n * It composes {@link AttributionExtension} (which registers the attribution\n * marks and drives their colors + hover tooltips from a user store), and adds\n * the {@link renderDiff} / {@link clearDiff} capability.\n *\n * Registering this extension is what makes non-collaborative versioning\n * (`inMemoryVersioning`) capable of showing diffs: the in-memory preview\n * controller looks this up by key (`\"diffVersioning\"`) and delegates to\n * {@link renderDiff}, falling back to a static document swap when it's absent.\n *\n * `renderDiff` is also a standalone, directly-callable API — you can register\n * just this extension and call\n * `editor.getExtension(DiffVersioningExtension).renderDiff(target, baseline)`\n * to render a known diff (e.g. in tests).\n *\n * @example\n * ```ts\n * const editor = BlockNoteEditor.create({\n * extensions: [DiffVersioningExtension()],\n * });\n * editor.getExtension(DiffVersioningExtension)!.renderDiff(target, baseline);\n * ```\n */\nexport const DiffVersioningExtension = createExtension(\n ({\n options,\n editor,\n }: {\n options: DiffVersioningExtensionOptions | undefined;\n editor: BlockNoteEditor<any, any, any>;\n }) => {\n const color = options?.color ?? DIFF_AUTHOR_COLOR;\n\n // Resolve a synthetic author id back to its version label. The id encodes\n // the label (`version:<label>`), so this is a pure decode — no shared mutable\n // state, and the user store caches each version's \"user\" separately (so\n // switching between version comparisons never shows a stale name).\n const resolveUsers = async (ids: string[]): Promise<User[]> =>\n ids\n .filter((id) => id.startsWith(DIFF_AUTHOR_ID_PREFIX))\n .map((id) => ({\n id,\n username: id.slice(DIFF_AUTHOR_ID_PREFIX.length),\n avatarUrl: \"\",\n color,\n }));\n\n /**\n * Render a read-only diff of `baselineBlocks` → `snapshotBlocks` into the\n * editor. The changes are attributed to the version that introduced them:\n * pass `versionLabel` to label the diff marks (shown in their hover tooltip,\n * e.g. \"Edited by: {versionLabel}\"). Uses the \"two-doc fork\" recipe so the\n * two Y.Docs share history — a hard requirement for\n * `createDiffRenderer`, which diffs by Yjs client/clock ids.\n */\n const renderDiff = (\n snapshotBlocks: Block<any, any, any>[],\n baselineBlocks: Block<any, any, any>[],\n versionLabel: string = DEFAULT_DIFF_LABEL,\n ) => {\n const authorId = diffAuthorId(versionLabel);\n\n if (!editor.pmSchema.marks[\"y-attributed-insert\"]) {\n throw new Error(\n \"DiffVersioningExtension: the y-attributed-* marks are missing from \" +\n \"the schema. This should not happen — the extension registers them \" +\n \"via AttributionExtension.\",\n );\n }\n\n const baselineNode = _blocksToProsemirrorNode(editor, baselineBlocks);\n const snapshotNode = _blocksToProsemirrorNode(editor, snapshotBlocks);\n\n // gc must stay off so the attribution manager can read the full struct\n // store (including deleted items) when diffing.\n const prevDoc = new Y.Doc({ gc: false });\n const prevType = prevDoc.get(\"prosemirror\");\n prevDoc.transact(() => {\n prevType.applyDelta(docToDelta(baselineNode) as any);\n });\n\n // Fork prevDoc into nextDoc so they share client/clock ids, then apply the\n // baseline → snapshot delta as a new transaction. New content gets ids\n // that prevDoc lacks (→ inserts); items retained-away become deletes.\n const nextDoc = new Y.Doc({ gc: false });\n Y.applyUpdateV2(nextDoc, Y.encodeStateAsUpdateV2(prevDoc));\n const nextType = findTypeInOtherYdoc(prevType, nextDoc);\n\n // Attach the author store BEFORE applying the delta so the diff\n // transaction's inserts/deletes are attributed.\n const attrs = attributeTransactionsTo(nextDoc, authorId);\n\n const delta = docDiffToDelta(baselineNode, snapshotNode);\n nextDoc.transact(() => {\n nextType.applyDelta(delta as any);\n }, authorId);\n\n const renderer = Y.createDiffRenderer(prevDoc, nextDoc, { attrs });\n\n // Clear the live doc first so ProseMirror rebuilds node views from\n // scratch (BlockNote node views resolve their block eagerly via getPos()\n // and throw on a moved node). The diff then inserts the attributed content\n // against an empty doc.\n editor.replaceBlocks(editor.document, []);\n\n editor.exec((state, dispatch) => {\n const tr = getProseMirrorTrFromYFragment({\n tr: state.tr,\n fragment: nextType,\n renderer,\n });\n if (dispatch) {\n dispatch(tr);\n }\n return true;\n });\n\n prevDoc.destroy();\n nextDoc.destroy();\n };\n\n /**\n * Leave diff view: clear the (mark-carrying) document and restore the given\n * blocks. Clears first so stale node views for block-level marks are torn\n * down instead of reused.\n */\n const clearDiff = (restore: Block<any, any, any>[]) => {\n editor.replaceBlocks(editor.document, []);\n editor.replaceBlocks(editor.document, restore);\n };\n\n return {\n key: \"diffVersioning\",\n // Compose AttributionExtension: registers the y-attributed-* marks and\n // drives their colors + hover-tooltip names from the (static) user store.\n blockNoteExtensions: [\n AttributionExtension({\n resolveUsers,\n getAttributionMarkClassName: options?.getAttributionMarkClassName,\n }),\n ],\n renderDiff,\n clearDiff,\n };\n },\n);\n","import type { Awareness } from \"@y/protocols/awareness\";\nimport type * as Y from \"@y/y\";\nimport { BlockNoteEditorOptions } from \"../../editor/BlockNoteEditor.js\";\nimport {\n createExtension,\n ExtensionOptions,\n} from \"../../editor/BlockNoteExtension.js\";\nimport {\n VersioningEndpoints,\n VersioningEndpointsFactory,\n VersioningExtension,\n} from \"../../extensions/Versioning/index.js\";\nimport { normalizeToUserStore, UserStoreOrResolver } from \"../../user/index.js\";\nimport { AttributionExtension } from \"./AttributionExtension.js\";\nimport { RelativePositionMappingExtension } from \"./RelativePositionMapping.js\";\nimport { SuggestionsExtension } from \"./Suggestions.js\";\nimport { createYjsVersioningAdapter } from \"./Versioning.js\";\nimport { CollaborationUser, YCursorExtension } from \"./YCursorPlugin.js\";\nimport type { GetAttributionMarkClassName } from \"./YAttributionMarks.js\";\nimport { YSyncExtension } from \"./YSync.js\";\n\nexport type CollaborationOptions = {\n /**\n * The Yjs Type that's used for collaboration.\n */\n fragment: Y.Type;\n /**\n * The user info for the current user that's shown to other collaborators.\n */\n user: CollaborationUser;\n /**\n * Resolve user information (usernames, colors) for suggestions and versions,\n * used to drive suggestion-author tooltips, suggestion colors and\n * version-history author labels.\n *\n * Either a resolver function (called with the ids of users that are not yet\n * cached, returning their information — a user store is built from it\n * internally) or a pre-built user store (see `createUserStore`). Pass the same\n * store you give the comments extension so a single de-duped user cache is\n * shared across comments, suggestions and versioning.\n */\n resolveUsers?: UserStoreOrResolver;\n /**\n * A Yjs provider (used for awareness / cursor information)\n */\n provider?: { awareness?: Awareness };\n /**\n * Optional function to customize how cursors of users are rendered\n */\n renderCursor?: (user: CollaborationUser) => HTMLElement;\n /**\n * Optional flag to set when the user label should be shown with the default\n * collaboration cursor. Setting to \"always\" will always show the label,\n * while \"activity\" will only show the label when the user moves the cursor\n * or types. Defaults to \"activity\".\n */\n showCursorLabels?: \"always\" | \"activity\";\n /**\n * The renderer for the collaboration.\n */\n renderer?: Y.DiffRenderer;\n /**\n * The suggestion doc for the collaboration. If using suggestion mode\n */\n suggestionDoc?: Y.Doc;\n\n /**\n * Optional callback to override suggestion-mark styling by change type instead\n * of by author. Given a mark's content/modification type, return a class name\n * applied to the mark and its hover tooltip; the per-user color is then\n * dropped for that mark. See {@link GetAttributionMarkClassName}.\n */\n getAttributionMarkClassName?: GetAttributionMarkClassName;\n\n /**\n * The endpoints for the versioning functionality.\n */\n versioningEndpoints?:\n | VersioningEndpoints<Y.Type, Uint8Array>\n | VersioningEndpointsFactory<Y.Type, Uint8Array>;\n};\n\nexport const CollaborationExtension = createExtension(\n ({ editor, options }: ExtensionOptions<CollaborationOptions>) => {\n // Build a single user store here (from a resolver callback or a store the\n // consumer passed in) and hand that same store down to every sub-extension\n // that needs it — suggestions, suggestion-mark tooltips/colors, versioning —\n // so they share one de-duped cache. Passing the resolved store (rather than\n // the raw resolver) is what guarantees the sharing: each child re-normalizes\n // it to itself instead of building its own.\n const userStore = normalizeToUserStore(options.resolveUsers);\n const optionsWithUserStore = { ...options, resolveUsers: userStore };\n return {\n key: \"collaboration\",\n userStore,\n blockNoteExtensions: [\n options.suggestionDoc\n ? SuggestionsExtension(optionsWithUserStore)\n : null,\n RelativePositionMappingExtension(),\n YSyncExtension(optionsWithUserStore),\n YCursorExtension(options),\n options.versioningEndpoints\n ? VersioningExtension({\n ...createYjsVersioningAdapter(editor, options.fragment),\n endpoints: options.versioningEndpoints,\n resolveUsers: userStore,\n })\n : null,\n AttributionExtension({\n resolveUsers: userStore,\n getAttributionMarkClassName: options.getAttributionMarkClassName,\n }),\n ].filter((a) => a !== null),\n } as const;\n },\n);\n\nexport function withCollaboration<\n Options extends Partial<BlockNoteEditorOptions<any, any, any>>,\n>(\n options: Options & {\n /**\n * Options for configuring the collaboration functionality.\n */\n collaboration: CollaborationOptions;\n },\n): Options {\n if (options.initialContent) {\n // eslint-disable-next-line no-console\n console.warn(\n \"When using Collaboration, initialContent might cause conflicts, because changes should come from the collaboration provider\",\n );\n }\n return {\n ...options,\n extensions: [\n ...(options.extensions ?? []),\n CollaborationExtension(options.collaboration),\n ],\n // We disable the default prosemirror history plugin, since it's not compatible with yjs\n disableExtensions: [\"history\", ...(options.disableExtensions ?? [])],\n // We don't want the default initial content, since it will generate a random id for the initial block on each client,\n // leading to conflicts when syncing happens afterwards.\n initialContent: [{ type: \"paragraph\", id: \"initialBlockId\" }],\n };\n}\n\nexport * from \"./AttributionExtension.js\";\nexport * from \"./DiffVersioningExtension.js\";\nexport * from \"./RelativePositionMapping.js\";\nexport * from \"./Suggestions.js\";\nexport * from \"./Versioning.js\";\nexport * from \"./YAttributionMarks.js\";\nexport * from \"./YCursorPlugin.js\";\nexport * from \"./YSync.js\";\n","import * as Y from \"@y/y\";\nimport type {\n CommentData,\n CommentReactionData,\n ThreadData,\n} from \"../../comments/types.js\";\n\nexport function commentToYType(comment: CommentData) {\n const yType = new Y.Type();\n yType.setAttr(\"id\", comment.id);\n yType.setAttr(\"userId\", comment.userId);\n yType.setAttr(\"createdAt\", comment.createdAt.getTime());\n yType.setAttr(\"updatedAt\", comment.updatedAt.getTime());\n if (comment.deletedAt) {\n yType.setAttr(\"deletedAt\", comment.deletedAt.getTime());\n yType.setAttr(\"body\", undefined);\n } else {\n yType.setAttr(\"body\", comment.body);\n }\n if (comment.reactions.length > 0) {\n throw new Error(\"Reactions should be empty in commentToYType\");\n }\n\n /**\n * Reactions are stored in a map keyed by {userId-emoji},\n * this makes it easy to add / remove reactions and in a way that works local-first.\n * The cost is that \"reading\" the reactions is a bit more complex (see yTypeToReactions).\n */\n yType.setAttr(\"reactionsByUser\", new Y.Type());\n yType.setAttr(\"metadata\", comment.metadata);\n\n return yType;\n}\n\nexport function threadToYType(thread: ThreadData) {\n const yType = new Y.Type();\n yType.setAttr(\"id\", thread.id);\n yType.setAttr(\"createdAt\", thread.createdAt.getTime());\n yType.setAttr(\"updatedAt\", thread.updatedAt.getTime());\n const commentsType = new Y.Type();\n\n commentsType.push(thread.comments.map((comment) => commentToYType(comment)));\n\n yType.setAttr(\"comments\", commentsType);\n yType.setAttr(\"resolved\", thread.resolved);\n yType.setAttr(\"resolvedUpdatedAt\", thread.resolvedUpdatedAt?.getTime());\n yType.setAttr(\"resolvedBy\", thread.resolvedBy);\n yType.setAttr(\"metadata\", thread.metadata);\n return yType;\n}\n\ntype SingleUserCommentReactionData = {\n emoji: string;\n createdAt: Date;\n userId: string;\n};\n\nexport function yTypeToReaction(yType: Y.Type): SingleUserCommentReactionData {\n return {\n emoji: yType.getAttr(\"emoji\"),\n createdAt: new Date(yType.getAttr(\"createdAt\")),\n userId: yType.getAttr(\"userId\"),\n };\n}\n\nfunction yTypeToReactions(yType: Y.Type): CommentReactionData[] {\n const flatReactions = [...yType.attrValues()].map((reaction: Y.Type) =>\n yTypeToReaction(reaction),\n );\n // combine reactions by the same emoji\n return flatReactions.reduce(\n (acc: CommentReactionData[], reaction: SingleUserCommentReactionData) => {\n const existingReaction = acc.find((r) => r.emoji === reaction.emoji);\n if (existingReaction) {\n existingReaction.userIds.push(reaction.userId);\n existingReaction.createdAt = new Date(\n Math.min(\n existingReaction.createdAt.getTime(),\n reaction.createdAt.getTime(),\n ),\n );\n } else {\n acc.push({\n emoji: reaction.emoji,\n createdAt: reaction.createdAt,\n userIds: [reaction.userId],\n });\n }\n return acc;\n },\n [] as CommentReactionData[],\n );\n}\n\nexport function yTypeToComment(yType: Y.Type): CommentData {\n return {\n type: \"comment\",\n id: yType.getAttr(\"id\"),\n userId: yType.getAttr(\"userId\"),\n createdAt: new Date(yType.getAttr(\"createdAt\")),\n updatedAt: new Date(yType.getAttr(\"updatedAt\")),\n deletedAt: yType.getAttr(\"deletedAt\")\n ? new Date(yType.getAttr(\"deletedAt\"))\n : undefined,\n reactions: yTypeToReactions(yType.getAttr(\"reactionsByUser\")),\n metadata: yType.getAttr(\"metadata\"),\n body: yType.getAttr(\"body\"),\n };\n}\n\nexport function yTypeToThread(yType: Y.Type): ThreadData {\n return {\n type: \"thread\",\n id: yType.getAttr(\"id\"),\n createdAt: new Date(yType.getAttr(\"createdAt\")),\n updatedAt: new Date(yType.getAttr(\"updatedAt\")),\n comments: ((yType.getAttr(\"comments\") as Y.Type)?.toArray() || []).map(\n (comment) => yTypeToComment(comment as Y.Type),\n ),\n resolved: yType.getAttr(\"resolved\"),\n resolvedUpdatedAt: new Date(yType.getAttr(\"resolvedUpdatedAt\")),\n resolvedBy: yType.getAttr(\"resolvedBy\"),\n metadata: yType.getAttr(\"metadata\"),\n };\n}\n","import * as Y from \"@y/y\";\nimport type { ThreadData } from \"../../comments/types.js\";\nimport { ThreadStore } from \"../../comments/threadstore/ThreadStore.js\";\nimport type { ThreadStoreAuth } from \"../../comments/threadstore/ThreadStoreAuth.js\";\nimport { yTypeToThread } from \"./yjsHelpers.js\";\n\n/**\n * This is an abstract class that only implements the READ methods required by the ThreadStore interface.\n * The data is read from a @y/y Type used as a map (via attributes).\n */\nexport abstract class YjsThreadStoreBase extends ThreadStore {\n constructor(\n protected readonly threadsYType: Y.Type,\n auth: ThreadStoreAuth,\n ) {\n super(auth);\n }\n\n // TODO: async / reactive interface?\n public getThread(threadId: string) {\n const yThread = this.threadsYType.getAttr(threadId);\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n const thread = yTypeToThread(yThread);\n return thread;\n }\n\n public getThreads(): Map<string, ThreadData> {\n const threadMap = new Map<string, ThreadData>();\n this.threadsYType.forEachAttr((yThread: any, id: string | number) => {\n if (yThread instanceof Y.Type) {\n threadMap.set(String(id), yTypeToThread(yThread));\n }\n });\n return threadMap;\n }\n\n public subscribe(cb: (threads: Map<string, ThreadData>) => void) {\n const observer = () => {\n cb(this.getThreads());\n };\n\n this.threadsYType.observeDeep(observer);\n\n return () => {\n this.threadsYType.unobserveDeep(observer);\n };\n }\n}\n","import * as Y from \"@y/y\";\nimport type { CommentBody } from \"../../comments/types.js\";\nimport type { ThreadStoreAuth } from \"../../comments/threadstore/ThreadStoreAuth.js\";\nimport { YjsThreadStoreBase } from \"./YjsThreadStoreBase.js\";\n\n/**\n * This is a REST-based implementation of the YjsThreadStoreBase for @y/y (v14).\n * It Reads data directly from the underlying document (same as YjsThreadStore),\n * but for Writes, it sends data to a REST API that should:\n * - check the user has the correct permissions to make the desired changes\n * - apply the updates to the underlying Yjs document\n *\n * (see https://github.com/TypeCellOS/BlockNote-demo-nextjs-hocuspocus)\n *\n * The reason we still use the Yjs document as underlying storage is that it makes it easy to\n * sync updates in real-time to other collaborators.\n * (but technically, you could also implement a different storage altogether\n * and not store the thread related data in the Yjs document)\n */\nexport class RESTYjsThreadStore extends YjsThreadStoreBase {\n constructor(\n private readonly BASE_URL: string,\n private readonly headers: Record<string, string>,\n threadsYType: Y.Type,\n auth: ThreadStoreAuth,\n ) {\n super(threadsYType, auth);\n }\n\n private doRequest = async (path: string, method: string, body?: any) => {\n const response = await fetch(`${this.BASE_URL}${path}`, {\n method,\n body: JSON.stringify(body),\n headers: {\n \"Content-Type\": \"application/json\",\n ...this.headers,\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to ${method} ${path}: ${response.statusText}`);\n }\n\n return response.json();\n };\n\n public addThreadToDocument = async (options: {\n threadId: string;\n selection: {\n head: number;\n anchor: number;\n };\n }) => {\n const { threadId, ...rest } = options;\n return this.doRequest(`/${threadId}/addToDocument`, \"POST\", rest);\n };\n\n public createThread = async (options: {\n initialComment: {\n body: CommentBody;\n metadata?: any;\n };\n metadata?: any;\n }) => {\n return this.doRequest(\"\", \"POST\", options);\n };\n\n public addComment = (options: {\n comment: {\n body: CommentBody;\n metadata?: any;\n };\n threadId: string;\n }) => {\n const { threadId, ...rest } = options;\n return this.doRequest(`/${threadId}/comments`, \"POST\", rest);\n };\n\n public updateComment = (options: {\n comment: {\n body: CommentBody;\n metadata?: any;\n };\n threadId: string;\n commentId: string;\n }) => {\n const { threadId, commentId, ...rest } = options;\n return this.doRequest(`/${threadId}/comments/${commentId}`, \"PUT\", rest);\n };\n\n public deleteComment = (options: {\n threadId: string;\n commentId: string;\n softDelete?: boolean;\n }) => {\n const { threadId, commentId, ...rest } = options;\n return this.doRequest(\n `/${threadId}/comments/${commentId}?soft=${!!rest.softDelete}`,\n \"DELETE\",\n );\n };\n\n public deleteThread = (options: { threadId: string }) => {\n return this.doRequest(`/${options.threadId}`, \"DELETE\");\n };\n\n public resolveThread = (options: { threadId: string }) => {\n return this.doRequest(`/${options.threadId}/resolve`, \"POST\");\n };\n\n public unresolveThread = (options: { threadId: string }) => {\n return this.doRequest(`/${options.threadId}/unresolve`, \"POST\");\n };\n\n public addReaction = (options: {\n threadId: string;\n commentId: string;\n emoji: string;\n }) => {\n const { threadId, commentId, ...rest } = options;\n return this.doRequest(\n `/${threadId}/comments/${commentId}/reactions`,\n \"POST\",\n rest,\n );\n };\n\n public deleteReaction = (options: {\n threadId: string;\n commentId: string;\n emoji: string;\n }) => {\n return this.doRequest(\n `/${options.threadId}/comments/${options.commentId}/reactions/${options.emoji}`,\n \"DELETE\",\n );\n };\n}\n","import { uuidv4 } from \"lib0/random\";\nimport * as Y from \"@y/y\";\nimport type {\n CommentBody,\n CommentData,\n ThreadData,\n} from \"../../comments/types.js\";\nimport type { ThreadStoreAuth } from \"../../comments/threadstore/ThreadStoreAuth.js\";\nimport { YjsThreadStoreBase } from \"./YjsThreadStoreBase.js\";\nimport {\n commentToYType,\n threadToYType,\n yTypeToComment,\n yTypeToThread,\n} from \"./yjsHelpers.js\";\n\n/**\n * This is a @y/y (v14)-based implementation of the ThreadStore interface.\n *\n * It reads and writes thread / comments information directly to the underlying Yjs Document.\n *\n * @important While this is the easiest to add to your app, there are two challenges:\n * - The user needs to be able to write to the Yjs document to store the information.\n * So a user without write access to the Yjs document cannot leave any comments.\n * - Even with write access, the operations are not secure. Unless your Yjs server\n * guards against malicious operations, it's technically possible for one user to make changes to another user's comments, etc.\n * (even though these options are not visible in the UI, a malicious user can make unauthorized changes to the underlying Yjs document)\n */\nexport class YjsThreadStore extends YjsThreadStoreBase {\n constructor(\n private readonly userId: string,\n threadsYType: Y.Type,\n auth: ThreadStoreAuth,\n ) {\n super(threadsYType, auth);\n }\n\n private transact = <T, R>(\n fn: (options: T) => R,\n ): ((options: T) => Promise<R>) => {\n return async (options: T) => {\n return this.threadsYType.doc!.transact(() => {\n return fn(options);\n });\n };\n };\n\n public createThread = this.transact(\n (options: {\n initialComment: {\n body: CommentBody;\n metadata?: any;\n };\n metadata?: any;\n }) => {\n if (!this.auth.canCreateThread()) {\n throw new Error(\"Not authorized\");\n }\n\n const date = new Date();\n\n const comment: CommentData = {\n type: \"comment\",\n id: uuidv4(),\n userId: this.userId,\n createdAt: date,\n updatedAt: date,\n reactions: [],\n metadata: options.initialComment.metadata,\n body: options.initialComment.body,\n };\n\n const thread: ThreadData = {\n type: \"thread\",\n id: uuidv4(),\n createdAt: date,\n updatedAt: date,\n comments: [comment],\n resolved: false,\n metadata: options.metadata,\n };\n\n this.threadsYType.setAttr(thread.id, threadToYType(thread));\n\n return thread;\n },\n );\n\n // YjsThreadStore does not support addThreadToDocument\n public addThreadToDocument = undefined;\n\n public addComment = this.transact(\n (options: {\n comment: {\n body: CommentBody;\n metadata?: any;\n };\n threadId: string;\n }) => {\n const yThread = this.threadsYType.getAttr(options.threadId) as\n | Y.Type\n | undefined;\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n if (!this.auth.canAddComment(yTypeToThread(yThread))) {\n throw new Error(\"Not authorized\");\n }\n\n const date = new Date();\n const comment: CommentData = {\n type: \"comment\",\n id: uuidv4(),\n userId: this.userId,\n createdAt: date,\n updatedAt: date,\n deletedAt: undefined,\n reactions: [],\n metadata: options.comment.metadata,\n body: options.comment.body,\n };\n\n (yThread.getAttr(\"comments\") as Y.Type).push([commentToYType(comment)]);\n\n yThread.setAttr(\"updatedAt\", new Date().getTime());\n return comment;\n },\n );\n\n public updateComment = this.transact(\n (options: {\n comment: {\n body: CommentBody;\n metadata?: any;\n };\n threadId: string;\n commentId: string;\n }) => {\n const yThread = this.threadsYType.getAttr(options.threadId) as\n | Y.Type\n | undefined;\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n const commentsType = yThread.getAttr(\"comments\") as Y.Type;\n const yCommentIndex = yTypeFindIndex(\n commentsType,\n (comment) => (comment as Y.Type).getAttr(\"id\") === options.commentId,\n );\n\n if (yCommentIndex === -1) {\n throw new Error(\"Comment not found\");\n }\n\n const yComment = commentsType.get(yCommentIndex) as Y.Type;\n\n if (!this.auth.canUpdateComment(yTypeToComment(yComment))) {\n throw new Error(\"Not authorized\");\n }\n\n yComment.setAttr(\"body\", options.comment.body);\n yComment.setAttr(\"updatedAt\", new Date().getTime());\n yComment.setAttr(\"metadata\", options.comment.metadata);\n },\n );\n\n public deleteComment = this.transact(\n (options: {\n threadId: string;\n commentId: string;\n softDelete?: boolean;\n }) => {\n const yThread = this.threadsYType.getAttr(options.threadId) as\n | Y.Type\n | undefined;\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n const commentsType = yThread.getAttr(\"comments\") as Y.Type;\n const yCommentIndex = yTypeFindIndex(\n commentsType,\n (comment) => (comment as Y.Type).getAttr(\"id\") === options.commentId,\n );\n\n if (yCommentIndex === -1) {\n throw new Error(\"Comment not found\");\n }\n\n const yComment = commentsType.get(yCommentIndex) as Y.Type;\n\n if (!this.auth.canDeleteComment(yTypeToComment(yComment))) {\n throw new Error(\"Not authorized\");\n }\n\n if (yComment.getAttr(\"deletedAt\")) {\n throw new Error(\"Comment already deleted\");\n }\n\n if (options.softDelete) {\n yComment.setAttr(\"deletedAt\", new Date().getTime());\n yComment.setAttr(\"body\", undefined);\n } else {\n commentsType.delete(yCommentIndex);\n }\n\n if (\n commentsType\n .toArray()\n .every((comment) => (comment as Y.Type).getAttr(\"deletedAt\"))\n ) {\n // all comments deleted\n if (options.softDelete) {\n yThread.setAttr(\"deletedAt\", new Date().getTime());\n } else {\n this.threadsYType.deleteAttr(options.threadId);\n }\n }\n\n yThread.setAttr(\"updatedAt\", new Date().getTime());\n },\n );\n\n public deleteThread = this.transact((options: { threadId: string }) => {\n if (\n !this.auth.canDeleteThread(\n yTypeToThread(this.threadsYType.getAttr(options.threadId) as Y.Type),\n )\n ) {\n throw new Error(\"Not authorized\");\n }\n\n this.threadsYType.deleteAttr(options.threadId);\n });\n\n public resolveThread = this.transact((options: { threadId: string }) => {\n const yThread = this.threadsYType.getAttr(options.threadId) as\n | Y.Type\n | undefined;\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n if (!this.auth.canResolveThread(yTypeToThread(yThread))) {\n throw new Error(\"Not authorized\");\n }\n\n yThread.setAttr(\"resolved\", true);\n yThread.setAttr(\"resolvedUpdatedAt\", new Date().getTime());\n yThread.setAttr(\"resolvedBy\", this.userId);\n });\n\n public unresolveThread = this.transact((options: { threadId: string }) => {\n const yThread = this.threadsYType.getAttr(options.threadId) as\n | Y.Type\n | undefined;\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n if (!this.auth.canUnresolveThread(yTypeToThread(yThread))) {\n throw new Error(\"Not authorized\");\n }\n\n yThread.setAttr(\"resolved\", false);\n yThread.setAttr(\"resolvedUpdatedAt\", new Date().getTime());\n });\n\n public addReaction = this.transact(\n (options: { threadId: string; commentId: string; emoji: string }) => {\n const yThread = this.threadsYType.getAttr(options.threadId) as\n | Y.Type\n | undefined;\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n const commentsType = yThread.getAttr(\"comments\") as Y.Type;\n const yCommentIndex = yTypeFindIndex(\n commentsType,\n (comment) => (comment as Y.Type).getAttr(\"id\") === options.commentId,\n );\n\n if (yCommentIndex === -1) {\n throw new Error(\"Comment not found\");\n }\n\n const yComment = commentsType.get(yCommentIndex) as Y.Type;\n\n if (!this.auth.canAddReaction(yTypeToComment(yComment), options.emoji)) {\n throw new Error(\"Not authorized\");\n }\n\n const date = new Date();\n\n const key = `${this.userId}-${options.emoji}`;\n\n const reactionsByUser = yComment.getAttr(\"reactionsByUser\") as Y.Type;\n\n if (reactionsByUser.hasAttr(key)) {\n // already exists\n return;\n } else {\n const reaction = new Y.Type();\n reaction.setAttr(\"emoji\", options.emoji);\n reaction.setAttr(\"createdAt\", date.getTime());\n reaction.setAttr(\"userId\", this.userId);\n reactionsByUser.setAttr(key, reaction);\n }\n },\n );\n\n public deleteReaction = this.transact(\n (options: { threadId: string; commentId: string; emoji: string }) => {\n const yThread = this.threadsYType.getAttr(options.threadId) as\n | Y.Type\n | undefined;\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n const commentsType = yThread.getAttr(\"comments\") as Y.Type;\n const yCommentIndex = yTypeFindIndex(\n commentsType,\n (comment) => (comment as Y.Type).getAttr(\"id\") === options.commentId,\n );\n\n if (yCommentIndex === -1) {\n throw new Error(\"Comment not found\");\n }\n\n const yComment = commentsType.get(yCommentIndex) as Y.Type;\n\n if (\n !this.auth.canDeleteReaction(yTypeToComment(yComment), options.emoji)\n ) {\n throw new Error(\"Not authorized\");\n }\n\n const key = `${this.userId}-${options.emoji}`;\n\n const reactionsByUser = yComment.getAttr(\"reactionsByUser\") as Y.Type;\n\n reactionsByUser.deleteAttr(key);\n },\n );\n}\n\nfunction yTypeFindIndex(yType: Y.Type, predicate: (item: any) => boolean) {\n for (let i = 0; i < yType.length; i++) {\n if (predicate(yType.get(i))) {\n return i;\n }\n }\n return -1;\n}\n","import * as Y from \"@y/y\";\nimport { decodeAny, encodeAny } from \"lib0/buffer\";\n\nimport {\n CURRENT_VERSION_ID,\n sortSnapshotsNewestFirst,\n VersioningEndpointsFactory,\n type VersioningEndpoints,\n type VersionSnapshot,\n} from \"../../extensions/Versioning/index.js\";\nimport { uint32 } from \"lib0/random\";\nimport { YCursorExtension } from \"../extensions/YCursorPlugin.js\";\nimport { YSyncExtension } from \"../extensions/YSync.js\";\n\n/**\n * Name of the root {@link Y.Type} map on the live collaboration doc that stores\n * a mutable `versionId -> name` mapping. Because YHub attributions are\n * immutable, version names that need to be editable (renamed) live here on the\n * Y.Doc instead of (or in addition to) the immutable `name` attribution.\n */\nconst VERSION_NAMES_MAP = \"__bn_version_names\";\n\n/**\n * Options for creating a YHub versioning endpoints instance.\n */\nexport interface YHubVersioningOptions {\n /**\n * Base URL of the YHub API, including the API prefix\n * (e.g. `\"https://yhub.example.com/api\"`).\n * Must **not** include a trailing slash.\n */\n baseUrl: string;\n\n /** YHub organisation identifier. */\n org: string;\n\n /** Document identifier within the organisation. */\n docId: string;\n\n /**\n * Optional headers to include in every request (e.g. authentication tokens).\n */\n headers?: Record<string, string>;\n\n /**\n * Maximum number of activity entries to fetch when listing versions.\n * @default 50\n */\n activityLimit?: number;\n\n /**\n * When set, forwarded as the `group` query param to the YHub activity API,\n * controlling whether adjacent edits are grouped into single entries.\n */\n group?: boolean;\n\n /**\n * Maximum gap (in ms) between edits for them to be grouped together.\n * Forwarded as the `groupMaxGap` query param.\n * @default 10000\n */\n groupMaxGap?: number;\n\n /**\n * Maximum total duration (in ms) a single group of edits may span.\n * When set, forwarded as the `groupMaxDuration` query param.\n */\n groupMaxDuration?: number;\n\n // TODO mergeUsers is not in standard yhub, but it exists in our fork.\n /**\n * When `true`, adjacent edits are grouped together even when made by\n * *different* users (their ids accumulate in the grouped entry's `by`).\n * When `false` (the default), only same-user adjacent edits are merged.\n * Forwarded as the `mergeUsers` query param.\n * @default false\n */\n mergeUsers?: boolean;\n}\n\n/**\n * Shape of a single activity entry returned by the YHub\n * `GET /api/activity/v1/{org}/{docId}` endpoint (after `decodeAny`).\n */\ninterface YHubActivityEntry {\n /** Start of the change window (unix-ms timestamp). */\n from: number;\n /** End of the change window (unix-ms timestamp). */\n to: number;\n /** Comma separated list of user-ids that matches the attribution */\n by?: string;\n /** Custom attribution key-value pairs (when `customAttributions=true`). */\n customAttributions?: Array<{ k: string; v: string }>;\n}\n\n/**\n * Shape returned by the YHub `GET /api/changeset/v1/{org}/{docId}` endpoint\n * (after `decodeAny`).\n */\ninterface YHubChangeset {\n /** Full Y.Doc state at the `to` timestamp. */\n ydoc?: Uint8Array;\n /**\n * Encoded {@link Y.ContentMap} describing who authored each change in the\n * window and when. Present when the changeset is requested with\n * `attributions=true`.\n */\n attributions?: Uint8Array;\n}\n\n/** Shape returned by the YHub activity endpoint. */\ninterface YHubActivityResponse {\n activity: YHubActivityEntry[];\n}\n\n/**\n * Whether an activity entry is a version marker (created with a `type:version`\n * custom attribution) as opposed to a plain edit.\n */\nfunction isVersionEntry(entry: YHubActivityEntry): boolean {\n return (\n entry.customAttributions?.some(\n (a) => a.k === \"type\" && a.v === \"version\",\n ) ?? false\n );\n}\n\n/**\n * Convert a YHub activity entry into a {@link VersionSnapshot}.\n *\n * Version markers (entries with a `type:version` custom attribution) map to\n * named snapshots: the `id` attribution becomes the snapshot identifier and the\n * `name` attribution its name. Any other (plain edit) entry maps to a\n * history-only snapshot with a synthetic `history-<to>-<index>` id and no name.\n * In both cases the entry's `by` user-ids are passed through raw on\n * {@link VersionSnapshot.by} — resolving them to user info is the view layer's\n * job.\n *\n * The history id embeds the entry's `index` within the activity response\n * because YHub can emit multiple activity entries sharing the same `to`\n * timestamp (e.g. distinct same-`insertAt` patches that grouping did not merge),\n * and `to` alone would then produce colliding `history-<to>` ids — duplicate\n * React keys in the sidebar. The `index` disambiguates them. The changeset\n * lookups (`getContent`/`getAttributions`/`restore`) key off\n * {@link VersionSnapshot.createdAt} (= `entry.to`), never the id, so embedding\n * the index in the id is safe.\n */\nfunction activityToSnapshot(\n entry: YHubActivityEntry,\n index: number,\n): VersionSnapshot | undefined {\n const by = entry.by\n ?.split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n const byField = by && by.length > 0 ? by : undefined;\n\n if (isVersionEntry(entry)) {\n const id = entry.customAttributions?.find((a) => a.k === \"id\")?.v;\n if (id === undefined) {\n return undefined;\n }\n const attributionName = entry.customAttributions?.find(\n (a) => a.k === \"name\",\n )?.v;\n return {\n id,\n name: attributionName,\n createdAt: entry.to,\n updatedAt: entry.to,\n by: byField,\n };\n }\n\n return {\n id: `history-${entry.to}-${index}`,\n createdAt: entry.to,\n updatedAt: entry.to,\n by: byField,\n };\n}\n\nasync function yhubFetch(\n url: string,\n headers: Record<string, string>,\n init?: RequestInit,\n): Promise<ArrayBuffer> {\n const res = await fetch(url, {\n ...init,\n headers: {\n ...headers,\n ...(init?.headers instanceof Headers\n ? Object.fromEntries(init.headers.entries())\n : Array.isArray(init?.headers)\n ? Object.fromEntries(init.headers)\n : init?.headers),\n },\n });\n if (!res.ok) {\n throw new Error(\n `YHub request failed: ${res.status} ${res.statusText} (${url})`,\n );\n }\n return res.arrayBuffer();\n}\n\n/**\n * Create a {@link VersioningEndpoints} implementation backed by the\n * [YHub](https://github.com/yjs/yhub) HTTP API.\n *\n * Versions are created by PATCHing the document with custom attributions\n * (`type:version` + an optional `name`). The `list` endpoint returns the full\n * activity timeline, mapping `type:version` markers to named versions and every\n * other entry to a history-only snapshot, so the sidebar can show both the\n * named versions and the complete edit history.\n *\n * A version's id lives in immutable YHub attributions (`type:version` + `id`),\n * so it is fixed at creation time. Version *names*, however, are stored in a\n * mutable `__bn_version_names` map on the live collaboration doc (see\n * {@link VERSION_NAMES_MAP}), so `rename` is supported and simply updates that\n * store.\n *\n * @example\n * ```ts\n * import { withCollaboration } from \"@blocknote/core/y\";\n * import { createYHubVersioningEndpoints } from \"@blocknote/core/y\";\n *\n * const editor = BlockNoteEditor.create(\n * withCollaboration({\n * collaboration: {\n * fragment,\n * user: { name: \"Alice\", color: \"#ff0\" },\n * provider,\n * versioningEndpoints: createYHubVersioningEndpoints({\n * baseUrl: \"https://yhub.example.com/api\",\n * org: \"my-org\",\n * docId: \"my-doc\",\n * }),\n * },\n * }),\n * );\n * ```\n */\nexport function createYHubVersioningEndpoints(\n options: YHubVersioningOptions,\n): VersioningEndpointsFactory<Y.Type, Uint8Array, Y.ContentMap> {\n const {\n baseUrl,\n org,\n docId,\n headers = {},\n activityLimit = 50,\n group,\n } = options;\n\n const activityUrl = `${baseUrl}/activity/v1/${org}/${docId}`;\n const changesetUrl = `${baseUrl}/changeset/v1/${org}/${docId}`;\n const rollbackUrl = `${baseUrl}/rollback/v1/${org}/${docId}`;\n const ydocUrl = `${baseUrl}/ydoc/v1/${org}/${docId}`;\n\n return (editor) => {\n /**\n * The mutable per-id version-name store on the live collaboration doc.\n *\n * Returns the root {@link VERSION_NAMES_MAP} map-typed {@link Y.Type}, which\n * uses `setAttr`/`getAttr` for keyed access (this Yjs fork has a single\n * unified `Y.Type` rather than a distinct `Y.Map`). `undefined` until the\n * live doc has been captured from a `create` call.\n */\n const getVersionNamesMap = (): Y.Type | undefined => {\n const fragment =\n editor.getExtension<typeof YSyncExtension>(\"ySync\")?.fragment.doc;\n // `fragment` is undefined until the live doc has been captured (e.g. no\n // ySync extension attached yet); return undefined rather than throwing so\n // callers can gracefully fall back to the immutable name attribution.\n return fragment?.get(VERSION_NAMES_MAP);\n };\n\n /**\n * Build the synthetic \"current version\" snapshot, or `undefined` when the\n * live document matches the latest saved version (no edits since).\n *\n * Both lookups are made here, independently of the grouped `list()` request:\n *\n * - the newest activity entry of *any* kind (ungrouped, so its `to` is the\n * true last-edit time), and\n * - the newest **version marker** (via the `withCustomAttributions`\n * server-side filter).\n *\n * Deriving the marker time from `list()`'s grouped entries would be wrong:\n * with grouping (especially `mergeUsers`) the newest marker's group absorbs\n * the later unsaved edit, so the group's `to` equals the edit's `to` and the\n * comparison below can never fire. Fetching the marker unmerged avoids that.\n */\n const getCurrentVersionEntry = async (): Promise<\n VersionSnapshot | undefined\n > => {\n const latestParams = new URLSearchParams({\n order: \"desc\",\n limit: \"1\",\n customAttributions: \"true\",\n });\n const latestVersionParams = new URLSearchParams({\n order: \"desc\",\n limit: \"1\",\n customAttributions: \"true\",\n // Server-side filter to `type:version` markers only, so this ignores the\n // plain edits that would otherwise be the newest entries.\n withCustomAttributions: \"type:version\",\n });\n\n const [latestBuf, latestVersionBuf] = await Promise.all([\n yhubFetch(`${activityUrl}?${latestParams}`, headers),\n yhubFetch(`${activityUrl}?${latestVersionParams}`, headers),\n ]);\n const latestEdit = (\n decodeAny(new Uint8Array(latestBuf)) as YHubActivityResponse\n ).activity[0];\n const latestVersion = (\n decodeAny(new Uint8Array(latestVersionBuf)) as YHubActivityResponse\n ).activity[0];\n\n if (!latestEdit || latestEdit.to <= (latestVersion?.to ?? 0)) {\n return undefined;\n }\n\n // Build the synthetic entry directly rather than via `activityToSnapshot`,\n // whose `id` comes from a string-typed wire attribution — the current\n // entry's id is the `CURRENT_VERSION_ID` symbol, not a real version id.\n const by =\n latestEdit.by\n ?.split(\",\")\n .map((t) => t.trim())\n .filter(Boolean) ?? [];\n return {\n id: CURRENT_VERSION_ID,\n createdAt: latestEdit.to,\n updatedAt: latestEdit.to,\n by: by.length > 0 ? by : undefined,\n };\n };\n\n /**\n * PATCH the current document state to YHub, optionally with custom\n * attributions. Used both for creating named version markers and for\n * backing up the document before a restore.\n */\n const patchDoc = async (\n fragment: Y.Type,\n customAttributions: Array<{ k: string; v: any }>,\n by?: string,\n ) => {\n const doc = fragment.doc;\n if (!doc) {\n throw new Error(\n \"Cannot patch document: the Y.Type is not attached to a Y.Doc.\",\n );\n }\n\n // YHub only records custom attributions when they attach to NEW content\n // that survives its server-side diff. An update-less PATCH is rejected\n // (400 — \"at least one of update or awareness must be present\"), and even\n // if it weren't, there'd be no content for the attributions to ride on, so\n // no activity entry is created. YHub has no metadata-only marker path.\n //\n // So we introduce a tiny piece of novel content for the marker to attach\n // to: a single insert into a dedicated `__bn_version_markers` fragment that\n // the editor never renders. A fresh Y.Doc guarantees a clientID/content the\n // server has never seen, so the diff is non-empty and the attributions land\n // on it. The reconstructed document at this version's timestamp still\n // contains the full editor content — this marker only ever lives in the\n // throwaway fragment.\n const markerDoc = new Y.Doc();\n markerDoc.get(\"__bn_version_markers\", \"XmlFragment\").insert(0, [\"v\"]);\n const update = Y.encodeStateAsUpdate(markerDoc);\n\n const body: Record<string, unknown> = { update, customAttributions };\n if (by) {\n body.by = by;\n }\n\n await yhubFetch(ydocUrl, headers, {\n method: \"PATCH\",\n body: encodeAny(body) as BufferSource,\n });\n };\n\n /**\n * Create a named version marker for the current document state by PATCHing\n * it with `type:version` custom attributions.\n */\n const create: VersioningEndpoints<\n Y.Type,\n Uint8Array,\n Y.ContentMap\n >[\"create\"] = async (fragment, options) => {\n const id = String(uint32());\n const now = Date.now();\n\n if (options?.name) {\n getVersionNamesMap()?.setAttr(id, options.name);\n }\n\n const customAttributions: Array<{ k: string; v: string }> = [\n { k: \"type\", v: \"version\" },\n { k: \"id\", v: id },\n ];\n if (options?.name) {\n customAttributions.push({ k: \"name\", v: options.name });\n }\n\n const user = editor\n .getExtension<typeof YCursorExtension>(\"yCursor\")\n ?.getUser();\n await patchDoc(fragment, customAttributions, user?.id);\n\n return {\n id,\n name: options?.name,\n createdAt: now,\n updatedAt: now,\n by: user?.id,\n };\n };\n\n /**\n * Reconstruct the full document state as it was at a given `to` timestamp.\n *\n * The changeset endpoint builds `ydoc` purely from the `to` timestamp\n * range — it ignores `withCustomAttributions` for doc reconstruction (that\n * filter only scopes the attribution overlay). So historical document state\n * can only be retrieved by timestamp, never by the version's `id`.\n */\n const getContentAt = async (to: number): Promise<Uint8Array> => {\n const params = new URLSearchParams({\n ydoc: \"true\",\n to: String(to),\n });\n\n const buf = await yhubFetch(`${changesetUrl}?${params}`, headers);\n const changeset = decodeAny(new Uint8Array(buf)) as YHubChangeset;\n\n if (!changeset.ydoc) {\n throw new Error(`YHub returned no document state at timestamp ${to}.`);\n }\n\n return Y.convertUpdateFormatV1ToV2(changeset.ydoc);\n };\n\n /**\n * Fetch the full document content for a saved version snapshot.\n *\n * The snapshot's `createdAt` is the activity entry's `to` timestamp (see\n * {@link activityToSnapshot}), which is exactly what the changeset API needs.\n */\n const getContent: VersioningEndpoints<\n Y.Type,\n Uint8Array,\n Y.ContentMap\n >[\"getContent\"] = async (snapshot) => {\n return getContentAt(snapshot.createdAt);\n };\n\n /**\n * Fetch the authorship attributions for the changes between two snapshots\n * (or from the start of the document when `compareTo` is omitted).\n *\n * Snapshots carry their `to` timestamp directly in `createdAt`, so no\n * activity lookup is needed to resolve the changeset window.\n */\n const getAttributions: VersioningEndpoints<\n Y.Type,\n Uint8Array,\n Y.ContentMap\n >[\"getAttributions\"] = async (snapshot, compareTo) => {\n const to = snapshot.createdAt;\n const from = compareTo !== undefined ? compareTo.createdAt : 0;\n\n const params = new URLSearchParams({\n from: String(from),\n to: String(to),\n attributions: \"true\",\n });\n\n const buf = await yhubFetch(`${changesetUrl}?${params}`, headers);\n const changeset = decodeAny(new Uint8Array(buf)) as YHubChangeset;\n\n if (!changeset.attributions) {\n throw new Error(\n `YHub returned no attributions for snapshot ${String(snapshot.id)}.`,\n );\n }\n\n return Y.decodeContentMap(changeset.attributions);\n };\n\n /**\n * Restore the document to a saved version: fetch the target version's\n * content and roll back everything after it.\n *\n * The snapshot's `createdAt` is the activity entry's `to` timestamp.\n */\n const restore: VersioningEndpoints<\n Y.Type,\n Uint8Array,\n Y.ContentMap\n >[\"restore\"] = async (_fragment, snapshot) => {\n const to = snapshot.createdAt;\n const snapshotContent = await getContentAt(to);\n\n await yhubFetch(rollbackUrl, headers, {\n method: \"POST\",\n body: encodeAny({ from: to }) as BufferSource,\n });\n\n return snapshotContent;\n };\n\n /**\n * Rename a saved version by updating its entry in the mutable\n * {@link VERSION_NAMES_MAP} store on the live collaboration doc.\n *\n * The version's `id` remains fixed in its immutable YHub attributions —\n * only the editable name in the map is changed. Passing an empty or\n * `undefined` name clears the entry (falling back to the immutable `name`\n * attribution captured at creation time).\n */\n const rename: VersioningEndpoints<\n Y.Type,\n Uint8Array,\n Y.ContentMap\n >[\"rename\"] = async (snapshot, name) => {\n if (typeof snapshot.id !== \"string\") {\n // CURRENT_VERSION_ID (symbol) is not renameable.\n return;\n }\n const map = getVersionNamesMap();\n if (!map) {\n throw new Error(\n \"Cannot rename version: no live collaboration document is available.\",\n );\n }\n if (name === undefined || name === \"\") {\n map.deleteAttr(snapshot.id);\n } else {\n map.setAttr(snapshot.id, name);\n }\n };\n\n /**\n * List the full version timeline (newest first), plus a synthetic\n * \"current version\" entry when the live document has unsaved edits.\n *\n * Returns the entire activity timeline: `type:version` markers are mapped\n * to named snapshots and every other entry to a history-only snapshot (see\n * {@link activityToSnapshot}), so the sidebar can offer both a \"named\n * versions\" and a full \"history\" view. Author user-ids are passed through\n * raw on {@link VersionSnapshot.by} — the view layer resolves them to user\n * info via the versioning extension's user store.\n */\n const list: VersioningEndpoints<\n Y.Type,\n Uint8Array,\n Y.ContentMap\n >[\"list\"] = async () => {\n // Read the grouping knobs fresh from `options` so a caller mutating the\n // object it passed in reconfigures grouping on the next refresh (see the\n // note where these are deliberately left out of the destructure above).\n const groupMaxGap = options.groupMaxGap ?? 10000;\n const groupMaxDuration = options.groupMaxDuration;\n const mergeUsers = options.mergeUsers;\n\n const params = new URLSearchParams({\n order: \"desc\",\n limit: String(activityLimit),\n customAttributions: \"true\",\n });\n // Always send a concrete `groupMaxGap`. Sending\n // `String(undefined)` here would make the server `parseInt(\"undefined\")`\n // to NaN, silently disabling grouping — which surfaces every same-`to`\n // attribution as its own history entry and produces duplicate React keys.\n params.set(\"groupMaxGap\", String(groupMaxGap));\n if (group !== undefined) {\n params.set(\"group\", String(group));\n }\n if (groupMaxDuration !== undefined) {\n params.set(\"groupMaxDuration\", String(groupMaxDuration));\n }\n if (mergeUsers !== undefined) {\n params.set(\"mergeUsers\", String(mergeUsers));\n }\n\n const buf = await yhubFetch(`${activityUrl}?${params}`, headers);\n const { activity: entries } = decodeAny(\n new Uint8Array(buf),\n ) as YHubActivityResponse;\n\n const snapshots = sortSnapshotsNewestFirst(\n entries\n .map((entry, i) => activityToSnapshot(entry, i))\n .filter((s): s is VersionSnapshot => s !== undefined)\n // Prefer the mutable per-id name from the live doc's\n // `__bn_version_names` store over the immutable `name` attribution,\n // so renames (which only mutate that store) are reflected here.\n .map((snapshot) => {\n const attributionName = snapshot.name;\n const mappedName =\n (typeof snapshot.id === \"string\"\n ? (getVersionNamesMap()?.getAttr(snapshot.id) as\n | string\n | undefined)\n : undefined) ?? attributionName;\n return { ...snapshot, name: mappedName };\n }),\n );\n\n // Surface a \"current version\" entry when the live document has edits\n // beyond the most recent saved version marker. `getCurrentVersionEntry`\n // makes its own unmerged lookups (see there), so it is unaffected by the\n // grouping/mergeUsers params used for the list above.\n //\n // This only re-evaluates when `list()` runs (sidebar open / refresh),\n // which matches how YHub versions load today.\n const currentEntry = await getCurrentVersionEntry();\n return currentEntry ? [currentEntry, ...snapshots] : snapshots;\n };\n\n return {\n list,\n create,\n getContent,\n getAttributions,\n restore,\n rename,\n };\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AAuDA,IAAa,KACX,GACA,MAEA,MAAW,KAAA,IACP,KAAA,IACA,OAAO,KAAW,WAChB,IACA,EAAO,IAmBT,KAEF,GACA,OAKD,EAAE,SAAM,gBAAgD;CACvD,IAAM,IAAS,GAAS,QAIlB,IACJ,MAAS,WACL,QACA,MAAS,WACP,QACA,IACE,SACA,OACJ,IAAM,SAAS,cAAc,CAAG;CAMtC,AAJA,OAAO,OAAO,EAAI,SAAS;EACzB,SAAS,KAAK,UAAU,EAAK,MAAM,OAAU;EAC7C,QAAQ,OAAO,CAAM;CACvB,CAAC,GACG,MAAS,mBACX,EAAI,QAAQ,OAAU,gBACtB,EAAI,QAAQ,SAAY,KAAK,UAAU,EAAK,MAAM,MAAS;CAS7D,IAAM,IAAmB,EACvB,GAAS,8BAA8B;EACrC,aAAa,IAAS,mBAAmB;EACzC,kBAAkB,MAAS,iBAAiB,WAAW;CACzD,CAAC,GACD,SACF,GAcM,KADW,EAAK,MAAM,WAAkC,CAAC,EAAA,CACvC,IAClB,IAAW,IACb,EAAuB,CAAO,IAC9B,EAAiB;CACrB,IAAI,GACF,EAAI,MAAM,UAAU;MACf;EACL,IAAM,IAAQ,IACV,OAAO,EAAkB,CAAO,CAAC,CAAC,MAAM,IAAI,EAAS,MAAM,KAC3D,EAAS,OACP,IAAO,IACT,OAAO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AAC,GAEM;GACT;GAqHE,eAtGmB,GAAU,MAAS;IACtC,IAAI,OAAO,EAAS,MAAO,UAEzB;IAEF,IAAM,IAAM,EAAmB;IAC/B,IAAI,CAAC,GACH,MAAU,MACR,qEACF;IAEF,AAAI,MAAS,KAAA,KAAa,MAAS,KACjC,EAAI,WAAW,EAAS,EAAE,IAE1B,EAAI,QAAQ,EAAS,IAAI,CAAI;GAEjC;EAuFA;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"y.js","names":[],"sources":["../src/y/extensions/YAttributionMarks.ts","../src/y/extensions/AttributionExtension.ts","../src/y/extensions/YCursorPlugin.ts","../src/y/extensions/blockMatchNodes.ts","../src/y/extensions/persistentBlockGroups.ts","../src/y/extensions/YSync.ts","../src/y/utils.ts","../src/y/extensions/ForkYDoc.ts","../src/y/extensions/RelativePositionMapping.ts","../src/y/extensions/Suggestions.ts","../src/y/extensions/DiffVersioningExtension.ts","../src/y/extensions/index.ts","../src/y/comments/yjsHelpers.ts","../src/y/comments/YjsThreadStoreBase.ts","../src/y/comments/RESTYjsThreadStore.ts","../src/y/comments/YjsThreadStore.ts","../src/y/extensions/snapshotCodec.ts","../src/y/extensions/snapshotPreview.ts","../src/y/extensions/Versioning.ts","../src/y/versioning/yhubClient.ts","../src/y/versioning/yhub.ts"],"sourcesContent":["import { Mark } from \"@tiptap/core\";\nimport { yattr2markname } from \"@y/prosemirror\";\nimport { Mark as PMMark, MarkSpec } from \"prosemirror-model\";\nimport {\n createExtension,\n type ExtensionOptions,\n} from \"../../editor/BlockNoteExtension.js\";\nimport type { BlockNoteEditor } from \"../../editor/BlockNoteEditor.js\";\nimport { BLOCK_LEVEL_SUGGESTION_GROUP } from \"../../pm-nodes/suggestionMarks.js\";\nimport { NON_FORMATTING_MARK_GROUP } from \"../../schema/markGroups.js\";\nimport {\n fallbackColorForUserId,\n userColorPalette,\n userColorVarNames,\n} from \"../../user/index.js\";\n\n/**\n * Describes a suggestion mark to {@link GetAttributionMarkClassName}: whether it\n * wraps inline content or a whole block, and which kind of change it represents.\n * `modificationType: \"format\"` corresponds to the `y-attributed-format`\n * (modification) mark.\n */\nexport type AttributionMarkStyleInfo = {\n contentType: \"inline-content\" | \"block\";\n modificationType: \"insert\" | \"delete\" | \"format\" | \"attrs\";\n};\n\n/**\n * The class name(s) an app returns to style a suggestion mark. Either:\n * - a single string applied to *both* the mark content and its hover tooltip, or\n * - `{ content, tooltip }` to style the mark content and the tooltip\n * independently.\n */\nexport type AttributionMarkClassNames =\n | string\n | { content: string; tooltip: string };\n\n/**\n * Optional callback to override suggestion-mark styling. Given a mark's\n * {@link AttributionMarkStyleInfo}, it returns the class name(s) to apply (see\n * {@link AttributionMarkClassNames}). When a class is returned, the default\n * per-user color (the `--user-color-*` custom properties and the built-in\n * `.bn-suggestion-mark` / `.bn-suggestion-node` styling) is *not* applied to the\n * mark content, so the class fully controls its appearance — letting an app\n * color suggestions by change type (e.g. green insertions, red deletions)\n * instead of by author.\n */\nexport type GetAttributionMarkClassName = (\n info: AttributionMarkStyleInfo,\n) => AttributionMarkClassNames;\n\n/**\n * Resolve the {@link AttributionMarkClassNames} returned by a\n * {@link GetAttributionMarkClassName} callback to the class name for a single\n * target (the mark `content` or its `tooltip`).\n */\nexport const resolveAttributionMarkClassName = (\n result: AttributionMarkClassNames | undefined,\n target: \"content\" | \"tooltip\",\n): string | undefined =>\n result === undefined\n ? undefined\n : typeof result === \"string\"\n ? result\n : result[target];\n\n/** The upstream attribute mark stores authors separately for each changed property. */\nexport type AttributeChanges = Record<\n string,\n { userIds: string[]; timestamp: number | null }\n>;\n\nexport function getAttributeChanges(mark: PMMark): AttributeChanges {\n return mark.attrs[\"changes\"] ?? {};\n}\n\n/**\n * The format changes of a `y-attributed-format` mark that format the text.\n * Annotation marks such as comments are left out: adding one isn't a\n * formatting change.\n */\nfunction formattingChanges(mark: PMMark): Record<string, string[]> {\n const format: Record<string, string[]> = mark.attrs[\"format\"] ?? {};\n return Object.fromEntries(\n Object.entries(format).filter(([key]) => {\n const group =\n mark.type.schema.marks[yattr2markname(key)]?.spec.group ?? \"\";\n return !group.split(\" \").includes(NON_FORMATTING_MARK_GROUP);\n }),\n );\n}\n\nexport function getAttributionUserIds(mark: PMMark): string[] {\n return mark.type.name === \"y-attributed-attrs\"\n ? [\n ...new Set(\n Object.values(getAttributeChanges(mark)).flatMap(\n (change) => change.userIds,\n ),\n ),\n ]\n : (mark.attrs[\"userIds\"] ?? []);\n}\n\n/**\n * Shared mark view for the attribution marks (insert / delete / modification).\n * It renders the marked content and tags the wrapper with the author(s) via\n * `data-*` attributes. The attribution tooltip shown on hover is handled\n * separately by the `AttributionExtension`, which reads those attributes\n * straight from the DOM — keeping this mark view purely presentational and the\n * tooltip state off of module scope.\n *\n * Author colors are *not* baked into the (deterministic) mark attrs. Instead the\n * wrapper sets the generic `--user-color-*` custom properties the Block.css rules\n * read, sourcing them from the author's *per-user* CSS variable via\n * `var(--user-color-<id>-*, <fallback>)`. Those per-user variables are populated\n * on the editor root by `AttributionExtension` once the user resolves, so a mark\n * shows the deterministic palette fallback immediately and recolors to the\n * author's own color purely through the CSS cascade — no decoration, no doc\n * transaction. See `userColors.ts`.\n */\nconst createAttributionMarkView =\n (\n type: \"insert\" | \"delete\" | \"modification\" | \"attrs\",\n options?: {\n editor?: BlockNoteEditor<any, any, any>;\n getAttributionMarkClassName?: GetAttributionMarkClassName;\n },\n ) =>\n ({ mark, inline }: { mark: PMMark; inline: boolean }) => {\n const editor = options?.editor;\n // A block's id isn't content users edit, so a change to it isn't shown\n // (e.g. a diff pairing a deleted block with the editor's empty one).\n // Inline content may have an `id` prop of its own, which is.\n const allChanges = getAttributeChanges(mark);\n const { id: _id, ...blockChanges } = allChanges;\n const changes = inline ? allChanges : blockChanges;\n const format =\n type === \"modification\" ? formattingChanges(mark) : undefined;\n if (\n (type === \"attrs\" && Object.keys(changes).length === 0) ||\n (format && Object.keys(format).length === 0)\n ) {\n // The mark has no change to show (only a block id or an annotation such\n // as a comment changed). Render the content without a highlight or a\n // tooltip. The mark stays in the document, so suggestion mode still\n // finds the change.\n const dom = document.createElement(inline ? \"span\" : \"div\");\n dom.style.display = \"contents\";\n return { dom, contentDOM: dom };\n }\n // Only the authors of the shown changes, not of a hidden id change or\n // annotation.\n const userIds =\n type === \"attrs\"\n ? [\n ...new Set(\n Object.values(changes).flatMap((change) => change.userIds),\n ),\n ]\n : format\n ? [...new Set(Object.values(format).flat())]\n : getAttributionUserIds(mark);\n // `<ins>`/`<del>` are semantic elements. The modification mark has no\n // dedicated element, so it renders as a `<span>` inline or a `<div>` over a\n // block, matching its `parseDOM` rules.\n const tag =\n type === \"insert\"\n ? \"ins\"\n : type === \"delete\"\n ? \"del\"\n : inline\n ? \"span\"\n : \"div\";\n const dom = document.createElement(tag);\n\n Object.assign(dom.dataset, {\n userIds: JSON.stringify(userIds),\n inline: String(inline),\n });\n if (type === \"attrs\") {\n dom.dataset[\"type\"] = \"attributes\";\n dom.dataset[\"attributes\"] = JSON.stringify(changes);\n }\n if (type === \"modification\") {\n dom.dataset[\"type\"] = \"modification\";\n dom.dataset[\"format\"] = JSON.stringify(format);\n }\n\n // Optional app-provided override: `y-attributed-format` is exposed as\n // `\"format\"`. When a class is returned it's applied to the content element\n // *instead of* the built-in `.bn-suggestion-mark` / `.bn-suggestion-node`\n // classes, and the per-user `--user-color-*` properties are omitted, so the\n // class fully controls the appearance (background, text color, etc.) with no\n // per-user color leaking through (see the type doc).\n const contentClassName = resolveAttributionMarkClassName(\n options?.getAttributionMarkClassName?.({\n contentType: inline ? \"inline-content\" : \"block\",\n modificationType: type === \"modification\" ? \"format\" : type,\n }),\n \"content\",\n );\n\n // The wrapper is always `display: contents` so it never generates a box of\n // its own — an inline `<ins>`/`<del>` around block/table content (e.g. a\n // suggestion spanning table cells) would otherwise break the normal layout.\n // Because a `display: contents` element paints nothing, the highlight is\n // applied to the inner content span (see `.bn-suggestion-mark` in Block.css)\n // using the `--user-color-*` custom properties, which cascade down from here.\n // They're sourced from the author's per-user variable (populated on the\n // editor root by `AttributionExtension`) with the deterministic palette as a\n // fallback, so a mark is colored before the user resolves and recolors via\n // the cascade afterward. When an override class owns the styling, no per-user\n // color is applied at all.\n const firstId = userIds[0];\n const fallback = firstId\n ? fallbackColorForUserId(firstId)\n : userColorPalette[0];\n if (contentClassName) {\n dom.style.cssText = \"display: contents\";\n } else {\n const light = firstId\n ? `var(${userColorVarNames(firstId).light}, ${fallback.light})`\n : fallback.light;\n const dark = firstId\n ? `var(${userColorVarNames(firstId).dark}, ${fallback.dark})`\n : fallback.dark;\n dom.style.cssText =\n \"display: contents\" +\n `; --user-color-light: ${light}; --user-color-dark: ${dark}`;\n }\n\n const contentDOM = document.createElement(\"span\");\n if (inline) {\n // Inline content: the span is a real inline box that carries the highlight\n // (default path) or the app-provided override class.\n contentDOM.className =\n contentClassName ??\n (type === \"delete\"\n ? \"bn-suggestion-mark bn-suggestion-mark--delete\"\n : \"bn-suggestion-mark\");\n } else {\n // Block-level marks wrap block/table structure (e.g. <tr>/<td>/<p>). The\n // span must be `display: contents` so it doesn't inject an inline box into\n // the table layout (which triggers the browser's anonymous-table fixup and\n // breaks the table). Such a span has no box to paint a background on, so\n // the `.bn-suggestion-node` rule highlights its children (the wrapped\n // nodes) instead. An override class is applied to the same span, so it\n // should likewise target its children (e.g. `.my-class > *`).\n contentDOM.style.display = \"contents\";\n contentDOM.className =\n contentClassName ??\n (type === \"delete\"\n ? \"bn-suggestion-node bn-suggestion-node--delete\"\n : \"bn-suggestion-node\");\n if (type === \"delete\") {\n // A deleted block shows a localized \"Deleted\" badge via a `::before`\n // (see Block.css). The badge text is passed down as a CSS string token\n // in `--deleted-label` so the stylesheet stays locale-agnostic; the\n // wrapper is `display: contents` and can't paint a pseudo-element of its\n // own, so the rule renders the badge on the wrapped node instead, which\n // inherits this custom property.\n const label = editor?.dictionary.suggestion_changes.deleted;\n if (label) {\n contentDOM.style.setProperty(\n \"--deleted-label\",\n JSON.stringify(label),\n );\n }\n }\n }\n dom.appendChild(contentDOM);\n\n return {\n dom,\n contentDOM,\n };\n };\n\nexport const YAttributedInsertion = Mark.create<{\n getAttributionMarkClassName?: GetAttributionMarkClassName;\n}>({\n name: \"y-attributed-insert\",\n inclusive: false,\n // Keep default self-exclusion: an updated author list replaces this mark,\n // while insertion, deletion, and formatting marks can still coexist.\n // Two groups: `BLOCK_LEVEL_SUGGESTION_GROUP` lets the mark sit on block nodes\n // (see `suggestionMarks`), so a whole block can be marked as inserted in\n // suggestion mode; `NON_FORMATTING_MARK_GROUP` lets it annotate text inside\n // `\"plain\"` blocks (e.g. code blocks) — see `nonFormattingMarks`.\n group: `${BLOCK_LEVEL_SUGGESTION_GROUP} ${NON_FORMATTING_MARK_GROUP}`,\n addAttributes() {\n return {\n userIds: { default: null },\n };\n },\n addMarkView() {\n return createAttributionMarkView(\"insert\", {\n getAttributionMarkClassName: this.options.getAttributionMarkClassName,\n });\n },\n extendMarkSchema(extension) {\n if (extension.name !== this.name) {\n return {};\n }\n return {\n blocknoteIgnore: true,\n } satisfies MarkSpec;\n },\n});\n\nexport const YAttributedDeletion = Mark.create<{\n editor?: BlockNoteEditor<any, any, any>;\n getAttributionMarkClassName?: GetAttributionMarkClassName;\n}>({\n name: \"y-attributed-delete\",\n inclusive: false,\n group: `${BLOCK_LEVEL_SUGGESTION_GROUP} ${NON_FORMATTING_MARK_GROUP}`,\n addAttributes() {\n return {\n userIds: { default: null },\n };\n },\n addMarkView() {\n return createAttributionMarkView(\"delete\", {\n editor: this.options.editor,\n getAttributionMarkClassName: this.options.getAttributionMarkClassName,\n });\n },\n extendMarkSchema(extension) {\n if (extension.name !== this.name) {\n return {};\n }\n return {\n blocknoteIgnore: true,\n } satisfies MarkSpec;\n },\n});\n\nexport const YAttributedFormat = Mark.create<{\n getAttributionMarkClassName?: GetAttributionMarkClassName;\n}>({\n name: \"y-attributed-format\",\n inclusive: false,\n group: `${BLOCK_LEVEL_SUGGESTION_GROUP} ${NON_FORMATTING_MARK_GROUP}`,\n addAttributes() {\n return {\n userIds: { default: null },\n format: { default: null },\n };\n },\n addMarkView() {\n return createAttributionMarkView(\"modification\", {\n getAttributionMarkClassName: this.options.getAttributionMarkClassName,\n });\n },\n extendMarkSchema(extension) {\n if (extension.name !== this.name) {\n return {};\n }\n return {\n blocknoteIgnore: true,\n } satisfies MarkSpec;\n },\n});\n\nexport const YAttributedAttributes = Mark.create<{\n getAttributionMarkClassName?: GetAttributionMarkClassName;\n}>({\n name: \"y-attributed-attrs\",\n // Wrap insertion/deletion marks, so their content spans still directly wrap\n // the node that paints the highlight or deletion badge (especially tables).\n priority: 110,\n inclusive: false,\n // Keep ProseMirror's default self-exclusion: each update replaces the\n // per-property map instead of stacking stale copies of the mark.\n group: `${BLOCK_LEVEL_SUGGESTION_GROUP} ${NON_FORMATTING_MARK_GROUP}`,\n addAttributes() {\n return { changes: { default: null } };\n },\n addMarkView() {\n return createAttributionMarkView(\"attrs\", {\n getAttributionMarkClassName: this.options.getAttributionMarkClassName,\n });\n },\n extendMarkSchema(extension) {\n return extension.name === this.name\n ? ({ blocknoteIgnore: true } satisfies MarkSpec)\n : {};\n },\n});\n\n/**\n * Bundles the four `y-attributed-*` suggestion marks into a single BlockNote\n * extension, so they can be registered wherever they're actually needed (the\n * Yjs collaboration extension, or a test that exercises suggestions) instead of\n * living in the default schema. The marks opt into being allowed on block nodes\n * via their `blockLevelSuggestion` option — see `suggestionMarks`.\n */\nexport const YAttributionMarksExtension = createExtension(\n ({\n options,\n }: ExtensionOptions<\n { getAttributionMarkClassName?: GetAttributionMarkClassName } | undefined\n >) => ({\n key: \"yAttributionMarks\",\n tiptapExtensions: [\n YAttributedInsertion.configure({\n getAttributionMarkClassName: options?.getAttributionMarkClassName,\n }),\n YAttributedDeletion.configure({\n getAttributionMarkClassName: options?.getAttributionMarkClassName,\n }),\n YAttributedAttributes.configure({\n getAttributionMarkClassName: options?.getAttributionMarkClassName,\n }),\n YAttributedFormat.configure({\n getAttributionMarkClassName: options?.getAttributionMarkClassName,\n }),\n ],\n }),\n);\n","import { Plugin, PluginKey, type Transaction } from \"prosemirror-state\";\nimport { getChangedRangeWithAttrs } from \"../../api/getChangedRangeWithAttrs.js\";\nimport {\n createExtension,\n createStore,\n type ExtensionOptions,\n} from \"../../editor/BlockNoteExtension.js\";\nimport {\n colorsForUserIds,\n userColorVarNames,\n userMarkColors,\n normalizeToUserStore,\n type UserStoreOrResolver,\n} from \"../../user/index.js\";\nimport {\n resolveAttributionMarkClassName,\n getAttributionUserIds,\n YAttributionMarksExtension,\n type AttributionMarkStyleInfo,\n type GetAttributionMarkClassName,\n} from \"./YAttributionMarks.js\";\n\n/** The attribution marks, mapped to their `modificationType`. */\nconst ATTRIBUTION_MARK_TYPES = {\n \"y-attributed-insert\": \"insert\",\n \"y-attributed-delete\": \"delete\",\n \"y-attributed-format\": \"format\",\n \"y-attributed-attrs\": \"attrs\",\n} as const;\n\nconst ATTRIBUTION_LOAD_PLUGIN_KEY = new PluginKey(\"attributionLoadUsers\");\n\n/** Wrapper of an attribution mark; carries its author(s) in `data-user-ids`. */\nconst ATTRIBUTION_MARK_SELECTOR = \"[data-user-ids]\";\n\n/** Parse the JSON-encoded `data-user-ids` attribute; `[]` if missing/malformed. */\nconst parseUserIds = (userIdsJSON: string | undefined): string[] => {\n if (!userIdsJSON) {\n return [];\n }\n let userIds: unknown;\n try {\n userIds = JSON.parse(userIdsJSON);\n } catch {\n return [];\n }\n return Array.isArray(userIds) ? userIds.map(String) : [];\n};\n\n/**\n * The changed format keys from a modification mark's `data-format` (e.g.\n * `[\"bold\", \"italic\"]`); `[]` if missing/malformed or an empty change. This is\n * the raw change context — turning it into a localized label (e.g.\n * `\"Bold, Italic\"`) is a view concern owned by the React layer's\n * `formatChangeLabel`, so core stays i18n-agnostic here.\n */\nconst parseFormatKeys = (formatJSON: string | undefined): string[] => {\n if (!formatJSON) {\n return [];\n }\n let format: unknown;\n try {\n format = JSON.parse(formatJSON);\n } catch {\n return [];\n }\n if (typeof format !== \"object\" || format === null) {\n return [];\n }\n return Object.keys(format);\n};\n\n/**\n * State for the currently-hovered suggestion mark's tooltip (`undefined` when\n * none). The extension computes it; a React controller renders + positions it\n * (see `AttributionTooltipController`).\n */\nexport type AttributionChange =\n | {\n // `change`: a preview (e.g. a diagram) can't show what was inserted or\n // deleted in its hidden source, only that it changed.\n modificationType: \"insert\" | \"delete\" | \"change\";\n format?: never;\n attributes?: never;\n }\n | { modificationType: \"format\"; format?: string[]; attributes?: never }\n | { modificationType: \"attrs\"; attributes: string[]; format?: never };\n\nexport type AttributionTooltipState = AttributionChange & {\n /** The wrapper element the tooltip anchors to (floating-ui reference). */\n anchor: HTMLElement;\n /** Visible surface when its attribution mark covers separately rendered source. */\n reference?: Element;\n /** Per-user background color, resolved from the user store (default path). */\n color: string;\n /** Whether the mark wraps inline content or a whole block. */\n contentType: \"inline-content\" | \"block\";\n /**\n * Resolved usernames (falls back to raw ids), for custom renderers. Empty\n * when the change has no named author, e.g. in a version diff.\n */\n users: string[];\n /**\n * Class name from the `getAttributionMarkClassName` callback (override path).\n * When present, the tooltip applies this and skips the inline `color`.\n */\n className?: string;\n};\n\n/**\n * Resolves the attribution tooltip state for suggestion marks on hover (exposed\n * via a store for React), and loads each mark's author so its color/username\n * resolves. Marks nest, so a single delegated `mouseover` listener picks the\n * `closest` wrapper to the pointer — the innermost mark wins.\n */\nexport const AttributionExtension = createExtension(\n ({\n editor,\n options,\n }: ExtensionOptions<\n | {\n /** Resolves authors to usernames. Optional; unresolved ids show raw. */\n resolveUsers?: UserStoreOrResolver;\n /** See {@link GetAttributionMarkClassName}. */\n getAttributionMarkClassName?: GetAttributionMarkClassName;\n }\n | undefined\n >) => {\n const userStore = normalizeToUserStore(options?.resolveUsers);\n const getAttributionMarkClassName = options?.getAttributionMarkClassName;\n\n const store = createStore<AttributionTooltipState | undefined>(undefined);\n\n // Load the authors of the attribution marks in `tr`'s changed range, so\n // their colors/usernames resolve (colors then flow to marks via `syncRootVars`).\n // The range covers mark-only and node-mark steps too — which suggestion\n // mode adds over existing text and `tr.changedRange()` would miss.\n const loadChangedUsers = (tr: Transaction) => {\n const range = getChangedRangeWithAttrs(tr);\n const ids = new Set<string>();\n if (range) {\n tr.doc.nodesBetween(range.from, range.to, (node) => {\n for (const mark of node.marks) {\n if (\n ATTRIBUTION_MARK_TYPES[\n mark.type.name as keyof typeof ATTRIBUTION_MARK_TYPES\n ]\n ) {\n const userIds = getAttributionUserIds(mark);\n userIds?.forEach((id) => ids.add(id));\n }\n }\n return true;\n });\n }\n if (ids.size > 0) {\n void userStore.loadUsers(Array.from(ids));\n }\n };\n\n return {\n key: \"attribution\",\n userStore,\n store,\n prosemirrorPlugins: [\n // Marks arrive in a transaction (suggestion mode, viewing suggestions,\n // version preview), so resolve their authors as the doc changes.\n new Plugin({\n key: ATTRIBUTION_LOAD_PLUGIN_KEY,\n state: {\n init: () => null,\n apply: (tr) => {\n if (tr.docChanged) {\n loadChangedUsers(tr);\n }\n return null;\n },\n },\n }),\n ],\n mount({ dom, root, signal }) {\n // Write each resolved author's color to the editor root as per-user CSS\n // variables (`--user-color-<id>-{light,dark}`) that the mark wrappers read\n // via `var(..., <fallback>)`, so the cascade recolors marks once a color\n // resolves. Color-less users have theirs removed so the fallback applies.\n const syncRootVars = () => {\n for (const [id, user] of userStore.store.state) {\n const { light, dark } = userColorVarNames(id);\n const colors = userMarkColors(user);\n if (colors) {\n dom.style.setProperty(light, colors.light);\n dom.style.setProperty(dark, colors.dark);\n } else {\n dom.style.removeProperty(light);\n dom.style.removeProperty(dark);\n }\n }\n };\n\n // The wrapper currently showing a tooltip, so we don't re-emit on every\n // `mouseover` over the same mark.\n let activeAnchor: HTMLElement | undefined;\n\n // The mark's authors as usernames, falling back to the raw id when not\n // cached (`getUser` is cache-only; ids load on hover, see `onPointerOver`).\n // A user with an empty name only colors its marks (a version diff's\n // synthetic author), so it isn't listed.\n const usersLabelArray = (userIdsJSON: string | undefined): string[] =>\n parseUserIds(userIdsJSON)\n .map((id) => userStore.getUser(id)?.username ?? id)\n .filter((username) => username !== \"\");\n\n // A stable identity string for a mark wrapper, used to group nested marks\n // with the *same* change under one tooltip. Every wrapper is a change;\n // its author may be unknown (e.g. content removed along with a\n // concurrently deleted block). It's an internal grouping key, not the\n // displayed text, so it's built from raw `data-*` and stays free of\n // i18n/username resolution.\n const attributionIdentity = (wrapper: HTMLElement) => {\n const ids = parseUserIds(wrapper.dataset[\"userIds\"]);\n const format = parseFormatKeys(wrapper.dataset[\"format\"]);\n return `${wrapper.tagName}:${wrapper.dataset[\"attributes\"] ?? \"\"}:${format.join(\",\")}:${ids.join(\",\")}`;\n };\n\n // Build the tooltip state from a wrapper's `data-*` attributes. A\n // `preview` is the rendered preview the change was hovered through.\n const buildState = (\n anchor: HTMLElement,\n preview?: Element,\n ): AttributionTooltipState => {\n const markChange: AttributionChange & {\n modificationType: AttributionMarkStyleInfo[\"modificationType\"];\n } =\n anchor.dataset[\"attributes\"] !== undefined\n ? {\n modificationType: \"attrs\",\n attributes: parseFormatKeys(anchor.dataset[\"attributes\"]),\n }\n : anchor.dataset[\"format\"] !== undefined\n ? {\n modificationType: \"format\",\n format: parseFormatKeys(anchor.dataset[\"format\"]),\n }\n : {\n modificationType:\n anchor.tagName === \"INS\" ? \"insert\" : \"delete\",\n };\n const { modificationType } = markChange;\n const change: AttributionChange = preview\n ? { modificationType: \"change\" }\n : markChange;\n const contentType: AttributionTooltipState[\"contentType\"] =\n anchor.dataset[\"inline\"] === \"false\" ? \"block\" : \"inline-content\";\n\n return {\n anchor,\n // The tooltip is portaled outside the editor root, so it can't read\n // the cascaded per-user vars — resolve a concrete color from the store.\n color: colorsForUserIds(\n userStore,\n parseUserIds(anchor.dataset[\"userIds\"]),\n ).dark,\n ...change,\n contentType,\n users: usersLabelArray(anchor.dataset[\"userIds\"]),\n className: resolveAttributionMarkClassName(\n getAttributionMarkClassName?.({ contentType, modificationType }),\n \"tooltip\",\n ),\n ...(preview ? { reference: preview } : {}),\n };\n };\n\n const hideTooltip = () => {\n if (!activeAnchor) {\n return;\n }\n activeAnchor = undefined;\n store.setState(undefined);\n };\n\n const nodeAttribution = (\n target: Element,\n ): { mark: HTMLElement; preview: Element } | undefined => {\n if (!dom.contains(target)) {\n return undefined;\n }\n const view = editor.prosemirrorView;\n const $pos = view.state.doc.resolve(view.posAtDOM(target, 0));\n if ($pos.depth === 0) {\n return undefined;\n }\n const owner = view.nodeDOM($pos.before($pos.depth));\n if (!(owner instanceof Element) || !owner.contains(target)) {\n return undefined;\n }\n const contentDOM = view.domAtPos($pos.start()).node;\n if (contentDOM.contains(target) || target.contains(contentDOM)) {\n // Editable content already shows inline attribution. Unchanged text\n // and the containing block must not inherit a sibling's change.\n return undefined;\n }\n // A separate rendered preview may hide its attributed source. Only\n // hovering that surface represents a change within the whole node,\n // not other controls like a checkbox, whose text is on screen.\n const name = $pos.parent.type.name;\n const hasPreview =\n editor.schema.blockSpecs[name]?.implementation?.meta?.hasPreview ||\n editor.schema.inlineContentSpecs[name]?.implementation?.meta\n ?.hasPreview;\n if (\n !hasPreview &&\n contentDOM instanceof Element &&\n contentDOM.getClientRects().length > 0\n ) {\n return undefined;\n }\n const mark = owner.querySelector<HTMLElement>(\n ATTRIBUTION_MARK_SELECTOR,\n );\n return mark ? { mark, preview: owner } : undefined;\n };\n\n const onPointerOver = (event: Event) => {\n const target = event.target instanceof Element ? event.target : null;\n const hoveredMark =\n target && dom.contains(target)\n ? (target.closest<HTMLElement>(ATTRIBUTION_MARK_SELECTOR) ??\n undefined)\n : undefined;\n const fallback =\n target && !hoveredMark ? nodeAttribution(target) : undefined;\n const innermost = hoveredMark ?? fallback?.mark;\n if (!innermost) {\n // Not over an attributed mark — drop the current tooltip.\n hideTooltip();\n return;\n }\n\n const identity = attributionIdentity(innermost);\n // Anchor on the outermost ancestor with the *same* attribution so one\n // tooltip covers the whole region; a different ancestor breaks the chain.\n let anchor = innermost;\n let el: Element | null = innermost.parentElement;\n while (el) {\n const ancestor = el.closest<HTMLElement>(ATTRIBUTION_MARK_SELECTOR);\n if (!ancestor) {\n break;\n }\n if (attributionIdentity(ancestor) !== identity) {\n break;\n }\n anchor = ancestor;\n el = ancestor.parentElement;\n }\n\n if (\n activeAnchor === anchor &&\n store.state?.reference === fallback?.preview\n ) {\n return;\n }\n\n activeAnchor = anchor;\n store.setState(buildState(anchor, fallback?.preview));\n\n // First hover renders raw ids (cache-only); load the authors and refresh\n // the resolved usernames once loaded, if this mark is still active.\n const ids = parseUserIds(anchor.dataset[\"userIds\"]);\n if (ids.length > 0) {\n void userStore.loadUsers(ids).then(() => {\n if (\n activeAnchor !== anchor ||\n store.state?.reference !== fallback?.preview\n ) {\n return;\n }\n store.setState(buildState(anchor, fallback?.preview));\n });\n }\n };\n\n root.addEventListener(\"mouseover\", onPointerOver, { signal });\n signal.addEventListener(\"abort\", hideTooltip);\n\n // Seed from the cache, then keep the vars in sync as users resolve.\n syncRootVars();\n const unsubscribe = userStore.store.subscribe(syncRootVars);\n signal.addEventListener(\"abort\", unsubscribe);\n },\n\n // The `y-attributed-*` marks aren't in the default schema — register them\n // here so the block specs can allow them (collaboration-only).\n blockNoteExtensions: [\n YAttributionMarksExtension({\n getAttributionMarkClassName: options?.getAttributionMarkClassName,\n }),\n ],\n };\n },\n);\n","import { defaultSelectionBuilder, yCursorPlugin } from \"@y/prosemirror\";\nimport {\n createExtension,\n ExtensionOptions,\n} from \"../../editor/BlockNoteExtension.js\";\nimport { CollaborationOptions } from \"./index.js\";\n\nexport type CollaborationUser = {\n id?: string;\n name: string;\n color: string;\n [key: string]: unknown;\n};\n\n/**\n * Determine whether the foreground color should be white or black based on a provided background color\n * Inspired by: https://stackoverflow.com/a/3943023\n */\nfunction isDarkColor(bgColor: string): boolean {\n const color = bgColor.charAt(0) === \"#\" ? bgColor.substring(1, 7) : bgColor;\n const r = parseInt(color.substring(0, 2), 16); // hexToR\n const g = parseInt(color.substring(2, 4), 16); // hexToG\n const b = parseInt(color.substring(4, 6), 16); // hexToB\n const uicolors = [r / 255, g / 255, b / 255];\n const c = uicolors.map((col) => {\n if (col <= 0.03928) {\n return col / 12.92;\n }\n return Math.pow((col + 0.055) / 1.055, 2.4);\n });\n const L = 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];\n return L <= 0.179;\n}\n\nfunction defaultCursorRender(user: CollaborationUser) {\n const cursorElement = document.createElement(\"span\");\n\n cursorElement.classList.add(\"bn-collaboration-cursor__base\");\n\n const caretElement = document.createElement(\"span\");\n caretElement.setAttribute(\"contentedEditable\", \"false\");\n caretElement.classList.add(\"bn-collaboration-cursor__caret\");\n caretElement.setAttribute(\n \"style\",\n `background-color: ${user.color}; color: ${\n isDarkColor(user.color) ? \"white\" : \"black\"\n }`,\n );\n\n const labelElement = document.createElement(\"span\");\n\n labelElement.classList.add(\"bn-collaboration-cursor__label\");\n labelElement.setAttribute(\n \"style\",\n `background-color: ${user.color}; color: ${\n isDarkColor(user.color) ? \"white\" : \"black\"\n }`,\n );\n labelElement.insertBefore(document.createTextNode(user.name), null);\n\n caretElement.insertBefore(labelElement, null);\n\n cursorElement.insertBefore(document.createTextNode(\"\\u2060\"), null); // Non-breaking space\n cursorElement.insertBefore(caretElement, null);\n cursorElement.insertBefore(document.createTextNode(\"\\u2060\"), null); // Non-breaking space\n\n return cursorElement;\n}\n\nexport const YCursorExtension = createExtension(\n ({ options }: ExtensionOptions<CollaborationOptions>) => {\n const recentlyUpdatedCursors = new Map();\n const awareness =\n options.provider &&\n \"awareness\" in options.provider &&\n typeof options.provider.awareness === \"object\"\n ? options.provider.awareness\n : undefined;\n if (awareness) {\n if (\n \"setLocalStateField\" in awareness &&\n typeof awareness.setLocalStateField === \"function\"\n ) {\n awareness.setLocalStateField(\"user\", options.user);\n }\n if (\"on\" in awareness && typeof awareness.on === \"function\") {\n if (options.showCursorLabels !== \"always\") {\n awareness.on(\n \"change\",\n ({\n updated,\n }: {\n added: Array<number>;\n updated: Array<number>;\n removed: Array<number>;\n }) => {\n for (const clientID of updated) {\n const cursor = recentlyUpdatedCursors.get(clientID);\n\n if (cursor) {\n setTimeout(() => {\n cursor.element.setAttribute(\"data-active\", \"\");\n }, 10);\n\n if (cursor.hideTimeout) {\n clearTimeout(cursor.hideTimeout);\n }\n\n recentlyUpdatedCursors.set(clientID, {\n element: cursor.element,\n hideTimeout: setTimeout(() => {\n cursor.element.removeAttribute(\"data-active\");\n }, 2000),\n });\n }\n }\n },\n );\n }\n }\n }\n\n return {\n key: \"yCursor\",\n prosemirrorPlugins: [\n awareness\n ? yCursorPlugin(awareness, {\n selectionBuilder: defaultSelectionBuilder,\n cursorBuilder(user, clientID) {\n let cursorData = recentlyUpdatedCursors.get(clientID);\n\n if (!cursorData) {\n const cursorElement = (\n options.renderCursor ?? defaultCursorRender\n )(user as CollaborationUser);\n\n if (options.showCursorLabels !== \"always\") {\n cursorElement.addEventListener(\"mouseenter\", () => {\n const cursor = recentlyUpdatedCursors.get(clientID)!;\n cursor.element.setAttribute(\"data-active\", \"\");\n\n if (cursor.hideTimeout) {\n clearTimeout(cursor.hideTimeout);\n recentlyUpdatedCursors.set(clientID, {\n element: cursor.element,\n hideTimeout: undefined,\n });\n }\n });\n\n cursorElement.addEventListener(\"mouseleave\", () => {\n const cursor = recentlyUpdatedCursors.get(clientID)!;\n\n recentlyUpdatedCursors.set(clientID, {\n element: cursor.element,\n hideTimeout: setTimeout(() => {\n cursor.element.removeAttribute(\"data-active\");\n }, 2000),\n });\n });\n }\n\n cursorData = {\n element: cursorElement,\n hideTimeout: undefined,\n };\n\n recentlyUpdatedCursors.set(clientID, cursorData);\n }\n\n return cursorData.element;\n },\n })\n : undefined,\n ].filter((a) => a !== undefined),\n dependsOn: [\"ySync\"],\n clearCursor() {\n awareness?.setLocalStateField(\"cursor\", null);\n },\n updateUser(user: CollaborationUser) {\n awareness?.setLocalStateField(\"user\", user);\n },\n getUser(): CollaborationUser | undefined {\n const state = awareness?.getLocalState();\n if (!state) {\n return undefined;\n }\n return state[\"user\"];\n },\n } as const;\n },\n);\n","import { $prosemirrorDelta } from \"@y/prosemirror\";\nimport * as delta from \"lib0/delta\";\nimport * as schema from \"lib0/schema\";\n\n/**\n * Canonical name of a content delta's first block child (the child carried by an\n * insert op), or `null`. For a BlockNote `blockContainer` (content\n * `blockContent blockGroup?`) this is its block-content type (paragraph,\n * heading, image, ...).\n */\nconst firstChild = (\n d: schema.Unwrap<typeof $prosemirrorDelta>,\n): schema.Unwrap<typeof $prosemirrorDelta> | null => {\n for (const op of (d as any).children) {\n if (delta.$insertOp.check(op)) {\n for (const it of op.insert) {\n if (delta.$deltaAny.check(it)) {\n return it;\n }\n }\n }\n }\n return null;\n};\n\nfunction getTableDimensions(\n d: schema.Unwrap<typeof $prosemirrorDelta>,\n): { rows: number; cols: number } | null {\n if (d.name !== \"table\") {\n return null;\n }\n\n // Collect all rows with their cells' colspan/rowspan values.\n const rows: Array<Array<{ colspan: number; rowspan: number }>> = [];\n for (const op of (d as any).children) {\n if (delta.$insertOp.check(op)) {\n for (const tr of op.insert as Array<\n schema.Unwrap<typeof $prosemirrorDelta>\n >) {\n if (tr.name !== \"tableRow\") {\n return null;\n }\n const cells: Array<{ colspan: number; rowspan: number }> = [];\n for (const trOp of (tr as any).children) {\n if (delta.$insertOp.check(trOp)) {\n for (const td of trOp.insert as Array<\n schema.Unwrap<typeof $prosemirrorDelta>\n >) {\n if (td.name !== \"tableCell\" && td.name !== \"tableHeader\") {\n return null;\n }\n cells.push({\n colspan: Number(td.attrs.colspan) || 1,\n rowspan: Number(td.attrs.rowspan) || 1,\n });\n }\n }\n }\n rows.push(cells);\n }\n }\n }\n\n if (rows.length === 0) {\n return null;\n }\n\n // Build an occupancy grid to determine the true column count.\n // Each entry in `grid[r]` tracks which columns are already occupied\n // (by a cell from a previous row with rowspan > 1).\n const grid: boolean[][] = [];\n for (let r = 0; r < rows.length; r++) {\n if (!grid[r]) {\n grid[r] = [];\n }\n let col = 0;\n for (const cell of rows[r]) {\n // Skip columns already occupied by a rowspan from above.\n while (grid[r][col]) {\n col++;\n }\n // Mark all slots this cell occupies.\n for (let dr = 0; dr < cell.rowspan; dr++) {\n if (!grid[r + dr]) {\n grid[r + dr] = [];\n }\n for (let dc = 0; dc < cell.colspan; dc++) {\n grid[r + dr][col + dc] = true;\n }\n }\n col += cell.colspan;\n }\n }\n\n const numCols = Math.max(...grid.map((row) => row.length));\n return { rows: rows.length, cols: numCols };\n}\n\n/**\n * BlockNote's node-pairing policy for y-prosemirror's `matchNodes` option\n * (forwarded to `lib0/delta.diff`). This is the schema-specific bit that lives\n * in userland - the binding itself stays schema-agnostic.\n *\n * A `blockContainer` holds exactly one block content (`blockContent\n * blockGroup?`). Diffing a *type change* of that content as an in-place child\n * delete+insert would, under a suggestion, tombstone the old content next to the\n * new one => two block-contents in one container => schema-invalid. So we\n * declare a container's identity to be its first block-content child's type:\n * when that changes, the two containers are reported as *different*, the PM->Y\n * diff replaces the whole container, and the deleted + inserted containers sit\n * as siblings in the blockGroup (`blockGroupChild+` allows that). Each carries\n * the `y-attributed-*` node mark - which `blockContainer` already whitelists -\n * so no schema change and no storage transform are needed. A plain text edit\n * keeps the same first-child type => same identity => the diff descends and\n * merges as usual.\n *\n * A change in nesting is *not* an identity change: a container that gains or\n * loses its child `blockGroup` is diffed in place. The persistent block group\n * transformer (see persistentBlockGroups.ts) keeps every `blockGroup` in Y and\n * routes the view's group insert into the container's existing group, so the\n * in-place diff can never leave two groups in one container. Replacing the\n * container instead would recreate the race the transformer removes (two users\n * nesting a first child concurrently would each insert their own container).\n *\n * @param a removed (old) node\n * @param b inserted (new) node\n * @returns whether `a` and `b` are the same node (diff in place) vs different (replace)\n */\nconst replaceReshapedTables = false;\n\nexport const blockMatchNodes = (\n a: schema.Unwrap<typeof $prosemirrorDelta>,\n b: schema.Unwrap<typeof $prosemirrorDelta>,\n): boolean => {\n if (a.name !== b.name) {\n return false;\n }\n\n if (a.name !== \"blockContainer\") {\n return true;\n }\n\n const childA = firstChild(a);\n const childB = firstChild(b);\n\n if (childA?.name !== childB?.name) {\n return false;\n }\n\n // Disabled: replacing a table that one edit reshapes both ways silently\n // dropped concurrent edits to it, and version diffs compare all the changes\n // between two versions, so concurrent one-way reshapes (a row and a column)\n // replaced the whole table there. Reshapes merge in place, as one-way ones\n // always did.\n if (\n replaceReshapedTables &&\n childA?.name === \"table\" &&\n childB?.name === \"table\"\n ) {\n const dimA = getTableDimensions(childA);\n const dimB = getTableDimensions(childB);\n if (\n dimA !== null &&\n dimB !== null &&\n dimA.rows !== dimB.rows &&\n dimA.cols !== dimB.cols\n ) {\n return false;\n }\n }\n\n return true;\n};\n","import * as delta from \"lib0/delta\";\nimport * as dt from \"lib0/delta/transformer\";\nimport type * as s from \"lib0/schema\";\n\n/**\n * # Persistent block groups\n *\n * A `@y/prosemirror` transformer (the `transformers` option of `syncPlugin`)\n * that keeps BlockNote's nested `blockGroup` nodes alive in the Yjs document\n * and hides the empty ones from ProseMirror.\n *\n * ## The problem\n *\n * BlockNote nests child blocks as `blockContainer > [blockContent, blockGroup?]`\n * and its ProseMirror schema forbids an empty `blockGroup`\n * (`content: \"blockGroupChild+\"`). So the editor creates the group together\n * with the first nested block and removes it with the last one. Under\n * concurrency that is a conflict generator: two users who nest a first child\n * under the same block at the same time each insert their own `blockGroup`,\n * and after the merge the container holds two groups, which the schema\n * rejects. BlockNote worked around it by replacing the whole container\n * whenever a group appeared or disappeared (the nesting check that used to be\n * in `blockMatchNodes`), which turns the same race into two copies of the\n * parent block and rewrites the parent on every first nesting and last\n * un-nesting.\n *\n * ## The model\n *\n * What Yjs stores is decoupled from what ProseMirror shows:\n *\n * - **Yjs (side A)** keeps every `blockGroup` once it exists. Emptying one\n * leaves it in place, and (with `implicitGroups`, the default) a container\n * the editor creates gets an empty group right away. Two users nesting a\n * first child concurrently therefore write into the *same* group item, and\n * Yjs merges their children like any other concurrent list insert.\n * - **ProseMirror (side B)** sees one `blockGroup` per container, present only\n * while it has children.\n *\n * Yjs ProseMirror\n * blockContainer[ content, group[] ] ⇄ blockContainer[ content ]\n * blockContainer[ content, group[a] ] ⇄ blockContainer[ content, group[a] ]\n * blockContainer[ content, g1[a], g2[b] ] ⇄ blockContainer[ content, group[a, b] ]\n * blockContainer[ content ] ⇄ blockContainer[ content ] (legacy)\n *\n * The third row is what a document written before this transformer (no\n * groups until the first nesting) produces when two users nest a first child\n * concurrently: the view merges every group of a container into one, so the\n * race degrades to an ordering question instead of invalid content. Edits\n * inside the merged group route back to the Yjs group that holds that\n * position. A legacy container never gets a group implicitly (that would be a\n * concurrent write by every client that opens the document); its first nesting\n * creates the group, as before.\n *\n * ## Rules, per `blockContainer`\n *\n * Yjs → view (`applyA`):\n * - every `blockGroup` child collapses into one view group placed after all\n * other children; it exists iff the groups hold at least one child in total\n * - a change that makes the total go 0 → n inserts the view group, n → 0\n * deletes it, n → m modifies it with the inner change re-based onto merged\n * coordinates (a group's children start at the sum of the lengths of the\n * groups before it)\n * - the group wrapper's own attributes, formats and attribution have no view\n * counterpart and are dropped; a group inserted by a suggestion renders its\n * *children* as inserted, which is what the user sees anyway\n *\n * view → Yjs (`applyB`):\n * - an edit at a merged offset routes into the group covering it; at a\n * boundary between two groups the earlier group wins\n * - deleting the view group empties every Yjs group and keeps them all\n * - inserting a view group (only possible while no view group exists) routes\n * its children into the first Yjs group, or, when the container has no\n * group at all (a legacy container), inserts the group as the editor built\n * it\n * - a container the view inserts without a group gets an empty group appended\n * (`implicitGroups`)\n *\n * Cursor positions (root marks) map through the same layout, in both\n * directions.\n *\n * ## Shape of the implementation\n *\n * {@link persistentBlockGroups} composes lib0's `children` template\n * recursively over the node types that can hold containers (`blockGroup`,\n * `column`, `columnList`) and pipes the stateful per-container stage\n * ({@link PersistentGroupTransformer}) after the recursion, so that stage sees\n * its container's children in Yjs layout on the way in and in view layout on\n * the way back. Every other node type (block content, inline content) opts\n * out of the recursion and costs nothing.\n *\n * The per-container state is the container's Yjs child layout: a list of\n * {@link Seg}s, one per child, telling groups (with their child count) apart\n * from everything else. It is kept current from the changes that flow through,\n * so no stage ever re-reads a document; a change costs O(size of the change)\n * plus O(children of the containers on its path), and a container has two or\n * three children.\n *\n * ## Assumptions\n *\n * - `blockContainer` children are a content node followed by zero or more\n * `blockGroup`s (BlockNote never produces anything else). The code tolerates\n * other layouts, but the view then shows non-group children in Yjs order\n * followed by the merged group, which may differ from the Yjs order.\n * - the view inserts at most one `blockGroup` per container (its schema\n * guarantees that).\n */\n\n/**\n * Options of {@link persistentBlockGroups}.\n */\nexport type PersistentBlockGroupsOptions = {\n /** The nested list node that is kept and hidden. Default `\"blockGroup\"`. */\n groupName?: string;\n /** The block node whose children the group lives in. Default `\"blockContainer\"`. */\n containerName?: string;\n /**\n * The node types (besides the container) that can hold containers, so the\n * recursion descends into them. Default `[\"blockGroup\", \"column\", \"columnList\"]`.\n */\n nestingNodes?: readonly string[];\n /**\n * Whether a container the view creates gets an empty group right away\n * (default `true`). With `false`, groups are only kept once the first\n * nesting creates them; concurrent first nestings then leave two groups in\n * Yjs, which the view merges.\n */\n implicitGroups?: boolean;\n};\n\nconst defaults = {\n groupName: \"blockGroup\",\n containerName: \"blockContainer\",\n nestingNodes: [\"blockGroup\", \"column\", \"columnList\"],\n implicitGroups: true,\n} as const satisfies Required<PersistentBlockGroupsOptions>;\n\n// lib0's delta builders are untyped at this level of genericity: the stage\n// works on arbitrary node deltas (`Delta<any>`), as lib0's own transformers do.\ntype AnyDelta = delta.DeltaAny;\ntype AnyBuilder = delta.DeltaBuilderAny;\ntype Format = delta.Formats | null | undefined;\ntype Attribution = delta.Attribution | null | undefined;\n\n/**\n * One child of a container in Yjs layout: a group with its child count, or\n * anything else.\n */\ntype Seg =\n | { readonly group: false }\n | { readonly group: true; readonly len: number };\n\n/** The shared layout entry of every non-group child. */\nconst PASS: Seg = { group: false };\n\nfunction groupSeg(len: number): Seg {\n return { group: true, len };\n}\n\nfunction isGroup(el: unknown, groupName: string): el is AnyDelta {\n return delta.$deltaAny.check(el) && el.name === groupName;\n}\n\n/**\n * Net change of a node's child count from a change delta: positions inserted\n * minus positions deleted (retain and modify keep the count).\n */\nfunction netLen(d: AnyDelta): number {\n let n = 0;\n for (const op of d.children) {\n if (delta.$insertOp.check(op) || delta.$textOp.check(op)) {\n n += op.insert.length;\n } else if (delta.$deleteOp.check(op)) {\n n -= op.delete;\n }\n }\n return n;\n}\n\n/** The total child count of the groups in a layout. */\nfunction totalOf(segs: readonly Seg[]): number {\n let n = 0;\n for (const seg of segs) {\n if (seg.group) {\n n += seg.len;\n }\n }\n return n;\n}\n\n/** The layout of `n` non-group positions (text characters or opaque nodes). */\nfunction passSegs(n: number): Seg[] {\n const segs: Seg[] = [];\n for (let i = 0; i < n; i++) {\n segs.push(PASS);\n }\n return segs;\n}\n\ntype Insert = {\n content: string | unknown[];\n format: Format;\n attribution: Attribution;\n /** the layout of the inserted content */\n segs: Seg[];\n};\n\ntype SlotOp =\n | { kind: \"retain\"; format: Format; attribution: Attribution }\n | { kind: \"delete\" }\n | {\n kind: \"modify\";\n value: AnyDelta;\n format: Format;\n attribution: Attribution;\n };\n\n/**\n * Edits to one node's child list, keyed by *pre-change* child index so they\n * can be collected in any order (the view's order of a container's children\n * is not the Yjs order) and emitted in index order. Inserts are keyed by the\n * gap they land in (`gap === len` appends). The layout bookkeeping (`segs` of\n * inserted content, deleted indexes, length adjustments of groups) lets\n * {@link ChildEdits.rebuildSegs} derive the post-change layout.\n */\nclass ChildEdits {\n private readonly inserts = new Map<number, Insert[]>();\n private readonly ops = new Map<number, SlotOp>();\n private readonly lenAdjust = new Map<number, number>();\n\n insertAt(\n gap: number,\n content: string | unknown[],\n format: Format,\n attribution: Attribution,\n segs: Seg[],\n ): void {\n let arr = this.inserts.get(gap);\n if (arr === undefined) {\n arr = [];\n this.inserts.set(gap, arr);\n }\n arr.push({ content, format, attribution, segs });\n }\n\n /** A formatted retain (a bare retain is implicit). */\n retainAt(idx: number, format: Format, attribution: Attribution): void {\n this.ops.set(idx, { kind: \"retain\", format, attribution });\n }\n\n deleteAt(idx: number): void {\n this.ops.set(idx, { kind: \"delete\" });\n }\n\n modifyAt(\n idx: number,\n value: AnyDelta,\n format: Format,\n attribution: Attribution,\n ): void {\n this.ops.set(idx, { kind: \"modify\", value, format, attribution });\n }\n\n /** Record that the group at `idx` changed its child count by `d`. */\n adjustLen(idx: number, d: number): void {\n this.lenAdjust.set(idx, (this.lenAdjust.get(idx) ?? 0) + d);\n }\n\n /**\n * Emit the collected edits onto `out`, in child order. Untouched positions\n * become plain retains (the builder coalesces them, and `done()` trims a\n * trailing run).\n *\n * @param out a delta builder\n * @param len the pre-change child count\n */\n emit(out: AnyBuilder, len: number): void {\n for (let i = 0; i <= len; i++) {\n const ins = this.inserts.get(i);\n if (ins !== undefined) {\n for (const e of ins) {\n out.insert(e.content, e.format, e.attribution);\n }\n }\n if (i === len) {\n break;\n }\n const op = this.ops.get(i);\n if (op === undefined) {\n out.retain(1);\n } else {\n switch (op.kind) {\n case \"retain\":\n out.retain(1, op.format, op.attribution);\n break;\n case \"delete\":\n out.delete(1);\n break;\n case \"modify\":\n out.modify(op.value, op.format, op.attribution);\n break;\n }\n }\n }\n }\n\n /** The post-change layout, from the pre-change one. */\n rebuildSegs(segs: readonly Seg[]): Seg[] {\n const out: Seg[] = [];\n for (let i = 0; i <= segs.length; i++) {\n const ins = this.inserts.get(i);\n if (ins !== undefined) {\n for (const e of ins) {\n out.push(...e.segs);\n }\n }\n if (i === segs.length) {\n break;\n }\n if (this.ops.get(i)?.kind === \"delete\") {\n continue;\n }\n const seg = segs[i];\n const adj = this.lenAdjust.get(i);\n out.push(adj === undefined || !seg.group ? seg : groupSeg(seg.len + adj));\n }\n return out;\n }\n}\n\n/**\n * The view gap of Yjs gap `k` in layout `segs`: the non-group children before\n * it, plus the view group when the gap sits at the very end behind a visible\n * group.\n */\nfunction viewGap(segs: readonly Seg[], k: number, total: number): number {\n let n = 0;\n const end = Math.min(k, segs.length);\n for (let i = 0; i < end; i++) {\n if (!segs[i].group) {\n n++;\n }\n }\n return k >= segs.length && total > 0 ? n + 1 : n;\n}\n\n/**\n * The Yjs gap of view gap `k` in layout `segs`: before the k-th non-group\n * child, or the end.\n */\nfunction yjsGapPost(segs: readonly Seg[], k: number): number {\n let n = 0;\n for (let i = 0; i < segs.length; i++) {\n if (!segs[i].group) {\n if (n === k) {\n return i;\n }\n n++;\n }\n }\n return segs.length;\n}\n\nfunction mapNumericKey(\n map: (k: number) => number | null,\n): (key: number | string) => number | string | null {\n return (key) => (typeof key === \"number\" ? map(key) : key);\n}\n\n/** The change routed into one Yjs group (view → Yjs). */\ntype GroupChange = {\n b: AnyBuilder;\n /** pre-change positions of the group consumed so far */\n emitted: number;\n /** post-change positions produced so far (anchors lifted marks) */\n out: number;\n /** net child count change */\n net: number;\n touched: boolean;\n};\n\n/**\n * The stateful per-container stage. Side A is the container's children in\n * Yjs layout, side B in view layout (see the module doc for the rules).\n */\nexport class PersistentGroupTransformer extends dt.Transformer<any, any> {\n /**\n * The container's Yjs child layout, kept current from the changes that\n * flow through (both directions).\n */\n segs: Seg[] = [];\n /**\n * Whether no change has been seen yet. The first change a stage receives\n * is the whole container node (lib0's `children` feeds a freshly inserted\n * child through a fresh stage); when that node comes from the view, the\n * container is new and gets its implicit group.\n */\n fresh = true;\n\n constructor(\n $in: s.Schema<AnyDelta>,\n $out: s.Schema<AnyDelta>,\n readonly groupName: string,\n readonly implicitGroups: boolean,\n ) {\n super($in, $out);\n }\n\n /** Yjs layout change → view layout change. */\n override applyA(da: AnyBuilder): dt.TransformResultAny {\n this.fresh = false;\n const segs = this.segs;\n const groupName = this.groupName;\n const totalPre = totalOf(segs);\n let nonPre = 0;\n for (const seg of segs) {\n if (!seg.group) {\n nonPre++;\n }\n }\n const newSegs: Seg[] = [];\n // the view-side edits of the non-group children, keyed by their view index\n const edits = new ChildEdits();\n // the merged change of the view group, in merged pre-change coordinates\n const inner: AnyBuilder = delta.create();\n let innerEmitted = 0; // merged pre-change positions `inner` consumed\n let innerOut = 0; // merged post-change positions `inner` produced (anchors lifted marks)\n let innerTouched = false;\n let ai = 0; // pre-change Yjs cursor\n let bi = 0; // view index of the cursor (non-group children before it)\n let mergedBefore = 0; // merged offset of the cursor (children of the groups before it)\n const alignInner = () => {\n if (mergedBefore > innerEmitted) {\n const n = mergedBefore - innerEmitted;\n inner.retain(n);\n innerEmitted = mergedBefore;\n innerOut += n;\n }\n };\n const step = () => {\n const seg = segs[ai++];\n if (seg.group) {\n mergedBefore += seg.len;\n } else {\n bi++;\n }\n };\n for (const op of da.children) {\n if (delta.$retainOp.check(op)) {\n const fmt = op.format;\n const attr = op.attribution;\n for (let n = op.retain; n > 0 && ai < segs.length; n--) {\n const seg = segs[ai];\n // a format or attribution on a group wrapper has no view counterpart\n if (!seg.group && (fmt !== undefined || attr !== undefined)) {\n edits.retainAt(bi, fmt, attr);\n }\n newSegs.push(seg);\n step();\n }\n } else if (delta.$textOp.check(op)) {\n edits.insertAt(bi, op.insert, op.format, op.attribution, []);\n newSegs.push(...passSegs(op.insert.length));\n } else if (delta.$insertOp.check(op)) {\n for (const el of op.insert) {\n if (isGroup(el, groupName)) {\n alignInner();\n const base = innerOut;\n inner.append(el);\n innerOut += el.childCnt;\n const hasMarks = el.marks !== null || el.deleteMarks !== null;\n if (hasMarks) {\n delta.mergeRootMarks(\n inner,\n el,\n mapNumericKey((k) => base + k),\n );\n }\n innerTouched ||= el.childCnt > 0 || hasMarks;\n newSegs.push(groupSeg(el.childCnt));\n } else {\n edits.insertAt(bi, [el], op.format, op.attribution, []);\n newSegs.push(PASS);\n }\n }\n } else if (delta.$deleteOp.check(op)) {\n for (let n = op.delete; n > 0 && ai < segs.length; n--) {\n const seg = segs[ai];\n if (seg.group) {\n if (seg.len > 0) {\n alignInner();\n inner.delete(seg.len);\n innerEmitted += seg.len;\n innerTouched = true;\n }\n } else {\n edits.deleteAt(bi);\n }\n step();\n }\n } else {\n // modify\n if (ai >= segs.length) {\n continue;\n }\n const seg = segs[ai];\n const v: AnyDelta = op.value;\n if (seg.group) {\n // the group's inner change, re-based onto merged coordinates; its\n // attribute ops (the wrapper's) are dropped\n alignInner();\n const base = innerOut;\n for (const iop of v.children) {\n if (delta.$retainOp.check(iop)) {\n inner.retain(iop.retain, iop.format, iop.attribution);\n innerEmitted += iop.retain;\n innerOut += iop.retain;\n innerTouched ||=\n iop.format !== undefined || iop.attribution !== undefined;\n } else if (delta.$deleteOp.check(iop)) {\n inner.delete(iop.delete);\n innerEmitted += iop.delete;\n innerTouched = true;\n } else if (delta.$modifyOp.check(iop)) {\n inner.modify(delta.clone(iop.value), iop.format, iop.attribution);\n innerEmitted += 1;\n innerOut += 1;\n innerTouched = true;\n } else if (delta.$insertOp.check(iop) || delta.$textOp.check(iop)) {\n inner.insert(iop.insert, iop.format, iop.attribution);\n innerOut += iop.insert.length;\n innerTouched = true;\n }\n }\n if (v.marks !== null || v.deleteMarks !== null) {\n delta.mergeRootMarks(\n inner,\n v,\n mapNumericKey((k) => base + k),\n );\n innerTouched = true;\n }\n newSegs.push(groupSeg(seg.len + netLen(v)));\n } else {\n edits.modifyAt(bi, delta.clone(v), op.format, op.attribution);\n newSegs.push(seg);\n }\n step();\n }\n }\n while (ai < segs.length) {\n newSegs.push(segs[ai++]);\n }\n const totalPost = totalOf(newSegs);\n // name, attrs and root marks (re-keyed below) of the container\n const out: AnyBuilder = delta.cloneShallow(da);\n edits.emit(out, nonPre); // consumes every non-group view position\n if (totalPre === 0) {\n if (totalPost > 0) {\n // the view group appears. There was no content, so `inner` holds only\n // inserts (and marks): materialize the group node from it.\n const g: AnyBuilder = delta.create(groupName);\n for (const iop of inner.children) {\n if (delta.$insertOp.check(iop) || delta.$textOp.check(iop)) {\n g.insert(iop.insert, iop.format, iop.attribution);\n }\n }\n delta.mergeRootMarks(g, inner);\n out.insert([g.done(false)]);\n }\n } else if (totalPost === 0) {\n out.delete(1);\n } else if (innerTouched) {\n out.modify(inner.done(false));\n }\n delta.remapRootMarks(\n out,\n mapNumericKey((k) => viewGap(newSegs, k, totalPost)),\n );\n this.segs = newSegs;\n out.done(false);\n return dt.createTransformResult(null, out);\n }\n\n /** View layout change → Yjs layout change. */\n override applyB(db: AnyBuilder): dt.TransformResultAny {\n const fresh = this.fresh;\n this.fresh = false;\n const segs = this.segs;\n const groupName = this.groupName;\n /** the Yjs index of each non-group child, in view order */\n const nonIdx: number[] = [];\n /** the groups in Yjs order with their merged start */\n const groups: Array<{ ai: number; len: number; start: number }> = [];\n {\n let start = 0;\n segs.forEach((seg, i) => {\n if (seg.group) {\n groups.push({ ai: i, len: seg.len, start });\n start += seg.len;\n } else {\n nonIdx.push(i);\n }\n });\n }\n const nonPre = nonIdx.length;\n const totalPre = totalOf(segs);\n const hasView = totalPre > 0; // whether the view group exists (at view index `nonPre`)\n // the Yjs-side edits, keyed by Yjs index\n const edits = new ChildEdits();\n // the change routed into each touched group (by index into `groups`)\n const gcs = new Map<number, GroupChange>();\n const gc = (gi: number): GroupChange => {\n let c = gcs.get(gi);\n if (c === undefined) {\n c = { b: delta.create(), emitted: 0, out: 0, net: 0, touched: false };\n gcs.set(gi, c);\n }\n return c;\n };\n /** `target` is an offset within the group */\n const alignG = (c: GroupChange, target: number) => {\n if (target > c.emitted) {\n const n = target - c.emitted;\n c.b.retain(n);\n c.emitted = target;\n c.out += n;\n }\n };\n /**\n * The Yjs gap an insert at view gap `bi` lands in: before the same\n * non-group child, or at the end for a position at or past the view group.\n */\n const yjsGap = (bi: number) => (bi < nonPre ? nonIdx[bi] : segs.length);\n let createdGroup = false;\n /**\n * Route the children of a view-inserted group node at merged offset `off`\n * into the covering Yjs group (the earliest one at a boundary), or, with\n * no group at all, insert the node as the view built it.\n */\n const insertGroup = (\n el: AnyDelta,\n off: number,\n format: Format,\n attribution: Attribution,\n ) => {\n const gi = groups.findIndex((g) => off <= g.start + g.len);\n if (gi === -1) {\n edits.insertAt(segs.length, [el], format, attribution, [\n groupSeg(el.childCnt),\n ]);\n createdGroup = true;\n return;\n }\n // the wrapper's own attrs, format and attribution are not routed\n const c = gc(gi);\n alignG(c, off - groups[gi].start);\n const base = c.out;\n c.b.append(el);\n c.out += el.childCnt;\n c.net += el.childCnt;\n c.touched = true;\n if (el.marks !== null || el.deleteMarks !== null) {\n delta.mergeRootMarks(\n c.b,\n el,\n mapNumericKey((k) => base + k),\n );\n }\n };\n /**\n * Split a view-side change of the merged group across the Yjs groups.\n *\n * @param v the inner change, in merged pre-change coordinates\n */\n const modifyGroup = (v: AnyDelta) => {\n let gi = 0; // cursor: group index ...\n let go = 0; // ... and offset within it\n // positions are consumed from the next group holding any\n const skipFull = () => {\n while (gi < groups.length && go >= groups[gi].len) {\n gi++;\n go = 0;\n }\n };\n for (const iop of v.children) {\n if (delta.$retainOp.check(iop)) {\n const fmt = iop.format;\n const attr = iop.attribution;\n let rem = iop.retain;\n while (rem > 0) {\n skipFull();\n if (gi >= groups.length) {\n break;\n }\n const k = Math.min(groups[gi].len - go, rem);\n if (fmt !== undefined || attr !== undefined) {\n const c = gc(gi);\n alignG(c, go);\n c.b.retain(k, fmt, attr);\n c.emitted += k;\n c.out += k;\n c.touched = true;\n }\n go += k;\n rem -= k;\n }\n } else if (delta.$deleteOp.check(iop)) {\n let rem = iop.delete;\n while (rem > 0) {\n skipFull();\n if (gi >= groups.length) {\n break;\n }\n const k = Math.min(groups[gi].len - go, rem);\n const c = gc(gi);\n alignG(c, go);\n c.b.delete(k);\n c.emitted += k;\n c.net -= k;\n c.touched = true;\n go += k;\n rem -= k;\n }\n } else if (delta.$modifyOp.check(iop)) {\n skipFull();\n if (gi >= groups.length) {\n continue;\n }\n const c = gc(gi);\n alignG(c, go);\n c.b.modify(delta.clone(iop.value), iop.format, iop.attribution);\n c.emitted += 1;\n c.out += 1;\n c.touched = true;\n go += 1;\n } else if (delta.$insertOp.check(iop) || delta.$textOp.check(iop)) {\n // the group the cursor sits in (the earlier one at a boundary)\n if (gi >= groups.length) {\n gi = groups.length - 1;\n go = groups[gi].len;\n }\n const c = gc(gi);\n alignG(c, go);\n c.b.insert(iop.insert, iop.format, iop.attribution);\n c.out += iop.insert.length;\n c.net += iop.insert.length;\n c.touched = true;\n }\n }\n // root marks (merged post-change coordinates) go to the covering group\n if (v.marks !== null) {\n let start = 0;\n const ranges = groups.map((g, i) => {\n const r = { start, len: g.len + (gcs.get(i)?.net ?? 0) };\n start += r.len;\n return r;\n });\n for (const m of v.marks) {\n if (typeof m.key !== \"number\") {\n continue; // an attribute mark on the merged wrapper has no home\n }\n const key = m.key;\n let gi = ranges.findIndex((r) => key <= r.start + r.len);\n if (gi === -1) {\n gi = groups.length - 1;\n }\n const c = gc(gi);\n delta.addRootMark(c.b, m.copy(key - ranges[gi].start));\n c.touched = true;\n }\n }\n if (v.deleteMarks !== null && groups.length > 0) {\n const c = gc(0);\n for (const id of v.deleteMarks) {\n delta.deleteRootMark(c.b, id);\n }\n c.touched = true;\n }\n };\n let bi = 0; // pre-change view cursor\n for (const op of db.children) {\n if (delta.$retainOp.check(op)) {\n const fmt = op.format;\n const attr = op.attribution;\n for (let n = op.retain; n > 0; n--, bi++) {\n if (bi < nonPre) {\n if (fmt !== undefined || attr !== undefined) {\n edits.retainAt(nonIdx[bi], fmt, attr);\n }\n } else if (!(bi === nonPre && hasView)) {\n break; // past the layout\n }\n // a format on the merged group has no single Yjs node to land on\n }\n } else if (delta.$textOp.check(op)) {\n edits.insertAt(\n yjsGap(bi),\n op.insert,\n op.format,\n op.attribution,\n passSegs(op.insert.length),\n );\n } else if (delta.$insertOp.check(op)) {\n for (const el of op.insert) {\n if (isGroup(el, groupName)) {\n insertGroup(\n el,\n hasView && bi > nonPre ? totalPre : 0,\n op.format,\n op.attribution,\n );\n } else {\n edits.insertAt(yjsGap(bi), [el], op.format, op.attribution, [PASS]);\n }\n }\n } else if (delta.$deleteOp.check(op)) {\n for (let n = op.delete; n > 0; n--, bi++) {\n if (bi < nonPre) {\n edits.deleteAt(nonIdx[bi]);\n } else if (bi === nonPre && hasView) {\n // the view removed its group: empty every Yjs group, keep them all\n groups.forEach((g, gi) => {\n if (g.len > 0) {\n const c = gc(gi);\n alignG(c, 0);\n c.b.delete(g.len);\n c.emitted = g.len;\n c.net -= g.len;\n c.touched = true;\n }\n });\n } else {\n break;\n }\n }\n } else {\n // modify\n if (bi < nonPre) {\n edits.modifyAt(\n nonIdx[bi],\n delta.clone(op.value),\n op.format,\n op.attribution,\n );\n } else if (bi === nonPre && hasView) {\n modifyGroup(op.value); // the op's own format / attribution (the wrapper's) is dropped\n }\n bi++;\n }\n }\n for (const [gi, c] of gcs) {\n if (c.touched) {\n edits.modifyAt(groups[gi].ai, c.b.done(false), undefined, undefined);\n }\n if (c.net !== 0) {\n edits.adjustLen(groups[gi].ai, c.net);\n }\n }\n if (this.implicitGroups && fresh && groups.length === 0 && !createdGroup) {\n // implicit creation: a container the view just built gets its group\n edits.insertAt(\n segs.length,\n [delta.create(groupName).done(false)],\n undefined,\n undefined,\n [groupSeg(0)],\n );\n }\n const out: AnyBuilder = delta.cloneShallow(db);\n edits.emit(out, segs.length);\n const newSegs = edits.rebuildSegs(segs);\n delta.remapRootMarks(\n out,\n mapNumericKey((k) => yjsGapPost(newSegs, k)),\n );\n this.segs = newSegs;\n out.done(false);\n return dt.createTransformResult(out, null);\n }\n}\n\n/** Template of the per-container stage. */\nexport class PersistentGroup extends dt.Template<any, any> {\n constructor(\n $d: s.Schema<AnyDelta>,\n readonly groupName: string,\n readonly implicitGroups: boolean,\n ) {\n super($d, delta.$deltaAny);\n }\n\n override get name(): string {\n return `blocknote:persistentGroup:${this.groupName}`;\n }\n\n override init(): dt.Transformer<any, any> {\n return new PersistentGroupTransformer(\n this.$in,\n this.$out,\n this.groupName,\n this.implicitGroups,\n );\n }\n}\n\n/**\n * The transformer: hide empty `blockGroup`s from the view, keep them in Yjs,\n * create them with every new container, and merge concurrently created ones\n * (module doc above). Slot it into the sync plugin:\n *\n * ```ts\n * syncPlugin({ transformers: [persistentBlockGroups], customCompare: blockMatchNodes })\n * ```\n *\n * and into the standalone conversions with\n * `defaultTransformer({ mapAttributionToMark, transformers: [persistentBlockGroups] })`.\n *\n * The returned template is the recursion over the document (lib0's\n * `children`): containers get the per-container stage, the `nestingNodes`\n * descend, every other node opts out.\n */\nexport function persistentBlockGroups<IN extends delta.DeltaConf>(\n $d: s.Schema<delta.Delta<IN>>,\n options: PersistentBlockGroupsOptions = {},\n): dt.Template<IN, any> {\n const groupName = options.groupName ?? defaults.groupName;\n const containerName = options.containerName ?? defaults.containerName;\n const implicitGroups = options.implicitGroups ?? defaults.implicitGroups;\n const nesting = new Set<string>(\n options.nestingNodes ?? defaults.nestingNodes,\n );\n function descend($c: s.Schema<AnyDelta>): dt.Template<any, any> {\n return dt.children($c, (child, $cc) =>\n child.name === containerName\n ? container($cc)\n : child.name !== null && nesting.has(child.name)\n ? descend($cc)\n : null,\n );\n }\n /**\n * Yjs → view order: descend into the container's groups first (Yjs layout),\n * then map the layout. The reverse direction runs the stages right to left.\n */\n function container($c: s.Schema<AnyDelta>): dt.Template<any, any> {\n return dt.pipe(\n $c,\n ($c1) => descend($c1),\n ($c2) => new PersistentGroup($c2, groupName, implicitGroups),\n );\n }\n return descend($d);\n}\n","import {\n configureYProsemirror,\n syncPlugin,\n ySyncPluginKey,\n} from \"@y/prosemirror\";\nimport type { Node } from \"prosemirror-model\";\nimport {\n type ExtensionOptions,\n createExtension,\n} from \"../../editor/BlockNoteExtension.js\";\nimport { blockMatchNodes } from \"./blockMatchNodes.js\";\nimport { persistentBlockGroups } from \"./persistentBlockGroups.js\";\nimport { docToBlocks } from \"../../api/nodeConversions/nodeToBlock.js\";\nimport type {\n BlockSchema,\n InlineContentSchema,\n StyleSchema,\n} from \"../../schema/index.js\";\nimport { CollaborationOptions } from \"./index.js\";\nimport { ForkYDocExtension } from \"./ForkYDoc.js\";\n\n/**\n * Maps a Y attribution to BlockNote's `y-attributed-*` mark attrs.\n *\n * The mapper must be deterministic in `(format, attribution)` and emit attrs\n * that exactly match the declared mark schema in YAttributionMarks.ts. Any\n * mismatch causes the sync plugin to fire phantom reconcile dispatches in a\n * loop. See ATTRIBUTION.md in @y/prosemirror.\n *\n * Crucially the marks carry only stable identity (`userIds`, plus `format` for\n * the modification mark) — *not* user colors. Colors resolve asynchronously\n * from the {@link UserStore}, so baking them in here would make the mapper's\n * output change under a fixed `(format, attribution)` once a user loads, which\n * is exactly the non-determinism that triggers the reconcile loop. Instead the\n * `AttributionExtension` applies colors as a decoration layer that can\n * update independently of the mark representation.\n */\n/**\n * Whether a ProseMirror document is BlockNote's initial (empty) state:\n * a single empty paragraph block. Ids and props are deliberately ignored —\n * a freshly mounted editor mints a random block id, but that skeleton still\n * carries no real content and must not be written into an empty Y fragment.\n * Anything more (extra blocks, non-empty text, a non-paragraph block, nested\n * children) counts as real content and syncs immediately.\n */\nfunction isInitialBlockNoteDoc<\n BSchema extends BlockSchema,\n I extends InlineContentSchema,\n S extends StyleSchema,\n>(doc: Node): boolean {\n const blocks = docToBlocks<BSchema, I, S>(doc);\n const block = blocks.length === 1 ? blocks[0] : undefined;\n if (!block || block.type !== \"paragraph\" || block.children.length !== 0) {\n return false;\n }\n const { content } = block;\n return (\n content === undefined ||\n ((typeof content === \"string\" || Array.isArray(content)) &&\n content.length === 0)\n );\n}\nexport const mapAttributionToMark = (\n format: Record<string, unknown> | null,\n attribution: {\n insert?: readonly string[];\n delete?: readonly string[];\n format?: Record<string, readonly string[]>;\n insertAt?: number;\n deleteAt?: number;\n formatAt?: number;\n },\n): Record<string, unknown> => {\n const out: Record<string, unknown> = { ...format };\n\n if (attribution.insert) {\n out[\"y-attributed-insert\"] = { userIds: attribution.insert };\n }\n\n if (attribution.delete) {\n out[\"y-attributed-delete\"] = { userIds: attribution.delete };\n }\n\n if (attribution.format) {\n const userIds = [...new Set(Object.values(attribution.format).flat())];\n out[\"y-attributed-format\"] = { userIds, format: attribution.format };\n }\n\n return out;\n};\n\nexport const YSyncExtension = createExtension(\n ({\n options,\n editor,\n }: ExtensionOptions<\n Pick<\n CollaborationOptions,\n | \"fragment\"\n | \"renderer\"\n | \"suggestionDoc\"\n | \"provider\"\n | \"getAttributionMarkClassName\"\n >\n >) => {\n return {\n key: \"ySync\",\n fragment: options.fragment,\n mount: ({ signal }: { signal: AbortSignal }) => {\n // The sync plugin reconnects an existing configuration when its view is\n // recreated. Do not switch an active suggestion editor back to the\n // base fragment on remount.\n if (\n ySyncPluginKey.getState(editor.prosemirrorState)?.ytype ||\n editor.getExtension(ForkYDocExtension)?.store.state.isForked\n ) {\n return;\n }\n\n const configure = () => {\n if (\n signal.aborted ||\n editor.getExtension(ForkYDocExtension)?.store.state.isForked\n ) {\n return;\n }\n editor.exec(\n configureYProsemirror({\n ytype: options.fragment,\n // purposefully not passing `renderer` here, this is only for syncing the main doc, not switching to suggestion mode\n // In the future, we may want view suggestion mode to be the default, and then we can decide how to indicate that through the options.\n // For now though, we are leaving suggestion mode as experimental and must be explicitly enabled through the SuggestionsExtension.\n }),\n );\n };\n\n if (\n options.provider &&\n \"synced\" in options.provider &&\n typeof options.provider.synced === \"boolean\"\n ) {\n if (options.provider[\"synced\"]) {\n configure();\n } else if (\n \"on\" in options.provider &&\n typeof options.provider.on === \"function\"\n ) {\n const provider = options.provider;\n const onSynced = (synced: boolean) => {\n if (synced) {\n configure();\n }\n };\n options.provider.on(\"synced\", onSynced);\n return () => {\n if (\"off\" in provider && typeof provider.off === \"function\") {\n provider.off(\"synced\", onSynced);\n }\n };\n } else {\n throw new Error(\n \"YSyncExtension: provider must have a 'synced' boolean or an 'on' method to listen for 'sync'\",\n );\n }\n } else {\n configure();\n }\n return;\n },\n prosemirrorPlugins: [\n syncPlugin({\n suggestionDoc: options.suggestionDoc,\n mapAttributionToMark,\n // Node-pairing policy for the PM->Y diff: a `blockContainer` whose\n // block-content type changes is treated as a *different* node, so the\n // diff replaces the whole container (deleted + inserted siblings in\n // the blockGroup) instead of producing two block-contents in one\n // container => schema-invalid. No schema change / storage transform\n // needed; `blockContainer` already whitelists the `y-attributed-*`\n // marks. See blockMatchNodes.ts.\n customCompare: blockMatchNodes,\n // Nested `blockGroup`s stay in Y once they exist (hidden while\n // empty) and every new block gets one, so two users nesting a first\n // child under the same block concurrently write into the same\n // group instead of each inserting their own. See\n // persistentBlockGroups.ts.\n transformers: [persistentBlockGroups],\n // Initial-empty gate: a single empty paragraph (any id/props) must\n // not seed an empty Y fragment — see isInitialBlockNoteDoc above\n // and \"Initial-content gate\" in ProsemirrorRdt's doc.\n isInitialContent: isInitialBlockNoteDoc,\n }),\n ],\n runsBefore: [\"default\"],\n } as const;\n },\n);\n","import {\n defaultTransformer,\n deltaToPSteps,\n nodeToDelta,\n pmnodeToDelta,\n ynodeToPmnode,\n} from \"@y/prosemirror\";\nimport * as d from \"lib0/delta\";\nimport { Node } from \"prosemirror-model\";\nimport type { Transaction } from \"prosemirror-state\";\nimport {\n type Block,\n type BlockNoteEditor,\n type BlockSchema,\n type InlineContentSchema,\n type PartialBlock,\n type StyleSchema,\n blockToNode,\n docToBlocks,\n} from \"../index.js\";\nimport { blockMatchNodes } from \"./extensions/blockMatchNodes.js\";\nimport { persistentBlockGroups } from \"./extensions/persistentBlockGroups.js\";\nimport { mapAttributionToMark } from \"./extensions/YSync.js\";\n\nimport * as Y from \"@y/y\";\n\n/**\n * The Y ⇄ ProseMirror pipeline of the collaboration binding (see\n * `YSyncExtension`): attributions become `y-attributed-*` marks and nested\n * `blockGroup`s are persistent (kept in Y, hidden while empty, merged in the\n * view). Every conversion outside a bound editor goes through the same\n * pipeline, so a document imported with `blocksToYDoc` gets its groups and one\n * read with `yDocToBlocks` hides the empty ones.\n */\nexport const blockNoteTransformer: ReturnType<typeof defaultTransformer> =\n defaultTransformer({\n mapAttributionToMark,\n transformers: [persistentBlockGroups],\n });\n\n/**\n * Find the equivalent of a Y.Node in another Y.Doc.\n *\n * For root types this looks up the matching shared key; for sub-types it\n * locates the item by its client/clock ID in the target doc's store.\n */\nexport function findTypeInOtherYdoc<T extends Y.Node<any>>(\n ytype: T,\n otherYdoc: Y.Doc,\n): T {\n const ydoc = ytype.doc;\n if (!ydoc) {\n throw new Error(\"type does not have a ydoc\");\n }\n if (ytype._item === null) {\n /**\n * If is a root type, we need to find the root key in the original ydoc\n * and use it to get the type in the other ydoc.\n */\n const rootKey = Array.from(ydoc.share.keys()).find(\n (key) => ydoc.share.get(key) === ytype,\n );\n if (typeof rootKey !== \"string\") {\n throw new Error(\"type does not exist in other ydoc\");\n }\n return otherYdoc.get(rootKey, ytype.name) as T;\n } else {\n /**\n * If it is a sub type, we use the item id to find the history type.\n */\n const ytypeItem = ytype._item;\n const otherStructs = otherYdoc.store.clients.get(ytypeItem.id.client) ?? [];\n const itemIndex = Y.findIndexSS(otherStructs, ytypeItem.id.clock);\n const otherItem = otherStructs[itemIndex] as Y.Item | undefined;\n if (!otherItem) {\n throw new Error(\"type does not exist in other ydoc\");\n }\n const otherContent = otherItem.content as Y.ContentType | undefined;\n if (!otherContent) {\n throw new Error(\"type does not exist in other ydoc\");\n }\n return otherContent.type as T;\n }\n}\n\n/**\n * Collect all stored Yjs ID ranges belonging to a fragment, including deleted\n * descendants. Items belonging to other shared types are excluded.\n *\n * Resolves the fragment in the supplied document and scans its stored items:\n * walking visible content would miss deleted subtrees. To include all deleted\n * descendants, the document or update must retain them; content already\n * garbage-collected cannot be recovered here.\n *\n * Updates are loaded into a temporary document with `gc: false`, which is\n * destroyed after collection. Caller-provided documents are never destroyed.\n */\nexport function collectFragmentIds(\n fragment: Y.Node,\n docOrUpdate: Uint8Array | Y.Doc,\n): Y.IdSet {\n if (docOrUpdate instanceof Uint8Array) {\n const doc = new Y.Doc({ gc: false });\n try {\n Y.applyUpdate(doc, docOrUpdate);\n return collectFragmentIds(fragment, doc);\n } finally {\n doc.destroy();\n }\n }\n\n const targetFragment = findTypeInOtherYdoc(fragment, docOrUpdate);\n const contentIds = Y.createIdSet();\n for (const structs of docOrUpdate.store.clients.values()) {\n for (const item of structs) {\n if (item instanceof Y.Item && Y.isParentOf(targetFragment, item)) {\n contentIds.add(item.id.client, item.id.clock, item.length);\n }\n }\n }\n return contentIds;\n}\n\n/**\n * Turn Prosemirror JSON to BlockNote style JSON\n * @param editor BlockNote editor\n * @param json Prosemirror JSON\n * @returns BlockNote style JSON\n */\nexport function _prosemirrorJSONToBlocks<\n BSchema extends BlockSchema,\n ISchema extends InlineContentSchema,\n SSchema extends StyleSchema,\n>(editor: BlockNoteEditor<BSchema, ISchema, SSchema>, json: any) {\n // note: theoretically this should also be possible without creating prosemirror nodes,\n // but this is definitely the easiest way\n const doc = editor.pmSchema.nodeFromJSON(json);\n return docToBlocks<BSchema, ISchema, SSchema>(doc);\n}\n\n/**\n * Turn BlockNote JSON to Prosemirror node / state\n * @param editor BlockNote editor\n * @param blocks BlockNote blocks\n * @returns Prosemirror root node\n */\nexport function _blocksToProsemirrorNode<\n BSchema extends BlockSchema,\n ISchema extends InlineContentSchema,\n SSchema extends StyleSchema,\n>(\n editor: BlockNoteEditor<BSchema, ISchema, SSchema>,\n blocks: PartialBlock<BSchema, ISchema, SSchema>[],\n) {\n const pmNodes = blocks.map((b) => blockToNode(b, editor.pmSchema));\n\n const doc = editor.pmSchema.topNodeType.create(\n null,\n editor.pmSchema.nodes[\"blockGroup\"].create(null, pmNodes),\n );\n return doc;\n}\n\n/** YJS / BLOCKNOTE conversions */\n\n/**\n * Whether a `toDeltaDeep()` tree contains a `blockContainer` node.\n *\n * The delta is an untyped tree from an external library whose child\n * collections may be plain arrays or lib0 `List`s, so this walks it\n * structurally (via the iteration protocol) instead of relying on its types.\n */\nfunction deltaHasBlockContainer(node: unknown): boolean {\n if (typeof node !== \"object\" || node === null) {\n return false;\n }\n const record = node as Record<string, unknown>;\n if (record[\"name\"] === \"blockContainer\") {\n return true;\n }\n return (\n deltaChildrenContainBlock(record[\"children\"]) ||\n deltaChildrenContainBlock(record[\"insert\"])\n );\n}\n\nfunction deltaChildrenContainBlock(value: unknown): boolean {\n // Arrays and lib0 `List`s both satisfy the iteration protocol, and\n // everything else (strings are excluded by the typeof check, plain\n // attribute values, null) is skipped.\n if (\n typeof value !== \"object\" ||\n value === null ||\n !(Symbol.iterator in value)\n ) {\n return false;\n }\n for (const child of value as Iterable<unknown>) {\n if (deltaHasBlockContainer(child)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Turn a Y.Node collaborative doc into a BlockNote document (BlockNote style JSON of all blocks)\n * @param editor BlockNote editor\n * @param fragment Y.Node\n * @returns BlockNote document (BlockNote style JSON of all blocks)\n */\nexport function yfragmentToBlocks<\n BSchema extends BlockSchema,\n ISchema extends InlineContentSchema,\n SSchema extends StyleSchema,\n>(editor: BlockNoteEditor<BSchema, ISchema, SSchema>, fragment: Y.Node) {\n // Docs seeded by the current `blocksToYDoc([])` are pristine-empty: no Y\n // children at all. This covers the common case without allocating a delta;\n // the structural check below only remains for pre-existing fragments (see\n // below).\n if (fragment.length === 0) {\n return [];\n }\n const delta = fragment.toDeltaDeep();\n // A fragment without block containers holds no blocks — e.g. one written\n // by an older `blocksToYDoc([])` (which used to write a childless block\n // group). Returning early avoids materializing the schema filler paragraph\n // in `ynodeToPmnode` below, whose id would be freshly minted on every\n // read — making empty docs unstable.\n if (!deltaHasBlockContainer(delta)) {\n return [];\n }\n const pmNode = ynodeToPmnode(fragment, editor.pmSchema, {\n renderer: null,\n transformer: blockNoteTransformer,\n });\n return docToBlocks<BSchema, ISchema, SSchema>(pmNode);\n}\n\n/**\n * Convert blocks to a Y.Node\n *\n * This can be used when importing existing content to Y.Doc for the first time,\n * note that this should not be used to rehydrate a Y.Doc from a database once\n * collaboration has begun as all history will be lost\n *\n * @param editor BlockNote editor\n * @param blocks the blocks to convert\n * @param fragment XML fragment name\n * @returns Y.Node\n */\nexport function blocksToYType<\n BSchema extends BlockSchema,\n ISchema extends InlineContentSchema,\n SSchema extends StyleSchema,\n>(\n editor: BlockNoteEditor<BSchema, ISchema, SSchema>,\n blocks: Block<BSchema, ISchema, SSchema>[],\n fragment?: Y.Node,\n) {\n if (!fragment) {\n fragment = new Y.Doc().get(\"prosemirror\");\n }\n // An empty block array writes nothing: the fragment stays pristine-empty\n // (no childless block group). This matters for the sync layer — the\n // @y/prosemirror initial-content gate only engages when the ytype has no\n // children (`ytype.length === 0`), keeping each mount's schema-default\n // skeleton local instead of committing a competing paragraph item per\n // client (the init race). See `EmptyDocBinding.test.ts`.\n if (blocks.length === 0) {\n return fragment;\n }\n fragment.applyDelta(\n pmnodeToDelta(_blocksToProsemirrorNode(editor, blocks), {\n transformer: blockNoteTransformer,\n }),\n );\n return fragment;\n}\n\n/**\n * Turn a Y.Doc collaborative doc into a BlockNote document (BlockNote style JSON of all blocks)\n * @param editor BlockNote editor\n * @param ydoc Y.Doc\n * @param fragment XML fragment name\n * @returns BlockNote document (BlockNote style JSON of all blocks)\n */\nexport function yDocToBlocks<\n BSchema extends BlockSchema,\n ISchema extends InlineContentSchema,\n SSchema extends StyleSchema,\n>(\n editor: BlockNoteEditor<BSchema, ISchema, SSchema>,\n ydoc: Y.Doc,\n fragment = \"prosemirror\",\n) {\n return yfragmentToBlocks(editor, ydoc.get(fragment));\n}\n\n/**\n * This can be used when importing existing content to Y.Doc for the first time,\n * note that this should not be used to rehydrate a Y.Doc from a database once\n * collaboration has begun as all history will be lost\n *\n * @param editor BlockNote editor\n * @param blocks the blocks to convert\n * @param fragment XML fragment name\n */\nexport function blocksToYDoc<\n BSchema extends BlockSchema,\n ISchema extends InlineContentSchema,\n SSchema extends StyleSchema,\n>(\n editor: BlockNoteEditor<BSchema, ISchema, SSchema>,\n blocks: PartialBlock<BSchema, ISchema, SSchema>[],\n fragment = \"prosemirror\",\n) {\n const doc = new Y.Doc();\n // An empty block array seeds a pristine-empty fragment (see\n // `blocksToYType` above for why writing nothing matters).\n if (blocks.length === 0) {\n doc.get(fragment);\n return doc;\n }\n const delta = pmnodeToDelta(_blocksToProsemirrorNode(editor, blocks), {\n transformer: blockNoteTransformer,\n });\n doc.get(fragment).applyDelta(delta);\n return doc;\n}\n\n/**\n * Diff two ProseMirror documents into a delta, using BlockNote's node-pairing\n * policy ({@link blockMatchNodes}) so a block's content-type change is reported\n * as a replace rather than a schema-invalid in-place edit.\n */\nexport function docDiffToDelta(previousDoc: Node, newDoc: Node) {\n const initialDelta = nodeToDelta(previousDoc);\n const finalDelta = nodeToDelta(newDoc);\n return d.diff(initialDelta.done(), finalDelta.done(), {\n compare: blockMatchNodes,\n });\n}\n\n/**\n * Append steps that render a Y node into the transaction's current document.\n * Supports both plain and already-attributed documents, replacing old preview\n * marks with the renderer's attributions using BlockNote's node-pairing policy.\n * Defaults to the binding's pipeline ({@link blockNoteTransformer}). Does not\n * dispatch or write to the Y node; the caller controls sync configuration and\n * dispatch.\n */\nexport function yNodeToTransaction(\n tr: Transaction,\n node: Y.Node,\n options: NonNullable<Parameters<typeof ynodeToPmnode>[2]> = {},\n): Transaction {\n const renderedDoc = ynodeToPmnode(node, tr.doc.type.schema, {\n transformer: blockNoteTransformer,\n ...options,\n });\n const renderedDelta = docDiffToDelta(tr.doc, renderedDoc);\n return deltaToPSteps(tr, renderedDelta).setMeta(\"y-sync-hydration\", {\n delta: renderedDelta,\n });\n}\n","import * as Y from \"@y/y\";\nimport {\n createExtension,\n createStore,\n ExtensionOptions,\n} from \"../../editor/BlockNoteExtension.js\";\nimport { CollaborationOptions } from \"./index.js\";\nimport { YCursorExtension } from \"./YCursorPlugin.js\";\nimport { findTypeInOtherYdoc } from \"../utils.js\";\nimport { configureYProsemirror } from \"@y/prosemirror\";\n\nexport const ForkYDocExtension = createExtension(\n ({ editor, options }: ExtensionOptions<CollaborationOptions>) => {\n let forkedState:\n | {\n originalFragment: Y.Node;\n forkedFragment: Y.Node;\n cursor: ReturnType<ReturnType<typeof YCursorExtension>> | undefined;\n }\n | undefined = undefined;\n\n const store = createStore({ isForked: false });\n\n return {\n key: \"yForkDoc\",\n store,\n /**\n * Fork the Y.js document from syncing to the remote,\n * allowing modifications to the document without affecting the remote.\n * These changes can later be rolled back or applied to the remote.\n */\n fork({\n /**\n * The initial update to apply to the forked document.\n */\n initialUpdate,\n }: {\n initialUpdate?: Uint8Array;\n } = {}) {\n if (forkedState) {\n return;\n }\n\n const originalFragment = options.fragment;\n\n if (!originalFragment) {\n throw new Error(\"No fragment to fork from\");\n }\n\n const doc = new Y.Doc();\n // Copy the original document to a new Yjs document\n Y.applyUpdateV2(\n doc,\n initialUpdate ?? Y.encodeStateAsUpdateV2(originalFragment.doc!),\n );\n\n // Find the forked fragment in the new Yjs document\n const forkedFragment = findTypeInOtherYdoc(originalFragment, doc);\n\n forkedState = {\n originalFragment,\n forkedFragment,\n cursor: editor.unregisterExtension(YCursorExtension),\n };\n\n options.provider?.awareness?.setLocalStateField(\"cursor\", null);\n store.setState({ isForked: true });\n editor.exec(configureYProsemirror({ ytype: forkedFragment }));\n },\n\n /**\n * Resume syncing the Y.js document to the remote\n * If `keepChanges` is true, any changes that have been made to the forked document will be applied to the original document.\n * Otherwise, the original document will be restored and the changes will be discarded.\n */\n merge({\n keepChanges,\n renderer = options.renderer,\n }: {\n keepChanges: boolean;\n renderer?: Y.DiffRenderer | null;\n }) {\n if (!forkedState) {\n return;\n }\n\n const { originalFragment, forkedFragment, cursor } = forkedState;\n // Restore the live binding before a cursor plugin view can use it.\n editor.exec(\n configureYProsemirror({\n ytype: originalFragment,\n renderer,\n }),\n );\n if (cursor) {\n editor.registerExtension(cursor);\n }\n\n if (keepChanges) {\n // Apply any changes that have been made to the fork, onto the original doc\n const update = Y.encodeStateAsUpdate(\n forkedFragment.doc!,\n Y.encodeStateVector(originalFragment.doc!),\n );\n // This arrives through Yjs synchronization, so normal ProseMirror\n // history does not record the merge as a local undoable transaction.\n Y.applyUpdate(originalFragment.doc!, update, editor);\n }\n // Reset the forked state\n forkedState = undefined;\n forkedFragment.doc!.destroy();\n // Tell the store that the editor is no longer forked\n store.setState({ isForked: false });\n },\n } as const;\n },\n);\n","import { relativePositionStore, ySyncPluginKey } from \"@y/prosemirror\";\nimport { createExtension } from \"../../editor/BlockNoteExtension.js\";\n\nexport const RelativePositionMappingExtension = createExtension(\n ({ editor }) => {\n return {\n key: \"yPositionMapping\",\n mapPosition: (position: number, side: \"left\" | \"right\" = \"left\") => {\n const ySyncPluginState = ySyncPluginKey.getState(\n editor.prosemirrorState,\n );\n if (!ySyncPluginState?.ytype) {\n throw new Error(\"YSync plugin state not found\");\n }\n\n // 0 is a special case & always should map to itself\n if (position === 0) {\n return () => 0;\n }\n\n const posStore = relativePositionStore(\n editor.prosemirrorView,\n editor.prosemirrorState.doc.resolve(\n position + (side === \"right\" ? 1 : -1),\n ),\n );\n\n if (posStore === null) {\n throw new Error(\"Position not found, cannot track positions\");\n }\n\n return () => {\n const pos = posStore(editor.prosemirrorView);\n\n // This can happen if the element is garbage collected\n if (pos === null) {\n throw new Error(\"Position not found, cannot track positions\");\n }\n\n return pos.pos + (side === \"right\" ? -1 : 1);\n };\n },\n } as const;\n },\n);\n","import { getMarkRange, posToDOMRect } from \"@tiptap/core\";\n\nimport {\n createExtension,\n ExtensionOptions,\n} from \"../../editor/BlockNoteExtension.js\";\nimport {\n acceptChanges,\n rejectAllChanges,\n rejectChanges,\n configureYProsemirror,\n acceptAllChanges,\n} from \"@y/prosemirror\";\nimport { CollaborationOptions } from \"./index.js\";\nimport { findTypeInOtherYdoc } from \"../utils.js\";\nimport { normalizeToUserStore } from \"../../user/index.js\";\n\nexport const SuggestionsExtension = createExtension(\n ({ editor, options }: ExtensionOptions<CollaborationOptions>) => {\n const suggestionDoc = options.suggestionDoc;\n if (!suggestionDoc) {\n throw new Error(\"Suggestion doc not found\");\n }\n // Shared with the rest of collaboration; the collaboration extension passes\n // an already-built store here.\n const userStore = normalizeToUserStore(options.resolveUsers);\n\n function getSuggestionElementAtPos(pos: number) {\n let currentNode = editor.prosemirrorView.nodeDOM(pos);\n while (currentNode && currentNode.parentElement) {\n if (currentNode.nodeName === \"INS\" || currentNode.nodeName === \"DEL\") {\n return currentNode as HTMLElement;\n }\n currentNode = currentNode.parentElement;\n }\n return null;\n }\n\n function getMarkAtPos(pos: number, markType: string) {\n return editor.transact((tr) => {\n const resolvedPos = tr.doc.resolve(pos);\n const mark = resolvedPos\n .marks()\n .find((mark) => mark.type.name === markType);\n\n if (!mark) {\n return;\n }\n\n const markRange = getMarkRange(resolvedPos, mark.type);\n if (!markRange) {\n return;\n }\n\n return {\n range: markRange,\n mark,\n get text() {\n return tr.doc.textBetween(markRange.from, markRange.to);\n },\n get position() {\n // to minimize re-renders, we convert to JSON, which is the same shape anyway\n return posToDOMRect(\n editor.prosemirrorView,\n markRange.from,\n markRange.to,\n ).toJSON() as DOMRect;\n },\n };\n });\n }\n\n function getSuggestionAtSelection() {\n return editor.transact((tr) => {\n const selection = tr.selection;\n if (!selection.empty) {\n return undefined;\n }\n return (\n getMarkAtPos(selection.anchor, \"insertion\") ||\n getMarkAtPos(selection.anchor, \"deletion\") ||\n getMarkAtPos(selection.anchor, \"modification\")\n );\n });\n }\n\n return {\n key: \"suggestions\",\n userStore,\n runsBefore: [\"ySync\"],\n viewSuggestions: () => {\n if (options.renderer) {\n options.renderer.suggestionMode = false;\n }\n editor.exec(\n configureYProsemirror({\n ytype: findTypeInOtherYdoc(options.fragment, suggestionDoc),\n renderer: options.renderer,\n }),\n );\n },\n enableSuggestions: () => {\n if (options.renderer) {\n options.renderer.suggestionMode = true;\n }\n editor.exec(\n configureYProsemirror({\n ytype: findTypeInOtherYdoc(options.fragment, suggestionDoc),\n renderer: options.renderer,\n }),\n );\n },\n disableSuggestions: () => {\n editor.exec(\n configureYProsemirror({\n ytype: options.fragment,\n renderer: null,\n }),\n );\n },\n applyAllSuggestions: () => {\n return editor.exec(acceptAllChanges());\n },\n applySuggestion: (start: number, end?: number) => {\n return editor.exec(acceptChanges(start, end));\n },\n revertSuggestion: (start: number, end?: number) => {\n return editor.exec(rejectChanges(start, end));\n },\n revertAllSuggestions: () => {\n return editor.exec(rejectAllChanges());\n },\n\n getSuggestionElementAtPos,\n getMarkAtPos,\n getSuggestionAtSelection,\n getSuggestionAtCoords: (coords: { left: number; top: number }) => {\n return editor.transact(() => {\n const posAtCoords = editor.prosemirrorView.posAtCoords(coords);\n if (posAtCoords === null || posAtCoords?.inside === -1) {\n return undefined;\n }\n\n return (\n getMarkAtPos(posAtCoords.pos, \"y-attributed-insert\") ||\n getMarkAtPos(posAtCoords.pos, \"y-attributed-delete\") ||\n getMarkAtPos(posAtCoords.pos, \"y-attributed-format\")\n );\n });\n },\n checkUnresolvedSuggestions: () => {\n let hasUnresolvedSuggestions = false;\n\n editor.prosemirrorState.doc.descendants((node) => {\n if (hasUnresolvedSuggestions) {\n return false;\n }\n\n hasUnresolvedSuggestions =\n node.marks.findIndex(\n (mark) =>\n mark.type.name === \"y-attributed-insert\" ||\n mark.type.name === \"y-attributed-delete\" ||\n mark.type.name === \"y-attributed-format\",\n ) !== -1;\n\n return true;\n });\n\n return hasUnresolvedSuggestions;\n },\n } as const;\n },\n);\n","import { docToDelta } from \"@y/prosemirror\";\nimport * as Y from \"@y/y\";\n\nimport type { Block } from \"../../blocks/defaultBlocks.js\";\nimport type { BlockNoteEditor } from \"../../editor/BlockNoteEditor.js\";\nimport { createExtension } from \"../../editor/BlockNoteExtension.js\";\nimport { createUserStore, type User } from \"../../user/index.js\";\nimport {\n _blocksToProsemirrorNode,\n docDiffToDelta,\n findTypeInOtherYdoc,\n yNodeToTransaction,\n} from \"../utils.js\";\nimport { AttributionExtension } from \"./AttributionExtension.js\";\nimport type { GetAttributionMarkClassName } from \"./YAttributionMarks.js\";\n\n/**\n * A version diff has no real authors, so all `y-attributed-*` marks carry one\n * synthetic id. Its user has an empty name: it only gives the marks their color,\n * and the tooltip names just the kind of change, because a diff can't tell which\n * intermediate version introduced it.\n */\nconst DIFF_AUTHOR_ID = \"blocknote:version-diff\";\n\n/** Colors used for the version diff marks — the palette's blue. */\nconst DIFF_AUTHOR_COLOR = \"#2948b3\";\nconst DIFF_AUTHOR_COLOR_LIGHT = \"#d6defd\";\n\nexport type DiffVersioningExtensionOptions = {\n /**\n * The color used for the diff's attribution marks. Defaults to a blue.\n */\n color?: string;\n /**\n * See {@link GetAttributionMarkClassName}. Forwarded to the underlying\n * {@link AttributionExtension} to override mark styling by change type.\n */\n getAttributionMarkClassName?: GetAttributionMarkClassName;\n};\n\n/**\n * Records the author of each transaction on `doc` into a mutable\n * {@link Y.ContentMap}, so the resulting attribution marks carry a non-empty\n * `userIds` (and therefore resolve to a color). The listener must be\n * attached *before* the attributed transaction runs. Mirrors the store used by\n * the suggestion gallery example (`createAttributionStore`).\n */\nfunction attributeTransactionsTo(doc: Y.Doc, userId: string): Y.ContentMap {\n const attrs = Y.createContentMap();\n doc.on(\"beforeObserverCalls\", (tr) => {\n if (!tr.insertSet.isEmpty()) {\n Y.insertIntoIdMap(\n attrs.inserts,\n Y.createIdMapFromIdSet(tr.insertSet, [\n Y.createContentAttribute(\"insert\", userId),\n ]),\n );\n }\n if (!tr.deleteSet.isEmpty()) {\n Y.insertIntoIdMap(\n attrs.deletes,\n Y.createIdMapFromIdSet(tr.deleteSet, [\n Y.createContentAttribute(\"delete\", userId),\n ]),\n );\n }\n });\n return attrs;\n}\n\n/**\n * An opt-in extension that renders a read-only diff between two BlockNote\n * documents (`Block[]`) directly in the editor, marking insertions/deletions\n * with the `y-attributed-*` suggestion marks — the same visual result the Yjs\n * collaboration adapter produces, but driven from two plain block arrays with\n * no server and no live Yjs sync.\n *\n * It composes {@link AttributionExtension} (which registers the attribution\n * marks and drives their colors + hover tooltips from a user store), and adds\n * the {@link renderDiff} capability.\n *\n * Registering this extension is what makes non-collaborative versioning\n * (`inMemoryVersioning`) capable of showing diffs: the in-memory preview\n * controller looks this up by key (`\"diffVersioning\"`) and delegates to\n * {@link renderDiff}, falling back to a static document swap when it's absent.\n *\n * `renderDiff` is also a standalone, directly-callable API — you can register\n * just this extension and call\n * `editor.getExtension(DiffVersioningExtension).renderDiff(target, baseline)`\n * to render a known diff (e.g. in tests).\n *\n * @example\n * ```ts\n * const editor = BlockNoteEditor.create({\n * extensions: [DiffVersioningExtension()],\n * });\n * editor.getExtension(DiffVersioningExtension)!.renderDiff(target, baseline);\n * ```\n */\nexport const DiffVersioningExtension = createExtension(\n ({\n options,\n editor,\n }: {\n options: DiffVersioningExtensionOptions | undefined;\n editor: BlockNoteEditor<any, any, any>;\n }) => {\n const color = options?.color ?? DIFF_AUTHOR_COLOR;\n // Only the default pairs with a hand-tuned light tint; a caller-supplied\n // colour gets the derived one (see `userMarkColors`).\n const colorLight =\n options?.color === undefined ? DIFF_AUTHOR_COLOR_LIGHT : undefined;\n\n // Cached up front, so a hover never shows the raw id before it resolves.\n const userStore = createUserStore<User>(async () => []);\n userStore.setUser({\n id: DIFF_AUTHOR_ID,\n username: \"\",\n avatarUrl: \"\",\n color,\n colorLight,\n });\n\n return {\n key: \"diffVersioning\",\n // Compose AttributionExtension: registers the y-attributed-* marks and\n // drives their colors from the (static) user store.\n blockNoteExtensions: [\n AttributionExtension({\n resolveUsers: userStore,\n getAttributionMarkClassName: options?.getAttributionMarkClassName,\n }),\n ],\n /**\n * Render a read-only diff of `baselineBlocks` → `snapshotBlocks` into the\n * editor, marking insertions and deletions. Uses the \"two-doc fork\" recipe\n * so the two Y.Docs share history — a hard requirement for\n * `createDiffRenderer`, which diffs by Yjs client/clock ids.\n */\n renderDiff(\n snapshotBlocks: Block<any, any, any>[],\n baselineBlocks: Block<any, any, any>[],\n ) {\n if (!editor.pmSchema.marks[\"y-attributed-insert\"]) {\n throw new Error(\n \"DiffVersioningExtension: the y-attributed-* marks are missing from \" +\n \"the schema. This should not happen — the extension registers them \" +\n \"via AttributionExtension.\",\n );\n }\n\n const baselineNode = _blocksToProsemirrorNode(editor, baselineBlocks);\n const snapshotNode = _blocksToProsemirrorNode(editor, snapshotBlocks);\n\n // gc must stay off so the attribution manager can read the full struct\n // store (including deleted items) when diffing.\n const prevDoc = new Y.Doc({ gc: false });\n const prevType = prevDoc.get(\"prosemirror\");\n prevDoc.transact(() => {\n prevType.applyDelta(docToDelta(baselineNode) as any);\n });\n\n // Fork prevDoc into nextDoc so they share client/clock ids, then apply the\n // baseline → snapshot delta as a new transaction. New content gets ids\n // that prevDoc lacks (→ inserts); items retained-away become deletes.\n const nextDoc = new Y.Doc({ gc: false });\n Y.applyUpdateV2(nextDoc, Y.encodeStateAsUpdateV2(prevDoc));\n const nextType = findTypeInOtherYdoc(prevType, nextDoc);\n\n // Attach the author store BEFORE applying the delta so the diff\n // transaction's inserts/deletes are attributed.\n const attrs = attributeTransactionsTo(nextDoc, DIFF_AUTHOR_ID);\n\n const delta = docDiffToDelta(baselineNode, snapshotNode);\n nextDoc.transact(() => {\n nextType.applyDelta(delta as any);\n }, DIFF_AUTHOR_ID);\n\n const renderer = Y.createDiffRenderer(prevDoc, nextDoc, {\n attributions: attrs,\n });\n\n // The diff is applied on top of whatever is currently on screen: the\n // attributed content comes entirely from the baseline -> snapshot Y\n // diff above, not from the ProseMirror before-state, so emptying the\n // document first would only churn node views for no gain.\n editor.exec((state, dispatch) => {\n const tr = yNodeToTransaction(state.tr, nextType, { renderer });\n if (dispatch) {\n dispatch(tr);\n }\n return true;\n });\n\n prevDoc.destroy();\n nextDoc.destroy();\n },\n };\n },\n);\n","import type { Awareness } from \"@y/protocols/awareness\";\nimport type * as Y from \"@y/y\";\nimport { BlockNoteEditorOptions } from \"../../editor/BlockNoteEditor.js\";\nimport {\n createExtension,\n ExtensionOptions,\n} from \"../../editor/BlockNoteExtension.js\";\nimport { normalizeToUserStore, UserStoreOrResolver } from \"../../user/index.js\";\nimport { AttributionExtension } from \"./AttributionExtension.js\";\nimport { ForkYDocExtension } from \"./ForkYDoc.js\";\nimport { RelativePositionMappingExtension } from \"./RelativePositionMapping.js\";\nimport { SuggestionsExtension } from \"./Suggestions.js\";\nimport { CollaborationUser, YCursorExtension } from \"./YCursorPlugin.js\";\nimport type { GetAttributionMarkClassName } from \"./YAttributionMarks.js\";\nimport { YSyncExtension } from \"./YSync.js\";\n\nexport type CollaborationOptions = {\n /**\n * The Yjs Type that's used for collaboration.\n */\n fragment: Y.Node;\n /**\n * The user info for the current user that's shown to other collaborators.\n */\n user: CollaborationUser;\n /**\n * Resolve user information (usernames, colors) for suggestions and versions,\n * used to drive suggestion-author tooltips, suggestion colors and\n * version-history author labels.\n *\n * Either a resolver function (called with the ids of users that are not yet\n * cached, returning their information — a user store is built from it\n * internally) or a pre-built user store (see `createUserStore`). Pass the same\n * store you give the comments extension so a single de-duped user cache is\n * shared across comments, suggestions and versioning.\n */\n resolveUsers?: UserStoreOrResolver;\n /**\n * A Yjs provider (used for awareness / cursor information)\n */\n provider?: { awareness?: Awareness };\n /**\n * Optional function to customize how cursors of users are rendered\n */\n renderCursor?: (user: CollaborationUser) => HTMLElement;\n /**\n * Optional flag to set when the user label should be shown with the default\n * collaboration cursor. Setting to \"always\" will always show the label,\n * while \"activity\" will only show the label when the user moves the cursor\n * or types. Defaults to \"activity\".\n */\n showCursorLabels?: \"always\" | \"activity\";\n /**\n * The renderer for the collaboration.\n */\n renderer?: Y.DiffRenderer;\n /**\n * The suggestion doc for the collaboration. If using suggestion mode\n */\n suggestionDoc?: Y.Doc;\n\n /**\n * Optional callback to override suggestion-mark styling by change type instead\n * of by author. Given a mark's content/modification type, return a class name\n * applied to the mark and its hover tooltip; the per-user color is then\n * dropped for that mark. See {@link GetAttributionMarkClassName}.\n */\n getAttributionMarkClassName?: GetAttributionMarkClassName;\n};\n\nexport const CollaborationExtension = createExtension(\n ({ options }: ExtensionOptions<CollaborationOptions>) => {\n // Build a single user store here (from a resolver callback or a store the\n // consumer passed in) and hand that same store down to every sub-extension\n // that needs it: suggestions and suggestion-mark tooltips/colors.\n // so they share one de-duped cache. Passing the resolved store (rather than\n // the raw resolver) is what guarantees the sharing: each child re-normalizes\n // it to itself instead of building its own.\n const userStore = normalizeToUserStore(options.resolveUsers);\n const optionsWithUserStore = { ...options, resolveUsers: userStore };\n return {\n key: \"collaboration\",\n fragment: options.fragment,\n userStore,\n blockNoteExtensions: [\n options.suggestionDoc\n ? SuggestionsExtension(optionsWithUserStore)\n : null,\n RelativePositionMappingExtension(),\n ForkYDocExtension(options),\n YSyncExtension(optionsWithUserStore),\n YCursorExtension(options),\n AttributionExtension({\n resolveUsers: userStore,\n getAttributionMarkClassName: options.getAttributionMarkClassName,\n }),\n ].filter((a) => a !== null),\n } as const;\n },\n);\n\nexport function withCollaboration<\n Options extends Partial<BlockNoteEditorOptions<any, any, any>>,\n>(\n options: Options & {\n /**\n * Options for configuring the collaboration functionality.\n */\n collaboration: CollaborationOptions;\n },\n): Options {\n if (options.initialContent) {\n // eslint-disable-next-line no-console\n console.warn(\n \"When using Collaboration, initialContent might cause conflicts, because changes should come from the collaboration provider\",\n );\n }\n // Keep normal ProseMirror history: the v14 sync plugin excludes incoming\n // Yjs changes from the local undo stack.\n return {\n ...options,\n extensions: [\n ...(options.extensions ?? []),\n CollaborationExtension(options.collaboration),\n ],\n // We don't want the default initial content, since it will generate a random id for the initial block on each client,\n // leading to conflicts when syncing happens afterwards.\n initialContent: [{ type: \"paragraph\", id: \"initialBlockId\" }],\n };\n}\n\nexport * from \"./AttributionExtension.js\";\nexport * from \"./DiffVersioningExtension.js\";\nexport * from \"./ForkYDoc.js\";\nexport * from \"./persistentBlockGroups.js\";\nexport * from \"./RelativePositionMapping.js\";\nexport * from \"./Suggestions.js\";\nexport * from \"./YAttributionMarks.js\";\nexport * from \"./YCursorPlugin.js\";\nexport * from \"./YSync.js\";\n","import * as Y from \"@y/y\";\nimport type {\n CommentData,\n CommentReactionData,\n ThreadData,\n} from \"../../comments/types.js\";\n\nexport function commentToYType(comment: CommentData) {\n const yType = new Y.Node();\n yType.setAttr(\"id\", comment.id);\n yType.setAttr(\"userId\", comment.userId);\n yType.setAttr(\"createdAt\", comment.createdAt.getTime());\n yType.setAttr(\"updatedAt\", comment.updatedAt.getTime());\n if (comment.deletedAt) {\n yType.setAttr(\"deletedAt\", comment.deletedAt.getTime());\n yType.setAttr(\"body\", undefined);\n } else {\n yType.setAttr(\"body\", comment.body);\n }\n if (comment.reactions.length > 0) {\n throw new Error(\"Reactions should be empty in commentToYType\");\n }\n\n /**\n * Reactions are stored in a map keyed by {userId-emoji},\n * this makes it easy to add / remove reactions and in a way that works local-first.\n * The cost is that \"reading\" the reactions is a bit more complex (see yTypeToReactions).\n */\n yType.setAttr(\"reactionsByUser\", new Y.Node());\n yType.setAttr(\"metadata\", comment.metadata);\n\n return yType;\n}\n\nexport function threadToYType(thread: ThreadData) {\n const yType = new Y.Node();\n yType.setAttr(\"id\", thread.id);\n yType.setAttr(\"createdAt\", thread.createdAt.getTime());\n yType.setAttr(\"updatedAt\", thread.updatedAt.getTime());\n const commentsType = new Y.Node();\n\n commentsType.push(thread.comments.map((comment) => commentToYType(comment)));\n\n yType.setAttr(\"comments\", commentsType);\n yType.setAttr(\"resolved\", thread.resolved);\n yType.setAttr(\"resolvedUpdatedAt\", thread.resolvedUpdatedAt?.getTime());\n yType.setAttr(\"resolvedBy\", thread.resolvedBy);\n yType.setAttr(\"metadata\", thread.metadata);\n return yType;\n}\n\ntype SingleUserCommentReactionData = {\n emoji: string;\n createdAt: Date;\n userId: string;\n};\n\nexport function yTypeToReaction(yType: Y.Node): SingleUserCommentReactionData {\n return {\n emoji: yType.getAttr(\"emoji\"),\n createdAt: new Date(yType.getAttr(\"createdAt\")),\n userId: yType.getAttr(\"userId\"),\n };\n}\n\nfunction yTypeToReactions(yType: Y.Node): CommentReactionData[] {\n const flatReactions = [...yType.attrValues()].map((reaction: Y.Node) =>\n yTypeToReaction(reaction),\n );\n // combine reactions by the same emoji\n return flatReactions.reduce(\n (acc: CommentReactionData[], reaction: SingleUserCommentReactionData) => {\n const existingReaction = acc.find((r) => r.emoji === reaction.emoji);\n if (existingReaction) {\n existingReaction.userIds.push(reaction.userId);\n existingReaction.createdAt = new Date(\n Math.min(\n existingReaction.createdAt.getTime(),\n reaction.createdAt.getTime(),\n ),\n );\n } else {\n acc.push({\n emoji: reaction.emoji,\n createdAt: reaction.createdAt,\n userIds: [reaction.userId],\n });\n }\n return acc;\n },\n [] as CommentReactionData[],\n );\n}\n\nexport function yTypeToComment(yType: Y.Node): CommentData {\n return {\n type: \"comment\",\n id: yType.getAttr(\"id\"),\n userId: yType.getAttr(\"userId\"),\n createdAt: new Date(yType.getAttr(\"createdAt\")),\n updatedAt: new Date(yType.getAttr(\"updatedAt\")),\n deletedAt: yType.getAttr(\"deletedAt\")\n ? new Date(yType.getAttr(\"deletedAt\"))\n : undefined,\n reactions: yTypeToReactions(yType.getAttr(\"reactionsByUser\")),\n metadata: yType.getAttr(\"metadata\"),\n body: yType.getAttr(\"body\"),\n };\n}\n\nexport function yTypeToThread(yType: Y.Node): ThreadData {\n return {\n type: \"thread\",\n id: yType.getAttr(\"id\"),\n createdAt: new Date(yType.getAttr(\"createdAt\")),\n updatedAt: new Date(yType.getAttr(\"updatedAt\")),\n comments: ((yType.getAttr(\"comments\") as Y.Node)?.toArray() || []).map(\n (comment) => yTypeToComment(comment as Y.Node),\n ),\n resolved: yType.getAttr(\"resolved\"),\n resolvedUpdatedAt: new Date(yType.getAttr(\"resolvedUpdatedAt\")),\n resolvedBy: yType.getAttr(\"resolvedBy\"),\n metadata: yType.getAttr(\"metadata\"),\n };\n}\n","import * as Y from \"@y/y\";\nimport type { ThreadData } from \"../../comments/types.js\";\nimport { ThreadStore } from \"../../comments/threadstore/ThreadStore.js\";\nimport type { ThreadStoreAuth } from \"../../comments/threadstore/ThreadStoreAuth.js\";\nimport { yTypeToThread } from \"./yjsHelpers.js\";\n\n/**\n * This is an abstract class that only implements the READ methods required by the ThreadStore interface.\n * The data is read from a @y/y Type used as a map (via attributes).\n */\nexport abstract class YjsThreadStoreBase extends ThreadStore {\n constructor(\n protected readonly threadsYType: Y.Node,\n auth: ThreadStoreAuth,\n ) {\n super(auth);\n }\n\n // TODO: async / reactive interface?\n public getThread(threadId: string) {\n const yThread = this.threadsYType.getAttr(threadId);\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n const thread = yTypeToThread(yThread);\n return thread;\n }\n\n public getThreads(): Map<string, ThreadData> {\n const threadMap = new Map<string, ThreadData>();\n this.threadsYType.forEachAttr((yThread: any, id: string | number) => {\n if (yThread instanceof Y.Node) {\n threadMap.set(String(id), yTypeToThread(yThread));\n }\n });\n return threadMap;\n }\n\n public subscribe(cb: (threads: Map<string, ThreadData>) => void) {\n const observer = () => {\n cb(this.getThreads());\n };\n\n this.threadsYType.observeDeep(observer);\n\n return () => {\n this.threadsYType.unobserveDeep(observer);\n };\n }\n}\n","import * as Y from \"@y/y\";\nimport type { CommentBody } from \"../../comments/types.js\";\nimport type { ThreadStoreAuth } from \"../../comments/threadstore/ThreadStoreAuth.js\";\nimport { YjsThreadStoreBase } from \"./YjsThreadStoreBase.js\";\n\n/**\n * This is a REST-based implementation of the YjsThreadStoreBase for @y/y (v14).\n * It Reads data directly from the underlying document (same as YjsThreadStore),\n * but for Writes, it sends data to a REST API that should:\n * - check the user has the correct permissions to make the desired changes\n * - apply the updates to the underlying Yjs document\n *\n * (see https://github.com/TypeCellOS/BlockNote-demo-nextjs-hocuspocus)\n *\n * The reason we still use the Yjs document as underlying storage is that it makes it easy to\n * sync updates in real-time to other collaborators.\n * (but technically, you could also implement a different storage altogether\n * and not store the thread related data in the Yjs document)\n */\nexport class RESTYjsThreadStore extends YjsThreadStoreBase {\n constructor(\n private readonly BASE_URL: string,\n private readonly headers: Record<string, string>,\n threadsYType: Y.Node,\n auth: ThreadStoreAuth,\n ) {\n super(threadsYType, auth);\n }\n\n private doRequest = async (path: string, method: string, body?: any) => {\n const response = await fetch(`${this.BASE_URL}${path}`, {\n method,\n body: JSON.stringify(body),\n headers: {\n \"Content-Type\": \"application/json\",\n ...this.headers,\n },\n });\n\n if (!response.ok) {\n throw new Error(`Failed to ${method} ${path}: ${response.statusText}`);\n }\n\n return response.json();\n };\n\n public addThreadToDocument = async (options: {\n threadId: string;\n selection: {\n head: number;\n anchor: number;\n };\n }) => {\n const { threadId, ...rest } = options;\n return this.doRequest(`/${threadId}/addToDocument`, \"POST\", rest);\n };\n\n public createThread = async (options: {\n initialComment: {\n body: CommentBody;\n metadata?: any;\n };\n metadata?: any;\n }) => {\n return this.doRequest(\"\", \"POST\", options);\n };\n\n public addComment = (options: {\n comment: {\n body: CommentBody;\n metadata?: any;\n };\n threadId: string;\n }) => {\n const { threadId, ...rest } = options;\n return this.doRequest(`/${threadId}/comments`, \"POST\", rest);\n };\n\n public updateComment = (options: {\n comment: {\n body: CommentBody;\n metadata?: any;\n };\n threadId: string;\n commentId: string;\n }) => {\n const { threadId, commentId, ...rest } = options;\n return this.doRequest(`/${threadId}/comments/${commentId}`, \"PUT\", rest);\n };\n\n public deleteComment = (options: {\n threadId: string;\n commentId: string;\n softDelete?: boolean;\n }) => {\n const { threadId, commentId, ...rest } = options;\n return this.doRequest(\n `/${threadId}/comments/${commentId}?soft=${!!rest.softDelete}`,\n \"DELETE\",\n );\n };\n\n public deleteThread = (options: { threadId: string }) => {\n return this.doRequest(`/${options.threadId}`, \"DELETE\");\n };\n\n public resolveThread = (options: { threadId: string }) => {\n return this.doRequest(`/${options.threadId}/resolve`, \"POST\");\n };\n\n public unresolveThread = (options: { threadId: string }) => {\n return this.doRequest(`/${options.threadId}/unresolve`, \"POST\");\n };\n\n public addReaction = (options: {\n threadId: string;\n commentId: string;\n emoji: string;\n }) => {\n const { threadId, commentId, ...rest } = options;\n return this.doRequest(\n `/${threadId}/comments/${commentId}/reactions`,\n \"POST\",\n rest,\n );\n };\n\n public deleteReaction = (options: {\n threadId: string;\n commentId: string;\n emoji: string;\n }) => {\n return this.doRequest(\n `/${options.threadId}/comments/${options.commentId}/reactions/${options.emoji}`,\n \"DELETE\",\n );\n };\n}\n","import { uuidv4 } from \"lib0/random\";\nimport * as Y from \"@y/y\";\nimport type {\n CommentBody,\n CommentData,\n ThreadData,\n} from \"../../comments/types.js\";\nimport type { ThreadStoreAuth } from \"../../comments/threadstore/ThreadStoreAuth.js\";\nimport { YjsThreadStoreBase } from \"./YjsThreadStoreBase.js\";\nimport {\n commentToYType,\n threadToYType,\n yTypeToComment,\n yTypeToThread,\n} from \"./yjsHelpers.js\";\n\n/**\n * This is a @y/y (v14)-based implementation of the ThreadStore interface.\n *\n * It reads and writes thread / comments information directly to the underlying Yjs Document.\n *\n * @important While this is the easiest to add to your app, there are two challenges:\n * - The user needs to be able to write to the Yjs document to store the information.\n * So a user without write access to the Yjs document cannot leave any comments.\n * - Even with write access, the operations are not secure. Unless your Yjs server\n * guards against malicious operations, it's technically possible for one user to make changes to another user's comments, etc.\n * (even though these options are not visible in the UI, a malicious user can make unauthorized changes to the underlying Yjs document)\n */\nexport class YjsThreadStore extends YjsThreadStoreBase {\n constructor(\n private readonly userId: string,\n threadsYType: Y.Node,\n auth: ThreadStoreAuth,\n ) {\n super(threadsYType, auth);\n }\n\n private transact = <T, R>(\n fn: (options: T) => R,\n ): ((options: T) => Promise<R>) => {\n return async (options: T) => {\n return this.threadsYType.doc!.transact(() => {\n return fn(options);\n });\n };\n };\n\n public createThread = this.transact(\n (options: {\n initialComment: {\n body: CommentBody;\n metadata?: any;\n };\n metadata?: any;\n }) => {\n if (!this.auth.canCreateThread()) {\n throw new Error(\"Not authorized\");\n }\n\n const date = new Date();\n\n const comment: CommentData = {\n type: \"comment\",\n id: uuidv4(),\n userId: this.userId,\n createdAt: date,\n updatedAt: date,\n reactions: [],\n metadata: options.initialComment.metadata,\n body: options.initialComment.body,\n };\n\n const thread: ThreadData = {\n type: \"thread\",\n id: uuidv4(),\n createdAt: date,\n updatedAt: date,\n comments: [comment],\n resolved: false,\n metadata: options.metadata,\n };\n\n this.threadsYType.setAttr(thread.id, threadToYType(thread));\n\n return thread;\n },\n );\n\n // YjsThreadStore does not support addThreadToDocument\n public addThreadToDocument = undefined;\n\n public addComment = this.transact(\n (options: {\n comment: {\n body: CommentBody;\n metadata?: any;\n };\n threadId: string;\n }) => {\n const yThread = this.threadsYType.getAttr(options.threadId) as\n | Y.Node\n | undefined;\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n if (!this.auth.canAddComment(yTypeToThread(yThread))) {\n throw new Error(\"Not authorized\");\n }\n\n const date = new Date();\n const comment: CommentData = {\n type: \"comment\",\n id: uuidv4(),\n userId: this.userId,\n createdAt: date,\n updatedAt: date,\n deletedAt: undefined,\n reactions: [],\n metadata: options.comment.metadata,\n body: options.comment.body,\n };\n\n (yThread.getAttr(\"comments\") as Y.Node).push([commentToYType(comment)]);\n\n yThread.setAttr(\"updatedAt\", new Date().getTime());\n return comment;\n },\n );\n\n public updateComment = this.transact(\n (options: {\n comment: {\n body: CommentBody;\n metadata?: any;\n };\n threadId: string;\n commentId: string;\n }) => {\n const yThread = this.threadsYType.getAttr(options.threadId) as\n | Y.Node\n | undefined;\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n const commentsType = yThread.getAttr(\"comments\") as Y.Node;\n const yCommentIndex = yTypeFindIndex(\n commentsType,\n (comment) => (comment as Y.Node).getAttr(\"id\") === options.commentId,\n );\n\n if (yCommentIndex === -1) {\n throw new Error(\"Comment not found\");\n }\n\n const yComment = commentsType.get(yCommentIndex) as Y.Node;\n\n if (!this.auth.canUpdateComment(yTypeToComment(yComment))) {\n throw new Error(\"Not authorized\");\n }\n\n yComment.setAttr(\"body\", options.comment.body);\n yComment.setAttr(\"updatedAt\", new Date().getTime());\n yComment.setAttr(\"metadata\", options.comment.metadata);\n },\n );\n\n public deleteComment = this.transact(\n (options: {\n threadId: string;\n commentId: string;\n softDelete?: boolean;\n }) => {\n const yThread = this.threadsYType.getAttr(options.threadId) as\n | Y.Node\n | undefined;\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n const commentsType = yThread.getAttr(\"comments\") as Y.Node;\n const yCommentIndex = yTypeFindIndex(\n commentsType,\n (comment) => (comment as Y.Node).getAttr(\"id\") === options.commentId,\n );\n\n if (yCommentIndex === -1) {\n throw new Error(\"Comment not found\");\n }\n\n const yComment = commentsType.get(yCommentIndex) as Y.Node;\n\n if (!this.auth.canDeleteComment(yTypeToComment(yComment))) {\n throw new Error(\"Not authorized\");\n }\n\n if (yComment.getAttr(\"deletedAt\")) {\n throw new Error(\"Comment already deleted\");\n }\n\n if (options.softDelete) {\n yComment.setAttr(\"deletedAt\", new Date().getTime());\n yComment.setAttr(\"body\", undefined);\n } else {\n commentsType.delete(yCommentIndex);\n }\n\n if (\n commentsType\n .toArray()\n .every((comment) => (comment as Y.Node).getAttr(\"deletedAt\"))\n ) {\n // all comments deleted\n if (options.softDelete) {\n yThread.setAttr(\"deletedAt\", new Date().getTime());\n } else {\n this.threadsYType.deleteAttr(options.threadId);\n }\n }\n\n yThread.setAttr(\"updatedAt\", new Date().getTime());\n },\n );\n\n public deleteThread = this.transact((options: { threadId: string }) => {\n if (\n !this.auth.canDeleteThread(\n yTypeToThread(this.threadsYType.getAttr(options.threadId) as Y.Node),\n )\n ) {\n throw new Error(\"Not authorized\");\n }\n\n this.threadsYType.deleteAttr(options.threadId);\n });\n\n public resolveThread = this.transact((options: { threadId: string }) => {\n const yThread = this.threadsYType.getAttr(options.threadId) as\n | Y.Node\n | undefined;\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n if (!this.auth.canResolveThread(yTypeToThread(yThread))) {\n throw new Error(\"Not authorized\");\n }\n\n yThread.setAttr(\"resolved\", true);\n yThread.setAttr(\"resolvedUpdatedAt\", new Date().getTime());\n yThread.setAttr(\"resolvedBy\", this.userId);\n });\n\n public unresolveThread = this.transact((options: { threadId: string }) => {\n const yThread = this.threadsYType.getAttr(options.threadId) as\n | Y.Node\n | undefined;\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n if (!this.auth.canUnresolveThread(yTypeToThread(yThread))) {\n throw new Error(\"Not authorized\");\n }\n\n yThread.setAttr(\"resolved\", false);\n yThread.setAttr(\"resolvedUpdatedAt\", new Date().getTime());\n });\n\n public addReaction = this.transact(\n (options: { threadId: string; commentId: string; emoji: string }) => {\n const yThread = this.threadsYType.getAttr(options.threadId) as\n | Y.Node\n | undefined;\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n const commentsType = yThread.getAttr(\"comments\") as Y.Node;\n const yCommentIndex = yTypeFindIndex(\n commentsType,\n (comment) => (comment as Y.Node).getAttr(\"id\") === options.commentId,\n );\n\n if (yCommentIndex === -1) {\n throw new Error(\"Comment not found\");\n }\n\n const yComment = commentsType.get(yCommentIndex) as Y.Node;\n\n if (!this.auth.canAddReaction(yTypeToComment(yComment), options.emoji)) {\n throw new Error(\"Not authorized\");\n }\n\n const date = new Date();\n\n const key = `${this.userId}-${options.emoji}`;\n\n const reactionsByUser = yComment.getAttr(\"reactionsByUser\") as Y.Node;\n\n if (reactionsByUser.hasAttr(key)) {\n // already exists\n return;\n } else {\n const reaction = new Y.Node();\n reaction.setAttr(\"emoji\", options.emoji);\n reaction.setAttr(\"createdAt\", date.getTime());\n reaction.setAttr(\"userId\", this.userId);\n reactionsByUser.setAttr(key, reaction);\n }\n },\n );\n\n public deleteReaction = this.transact(\n (options: { threadId: string; commentId: string; emoji: string }) => {\n const yThread = this.threadsYType.getAttr(options.threadId) as\n | Y.Node\n | undefined;\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n const commentsType = yThread.getAttr(\"comments\") as Y.Node;\n const yCommentIndex = yTypeFindIndex(\n commentsType,\n (comment) => (comment as Y.Node).getAttr(\"id\") === options.commentId,\n );\n\n if (yCommentIndex === -1) {\n throw new Error(\"Comment not found\");\n }\n\n const yComment = commentsType.get(yCommentIndex) as Y.Node;\n\n if (\n !this.auth.canDeleteReaction(yTypeToComment(yComment), options.emoji)\n ) {\n throw new Error(\"Not authorized\");\n }\n\n const key = `${this.userId}-${options.emoji}`;\n\n const reactionsByUser = yComment.getAttr(\"reactionsByUser\") as Y.Node;\n\n reactionsByUser.deleteAttr(key);\n },\n );\n}\n\nfunction yTypeFindIndex(yType: Y.Node, predicate: (item: any) => boolean) {\n for (let i = 0; i < yType.length; i++) {\n if (predicate(yType.get(i))) {\n return i;\n }\n }\n return -1;\n}\n","import * as Y from \"@y/y\";\n\nimport { findTypeInOtherYdoc } from \"../utils.js\";\n\n/** Serialize the live fragment as a V2 update. */\nexport function serializeFragment(fragment: Y.Node): Uint8Array {\n return Y.encodeStateAsUpdateV2(fragment.doc!);\n}\n\nexport type DecodedFragment = {\n doc: Y.Doc;\n fragment: Y.Node;\n};\n\n/** Materialize a stored update into a throwaway doc and resolve `fragment` inside it. */\nexport function decodeFragmentUpdate(\n fragment: Y.Node,\n content: Uint8Array,\n opts?: { suggestionDoc?: boolean },\n): DecodedFragment {\n const doc = new Y.Doc(\n opts?.suggestionDoc ? { isSuggestionDoc: true } : undefined,\n );\n try {\n Y.applyUpdateV2(doc, content);\n return { doc, fragment: findTypeInOtherYdoc(fragment, doc) };\n } catch (error) {\n // A failed decode must not leak the throwaway doc.\n doc.destroy();\n throw error;\n }\n}\n\n/** Release a decoded throwaway doc. */\nexport function destroyDecodedFragment(\n decoded: DecodedFragment | undefined,\n): void {\n decoded?.doc.destroy();\n}\n","import { configureYProsemirror } from \"@y/prosemirror\";\nimport * as Y from \"@y/y\";\n\nimport type { BlockNoteEditor } from \"../../editor/BlockNoteEditor.js\";\nimport { findTypeInOtherYdoc } from \"../utils.js\";\nimport { blockMatchNodes } from \"./blockMatchNodes.js\";\nimport {\n decodeFragmentUpdate,\n destroyDecodedFragment,\n} from \"./snapshotCodec.js\";\n\n/** Whether the item with this id was already in `baseline`. */\nfunction inBaseline(baseline: Y.Doc, id: Y.ID): boolean {\n const last = baseline.store.clients.get(id.client)?.at(-1);\n return last !== undefined && id.clock < last.id.clock + last.length;\n}\n\n/**\n * The attributions of what changed `block`'s structure since `baseline`: its\n * content nodes and child groups that are new, or deleted, since then. Its\n * other content (e.g. text typed in it) doesn't make the change.\n */\nfunction structuralAttributions(\n block: Y.Node,\n baseline: Y.Doc,\n attributions: Y.ContentMap,\n): { inserted: Y.ContentAttribute<any>[]; deleted: Y.ContentAttribute<any>[] } {\n const inserted = new Map<string, Y.ContentAttribute<any>>();\n const deleted = new Map<string, Y.ContentAttribute<any>>();\n for (let item = block._start; item !== null; item = item.right) {\n const isNew = !inBaseline(baseline, item.id);\n if (!isNew && !item.deleted) {\n continue;\n }\n const [found, map] = isNew\n ? [inserted, attributions.inserts]\n : [deleted, attributions.deletes];\n for (const range of map.slice(item.id.client, item.id.clock, item.length)) {\n for (const attr of range.attrs ?? []) {\n found.set(`${attr.name}:${String(attr.val)}`, attr);\n }\n }\n }\n return { inserted: [...inserted.values()], deleted: [...deleted.values()] };\n}\n\n/**\n * The units of a node's live content, in order: one per character or embed,\n * and one per child node.\n */\nfunction liveUnits(node: Y.Node): Array<{ id: Y.ID; node?: Y.Node }> {\n const units: Array<{ id: Y.ID; node?: Y.Node }> = [];\n for (let item = node._start; item !== null; item = item.right) {\n if (item.deleted) {\n continue;\n }\n if (item.content instanceof Y.ContentType) {\n units.push({ id: item.id, node: item.content.type });\n continue;\n }\n for (let i = 0; i < item.length; i++) {\n units.push({ id: Y.createID(item.id.client, item.id.clock + i) });\n }\n }\n return units;\n}\n\n/**\n * Pair each unit and attribute of `original` with the same one in `copy`, its\n * clone. Returns false if they don't line up, which a clone always should.\n */\nfunction pairClone(\n original: Y.Node,\n copy: Y.Node,\n pairs: Array<[Y.ID, Y.ID]>,\n): boolean {\n for (const [key, item] of original._map) {\n const cloned = copy._map.get(key);\n if (!item.deleted) {\n if (!cloned) {\n return false;\n }\n pairs.push([item.id, cloned.id]);\n }\n }\n const a = liveUnits(original);\n const b = liveUnits(copy);\n if (a.length !== b.length) {\n return false;\n }\n return a.every((unit, i) => {\n const other = b[i];\n pairs.push([unit.id, other.id]);\n return unit.node && other.node\n ? pairClone(unit.node, other.node, pairs)\n : !unit.node && !other.node;\n });\n}\n\n/**\n * Throws when something syncs `doc` (a provider or a persistence layer listens\n * to its updates). A decoded snapshot is written to (see\n * {@link splitChangedBlocks}), and that write must never reach a stored\n * document.\n */\nexport function assertUnsyncedDoc(doc: Y.Doc): void {\n // lib0's observable keeps its listeners in `_observers`.\n const observers = (doc as unknown as { _observers: Map<string, unknown> })\n ._observers;\n if (observers.has(\"update\") || observers.has(\"updateV2\")) {\n throw new Error(\n \"DANGER! Refusing to write to a doc that something syncs. splitChangedBlocks should only write to throwaway copies.\",\n );\n }\n}\n\n/** Attributions as the other kind: `insert`/`insertAt` as `delete`/`deleteAt`. */\nfunction asKind(\n attrs: Y.ContentAttribute<any>[],\n kind: \"insert\" | \"delete\",\n): Y.ContentAttribute<any>[] {\n return attrs.map((attr) =>\n Y.createContentAttribute(\n attr.name.replace(/^(insert|delete)/, kind),\n attr.val,\n ),\n );\n}\n\n/**\n * Replace each block that changed structurally since `baseline` with a fresh\n * copy, where \"structurally\" is what `blockMatchNodes` treats as a different\n * block (e.g. a type change). The old collaboration binding stored such changes\n * inside the same container, which a diff renders as schema-invalid content\n * that is then dropped. A fresh container diffs as a deleted block next to an\n * inserted one, as the current binding stores it. The copy and the deletion\n * are credited to whoever changed the block's structure (see\n * {@link structuralAttributions}).\n */\nfunction splitChangedBlocks(\n node: Y.Node,\n baseline: Y.Doc,\n attributions: Y.ContentMap | undefined,\n added: Y.ContentMap,\n): void {\n // The split is a real write: it must stay in the decoded snapshot.\n assertUnsyncedDoc(node.doc!);\n for (let index = 0; index < node.length; index++) {\n const child = node.get(index);\n if (!(child instanceof Y.Node)) {\n continue;\n }\n if (child.name === \"blockContainer\" && child._item) {\n // A block created after the baseline has no previous version.\n const before = inBaseline(baseline, child._item.id)\n ? findTypeInOtherYdoc(child, baseline)\n : undefined;\n if (\n before &&\n !blockMatchNodes(before.toDeltaDeep(), child.toDeltaDeep())\n ) {\n const { inserted, deleted } = attributions\n ? structuralAttributions(child, baseline, attributions)\n : { inserted: [], deleted: [] };\n const doc = child.doc!;\n // A change that only inserted (or only deleted) still credits both\n // sides of the split, under that side's attribution kind.\n const insertedAs = inserted.length\n ? inserted\n : asKind(deleted, \"insert\");\n const deletedAs = deleted.length ? deleted : asKind(inserted, \"delete\");\n // Copied content added after the baseline keeps its own author (e.g.\n // text typed after the structural change).\n const own: Y.IdMap<any> = Y.createIdMap();\n const owned = Y.createIdSet();\n function record(tr: Y.Transaction) {\n if (insertedAs.length) {\n Y.insertIntoIdMap(\n added.inserts,\n Y.mergeIdMaps([\n Y.diffIdMap(\n Y.createIdMapFromIdSet(tr.insertSet, insertedAs),\n owned,\n ),\n own,\n ]),\n );\n Y.insertIntoIdMap(\n added.deletes,\n Y.createIdMapFromIdSet(tr.deleteSet, deletedAs),\n );\n }\n }\n doc.on(\"beforeObserverCalls\", record);\n try {\n doc.transact(() => {\n const copy = child.clone();\n node.insert(index + 1, [copy]);\n // Paired while the original is still live.\n const pairs: Array<[Y.ID, Y.ID]> = [];\n if (attributions && pairClone(child, copy, pairs)) {\n for (const [original, cloned] of pairs) {\n const attrs = inBaseline(baseline, original)\n ? undefined\n : attributions.inserts.slice(\n original.client,\n original.clock,\n 1,\n )[0]?.attrs;\n if (attrs) {\n const ids = Y.createIdSet();\n ids.add(cloned.client, cloned.clock, 1);\n owned.add(cloned.client, cloned.clock, 1);\n Y.insertIntoIdMap(own, Y.createIdMapFromIdSet(ids, attrs));\n }\n }\n }\n node.delete(index);\n });\n } finally {\n doc.off(\"beforeObserverCalls\", record);\n }\n continue;\n }\n }\n splitChangedBlocks(child, baseline, attributions, added);\n }\n}\n\n/**\n * Decode a snapshot, diff it against a baseline if given, and render it.\n *\n * Snapshots are decoded into throwaway documents, so pointing the binding at\n * one is already an isolated state: the live fragment stops receiving view\n * updates, and nothing typed into the preview reaches the live document.\n * {@link configureYProsemirror} rebuilds the binding against the decoded\n * fragment through the same `customCompare`/attribution pipeline the live\n * binding uses; passing the `renderer` keeps the attribution tooltips\n * (\"who/when\") working.\n */\nexport function showSnapshotPreview(\n editor: BlockNoteEditor<any, any, any>,\n fragment: Y.Node,\n snapshotContent: Uint8Array,\n compareToContent?: Uint8Array,\n attributions?: Y.ContentMap,\n): void {\n const baseline = compareToContent\n ? decodeFragmentUpdate(fragment, compareToContent, {\n suggestionDoc: true,\n })\n : undefined;\n try {\n const snapshot = decodeFragmentUpdate(fragment, snapshotContent);\n try {\n let renderAttributions = attributions;\n if (baseline) {\n const added = Y.createContentMap();\n splitChangedBlocks(\n snapshot.fragment,\n baseline.doc,\n attributions,\n added,\n );\n if (attributions) {\n renderAttributions = Y.createContentMap(\n Y.mergeIdMaps([attributions.inserts, added.inserts]),\n Y.mergeIdMaps([attributions.deletes, added.deletes]),\n );\n }\n }\n editor.exec(\n configureYProsemirror({\n ytype: snapshot.fragment,\n renderer: baseline\n ? Y.createDiffRenderer(\n baseline.doc,\n snapshot.doc,\n renderAttributions\n ? { attributions: renderAttributions }\n : undefined,\n )\n : undefined,\n }),\n );\n } finally {\n destroyDecodedFragment(snapshot);\n }\n } finally {\n destroyDecodedFragment(baseline);\n }\n}\n","import { pauseSync, ySyncPluginKey } from \"@y/prosemirror\";\nimport * as Y from \"@y/y\";\nimport type { BlockNoteEditor } from \"../../editor/BlockNoteEditor.js\";\nimport type { VersionViewAdapter } from \"../../extensions/Versioning/types.js\";\nimport type {\n BlockSchema,\n InlineContentSchema,\n StyleSchema,\n} from \"../../schema/index.js\";\nimport { ForkYDocExtension } from \"./ForkYDoc.js\";\nimport { serializeFragment } from \"./snapshotCodec.js\";\nimport { showSnapshotPreview } from \"./snapshotPreview.js\";\n\n/** Uses the existing fork primitive, but exposes only an owned view. */\nexport function createYVersionView<\n BSchema extends BlockSchema,\n ISchema extends InlineContentSchema,\n SSchema extends StyleSchema,\n>(\n editor: BlockNoteEditor<BSchema, ISchema, SSchema>,\n fragment: Y.Node,\n): VersionViewAdapter<Uint8Array, Y.ContentMap> {\n return {\n supportsComparison: true,\n open() {\n const fork = editor.getExtension(ForkYDocExtension);\n const binding = ySyncPluginKey.getState(editor.prosemirrorState);\n if (\n !fork ||\n fork.store.state.isForked ||\n binding?.renderer ||\n binding?.ytype !== fragment\n ) {\n throw new Error(\n \"Versioning requires an active plain live binding and an available fork\",\n );\n }\n const current = {\n content: serializeFragment(fragment),\n capturedAt: Date.now(),\n };\n try {\n fork.fork();\n editor.exec((state, dispatch) => pauseSync(state, dispatch ?? null));\n } catch (error) {\n fork.merge({ keepChanges: false });\n throw error;\n }\n let closed = false;\n return {\n current,\n show({ content, comparison }) {\n if (closed) {\n throw new Error(\"Version view is closed\");\n }\n showSnapshotPreview(\n editor,\n fragment,\n content,\n comparison?.content,\n comparison?.attributions,\n );\n },\n close() {\n if (closed) {\n return;\n }\n fork.merge({ keepChanges: false });\n closed = true;\n },\n };\n },\n };\n}\n","import { decodeAny, encodeAny } from \"lib0/buffer\";\nimport type { VersionResult } from \"../../extensions/Versioning/types.js\";\n\nexport interface YHubClientOptions {\n /** API base URL, including the API prefix, without a trailing slash. */\n baseUrl: string;\n /** Organisation identifier. */\n org: string;\n /** Document identifier within the organisation. */\n docId: string;\n /** Headers included in every request, e.g. authentication tokens. */\n headers?: Record<string, string>;\n /** Authentication query parameters included in every request. The open YHub demo uses `userid`. */\n queryParams?: YHubQueryParams;\n /** Bounds each request, including reading the response body. Defaults to 30 seconds. */\n timeoutMs?: number;\n}\n\ninterface YHubActivityWireEntry<Metadata> {\n /** Start of the change window, in Unix milliseconds. */\n from: number;\n /** End of the change window, in Unix milliseconds. */\n to: number;\n /** Scalar when grouping by user; an author list when grouping across users. */\n by?: string | Array<string | null> | null;\n customAttributions?: Array<{ k: string; v: string }>;\n version?: YHubVersion<Metadata>;\n}\n\nexport interface YHubVersion<Metadata = unknown> {\n type: \"version:v1\";\n t: number;\n name: string;\n custom: Metadata | null | undefined;\n updatedAt: number;\n}\n\ntype YHubVersionCreate<Metadata> = Pick<\n YHubVersion<Metadata>,\n \"type\" | \"t\" | \"name\"\n> & {\n custom?: Metadata | null;\n};\n\ntype YHubVersionUpdate<Metadata> = Pick<\n YHubVersion<Metadata>,\n \"type\" | \"t\" | \"name\" | \"custom\" | \"updatedAt\"\n>;\n\n/** Activity with wire-format authors and attribution pairs normalized. */\nexport interface YHubActivityEntry<Metadata = unknown> {\n from: number;\n to: number;\n by: string[];\n customAttributions: Record<string, string>;\n version?: YHubVersion<Metadata>;\n}\n\nexport interface YHubChangeset {\n /** Encoded document state at the requested timestamp. */\n ydoc?: Uint8Array;\n /** Encoded content map, when requested. */\n attributions?: Uint8Array;\n}\n\nexport interface YHubDocument {\n doc: Uint8Array;\n}\n\n/** Query values are serialized without adding defaults. */\nexport type YHubQueryParams = Record<\n string,\n string | number | boolean | undefined\n>;\n\nexport interface YHubRollbackParams {\n /** Inclusive start of the rollback window, in Unix milliseconds. */\n from: number;\n /** Encoded content IDs to roll back. */\n contentIds: Uint8Array;\n}\n\n/** Document-scoped REST operations; binary Yjs payloads remain encoded. */\nexport class YHubClient<Metadata = unknown> {\n private readonly baseUrl: string;\n private readonly documentPath: string;\n private readonly headers: Record<string, string>;\n private readonly queryParams: YHubQueryParams;\n private readonly timeoutMs: number;\n\n constructor({\n baseUrl,\n org,\n docId,\n headers = {},\n queryParams = {},\n timeoutMs = 30_000,\n }: YHubClientOptions) {\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n throw new Error(\"YHub timeout must be a positive finite number\");\n }\n this.baseUrl = baseUrl;\n this.documentPath = `${encodeURIComponent(org)}/${encodeURIComponent(docId)}`;\n this.headers = headers;\n this.queryParams = queryParams;\n this.timeoutMs = timeoutMs;\n }\n\n private async request<Value>(\n endpoint: string,\n decode: (data: Uint8Array) => Value,\n params?: YHubQueryParams,\n init?: RequestInit,\n ): Promise<VersionResult<Value>> {\n const query = new URLSearchParams(\n Object.entries({ ...params, ...this.queryParams })\n .filter(([, value]) => value !== undefined)\n .map(([key, value]) => [key, String(value)]),\n );\n const url = `${this.baseUrl}/${endpoint}/v1/${this.documentPath}${query.size ? `?${query}` : \"\"}`;\n const parsedUrl = new URL(url);\n if (parsedUrl.protocol !== \"https:\" && parsedUrl.protocol !== \"http:\") {\n throw new Error(\"YHub requires an HTTP or HTTPS URL\");\n }\n const headers = new Headers(this.headers);\n const timeout = AbortSignal.timeout(this.timeoutMs);\n const signal = init?.signal\n ? AbortSignal.any([init.signal, timeout])\n : timeout;\n let data: ArrayBuffer;\n try {\n const response = await fetch(url, { ...init, signal, headers });\n if (!response.ok) {\n return {\n ok: false,\n error:\n response.status === 401 || response.status === 403\n ? { type: \"forbidden\" }\n : response.status === 409 || response.status === 412\n ? { type: \"conflict\" }\n : response.status === 404\n ? { type: \"not-found\" }\n : { type: \"server\", status: response.status },\n };\n }\n data = await response.arrayBuffer();\n } catch (error) {\n if (init?.signal?.aborted) {\n throw error;\n }\n if (timeout.aborted) {\n return {\n ok: false,\n error: {\n type: \"timeout\",\n outcome: init?.method ? \"unknown\" : \"unchanged\",\n },\n };\n }\n // Fetch reports transport failures as TypeError. URL/configuration errors\n // are prevented by constructing and validating the URL before this boundary.\n if (error instanceof TypeError) {\n return { ok: false, error: { type: \"network\" } };\n }\n throw error;\n }\n // Decode outside the transport catch: malformed responses are unexpected errors.\n return { ok: true, value: decode(new Uint8Array(data)) };\n }\n\n async getVersion(\n t: number,\n ): Promise<VersionResult<YHubVersion<Metadata> | undefined>> {\n return this.request(\n \"version\",\n (data) => {\n const { versions } = decodeAny(data) as {\n versions: YHubVersion<Metadata>[];\n };\n return versions[0];\n },\n { from: t, to: t },\n );\n }\n\n async createVersion(\n t: number,\n name: string,\n custom?: Metadata | null,\n ): Promise<VersionResult<YHubVersion<Metadata>>> {\n const body = {\n type: \"version:v1\",\n t,\n name,\n ...(custom === undefined ? {} : { custom }),\n } satisfies YHubVersionCreate<Metadata>;\n return this.request(\n \"version\",\n (data) => decodeAny(data) as YHubVersion<Metadata>,\n undefined,\n { method: \"POST\", body: encodeAny(body) as BufferSource },\n );\n }\n\n async updateVersion(\n version: YHubVersion<Metadata>,\n name: string,\n custom: Metadata | null | undefined = version.custom,\n ): Promise<VersionResult<YHubVersion<Metadata>>> {\n const body = {\n type: \"version:v1\",\n t: version.t,\n updatedAt: version.updatedAt,\n name,\n custom,\n } satisfies YHubVersionUpdate<Metadata>;\n return this.request(\n \"version\",\n (data) => decodeAny(data) as YHubVersion<Metadata>,\n undefined,\n { method: \"PATCH\", body: encodeAny(body) as BufferSource },\n );\n }\n\n async deleteVersion(\n version: YHubVersion<Metadata>,\n ): Promise<VersionResult<void>> {\n return this.request(\n \"version\",\n () => undefined,\n {\n t: version.t,\n updatedAt: version.updatedAt,\n },\n { method: \"DELETE\" },\n );\n }\n\n async getActivity(\n params?: YHubQueryParams,\n signal?: AbortSignal,\n ): Promise<VersionResult<YHubActivityEntry<Metadata>[]>> {\n return this.request(\n \"activity\",\n (data) => {\n const { activity } = decodeAny(data) as {\n activity: YHubActivityWireEntry<Metadata>[];\n };\n return activity.map((entry) => ({\n ...entry,\n by: (Array.isArray(entry.by)\n ? entry.by\n : (entry.by?.split(\",\") ?? [])\n )\n .filter((id): id is string => id !== null)\n .map((id) => id.trim())\n .filter(Boolean),\n customAttributions: Object.fromEntries(\n entry.customAttributions?.map(({ k, v }) => [k, v]) ?? [],\n ),\n }));\n },\n params,\n { signal },\n );\n }\n\n async getChangeset(\n params?: YHubQueryParams,\n signal?: AbortSignal,\n ): Promise<VersionResult<YHubChangeset>> {\n return this.request(\n \"changeset\",\n (data) => decodeAny(data) as YHubChangeset,\n params,\n { signal },\n );\n }\n\n async getDocument(\n params?: YHubQueryParams,\n ): Promise<VersionResult<Uint8Array>> {\n return this.request(\n \"ydoc\",\n (data) => {\n const { doc } = decodeAny(data) as Partial<YHubDocument>;\n if (!doc) {\n throw new Error(\"YHub returned no document state.\");\n }\n return doc;\n },\n params,\n );\n }\n\n async getContent(\n to: number,\n signal?: AbortSignal,\n ): Promise<VersionResult<Uint8Array>> {\n return this.request(\n \"changeset\",\n (data) => {\n const { ydoc } = decodeAny(data) as YHubChangeset;\n if (!ydoc) {\n throw new Error(\n `YHub returned no document state at timestamp ${to}.`,\n );\n }\n return ydoc;\n },\n { ydoc: true, to },\n { signal },\n );\n }\n\n async getAttributions(\n from: number,\n to?: number,\n signal?: AbortSignal,\n ): Promise<VersionResult<Uint8Array>> {\n return this.request(\n \"changeset\",\n (data) => {\n const { attributions } = decodeAny(data) as YHubChangeset;\n if (!attributions) {\n throw new Error(\"YHub returned no attributions.\");\n }\n return attributions;\n },\n {\n from,\n to,\n attributions: true,\n },\n { signal },\n );\n }\n\n async rollback(params: YHubRollbackParams): Promise<VersionResult<void>> {\n return this.request(\"rollback\", () => undefined, undefined, {\n method: \"POST\",\n body: encodeAny(params) as BufferSource,\n });\n }\n}\n","import * as Y from \"@y/y\";\nimport type {\n VersionSnapshot,\n VersionStorage,\n} from \"../../extensions/Versioning/types.js\";\nimport { collectFragmentIds, findTypeInOtherYdoc } from \"../utils.js\";\nimport { CollaborationExtension } from \"../extensions/index.js\";\nimport { createYVersionView } from \"../extensions/Versioning.js\";\nimport { createVersioningExtension } from \"../../extensions/Versioning/Versioning.js\";\nimport {\n YHubClient,\n type YHubClientOptions,\n type YHubQueryParams,\n} from \"./yhubClient.js\";\n\nexport interface YHubVersionStorageOptions extends YHubClientOptions {\n /** Activity grouping and filters. `limit` is the page size, defaulting to 50. History is newest first. */\n activityParams?: YHubQueryParams;\n}\n\ntype YHubStorage = VersionStorage<Uint8Array, Y.ContentMap> &\n Required<\n Pick<\n VersionStorage<Uint8Array, Y.ContentMap>,\n \"getAttributions\" | \"create\" | \"restore\" | \"rename\" | \"remove\"\n >\n >;\n\n/** Configure Y14 history independently of collaboration installation. */\nexport function YVersioningExtension(options: {\n storage: VersionStorage<Uint8Array, Y.ContentMap>;\n scrollToFirstChange?: boolean;\n}) {\n return createVersioningExtension((editor) => {\n const collaboration = editor.getExtension(CollaborationExtension);\n if (!collaboration) {\n throw new Error(\"Y14 versioning requires Y14 collaboration\");\n }\n return {\n adapter: createYVersionView(editor, collaboration.fragment),\n storage: options.storage,\n resolveUsers: collaboration.userStore,\n scrollToFirstChange: options.scrollToFirstChange,\n };\n })();\n}\n\n/** Install YHub history for the editor's live collaboration document. */\nexport function YHubVersioningExtension(\n options: YHubVersionStorageOptions & { scrollToFirstChange?: boolean },\n) {\n return createVersioningExtension((editor) => {\n const collaboration = editor.getExtension(CollaborationExtension);\n if (!collaboration) {\n throw new Error(\"Y14 versioning requires Y14 collaboration\");\n }\n return {\n adapter: createYVersionView(editor, collaboration.fragment),\n storage: createYHubVersionStorage({\n ...options,\n fragment: collaboration.fragment,\n beforeRestoreName: editor.dictionary.versioning.before_restore,\n }),\n resolveUsers: collaboration.userStore,\n scrollToFirstChange: options.scrollToFirstChange,\n };\n })();\n}\n\n/** Continuous history for a live fragment, with no editor dependency. */\nexport function createYHubVersionStorage(\n options: YHubVersionStorageOptions & {\n fragment: Y.Node;\n beforeRestoreName: string;\n },\n): YHubStorage {\n const { fragment, beforeRestoreName } = options;\n const client = new YHubClient(options);\n function timestamps(id: string) {\n const parts = id.split(\"-\");\n const from = Number(parts[0]);\n const to = Number(parts[1]);\n if (\n parts.length !== 2 ||\n parts.some((part) => part.length === 0) ||\n !Number.isFinite(from) ||\n !Number.isFinite(to) ||\n from > to\n ) {\n throw new Error(\"Invalid YHub checkpoint identifier\");\n }\n return { from, to };\n }\n function getHistoryList(signal?: AbortSignal, overrides?: YHubQueryParams) {\n return client.getActivity(activityParams(overrides), signal);\n }\n function activityParams(overrides?: YHubQueryParams): YHubQueryParams {\n return {\n order: \"desc\",\n limit: 50,\n groupMaxGap: 60 * 60 * 1000,\n groupMaxDuration: 12 * 60 * 60 * 1000,\n groupByUser: false,\n customAttributions: true,\n ...options.activityParams,\n ...overrides,\n versions: true,\n };\n }\n return {\n showCurrentVersion: false,\n historyIncludesBeginning: true,\n async list(signal, cursor) {\n const params =\n cursor === undefined\n ? { ...activityParams(), order: \"desc\" }\n : Object.fromEntries(new URLSearchParams(cursor));\n const limit = Number(params.limit);\n if (!Number.isSafeInteger(limit) || limit <= 0) {\n throw new Error(\"YHub activity limit must be a positive integer\");\n }\n const [result, firstSnapshotResult] = await Promise.all([\n client.getActivity({ ...params, limit: limit + 1 }, signal),\n cursor === undefined\n ? client.getActivity(\n {\n from: 0,\n order: \"asc\",\n limit: 1,\n group: false,\n versions: true,\n customAttributions: true,\n },\n signal,\n )\n : undefined,\n ]);\n if (!result.ok) {\n return result;\n }\n if (firstSnapshotResult && !firstSnapshotResult.ok) {\n return firstSnapshotResult;\n }\n const entries = result.value.slice(0, limit);\n const oldest = entries.at(-1);\n let nextCursor: string | undefined;\n if (result.value.length > limit && oldest && oldest.from > 0) {\n const query = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined) {\n query.set(key, String(value));\n }\n }\n query.set(\"to\", String(oldest.from - 1));\n nextCursor = query.toString();\n }\n // The pinned start of the document is not part of the page boundary. It\n // is the moment before the first edit, so it shows the empty document,\n // and comparing to it includes the first edit like any other.\n const firstSnapshot = firstSnapshotResult?.value[0];\n if (firstSnapshot) {\n const start = Math.max(0, firstSnapshot.from - 1);\n entries.push({\n ...firstSnapshot,\n from: start,\n to: start,\n version: undefined,\n });\n }\n return {\n ok: true,\n value: {\n nextCursor,\n snapshots: entries.map((entry): VersionSnapshot => {\n const custom = entry.version?.custom;\n const restoredFrom =\n custom !== null &&\n typeof custom === \"object\" &&\n \"restoredFrom\" in custom\n ? custom.restoredFrom\n : undefined;\n return {\n id: `${entry.from}-${entry.to}`,\n createdAt: entry.to,\n by: entry.by,\n name: entry.version?.name || undefined,\n metadata: custom,\n customAttributions: entry.customAttributions,\n restoredFrom:\n typeof restoredFrom === \"number\" &&\n Number.isFinite(restoredFrom)\n ? {\n id: `${entries.find((entry) => entry.to === restoredFrom)?.from ?? restoredFrom}-${restoredFrom}`,\n createdAt: restoredFrom,\n }\n : undefined,\n };\n }),\n },\n };\n },\n async getContent(id, signal) {\n // YHub includes edits at `to`.\n const result = await client.getContent(timestamps(id).to, signal);\n return result.ok\n ? { ok: true, value: Y.convertUpdateFormatV1ToV2(result.value) }\n : result;\n },\n async getAttributions(target, baselineId, _capturedAt, signal) {\n const result = await client.getAttributions(\n // The baseline already holds its edits at `to`.\n timestamps(baselineId).to + 1,\n // Use the server's current time, not the potentially skewed client clock.\n target.type === \"current\" ? undefined : timestamps(target.id).to,\n signal,\n );\n return result.ok\n ? { ok: true, value: Y.decodeContentMap(result.value) }\n : result;\n },\n async create(content, name) {\n const history = await getHistoryList(undefined, { limit: 1 });\n if (!history.ok) {\n return history;\n }\n const latest = history.value[0];\n if (!latest) {\n return { ok: false, error: { type: \"conflict\" } };\n }\n const checkpoint = await client.getContent(latest.to);\n if (!checkpoint.ok) {\n return checkpoint;\n }\n const frozen = new Y.Doc();\n const stored = new Y.Doc();\n try {\n Y.applyUpdateV2(frozen, content);\n Y.applyUpdate(stored, checkpoint.value);\n if (\n JSON.stringify(findTypeInOtherYdoc(fragment, frozen).toJSON()) !==\n JSON.stringify(findTypeInOtherYdoc(fragment, stored).toJSON())\n ) {\n return { ok: false, error: { type: \"conflict\" } };\n }\n } finally {\n frozen.destroy();\n stored.destroy();\n }\n const existing = await client.getVersion(latest.to);\n if (!existing.ok) {\n return existing;\n }\n const result = existing.value\n ? await client.updateVersion(existing.value, name ?? \"\")\n : await client.createVersion(latest.to, name ?? \"\");\n if (!result.ok) {\n return result;\n }\n const version = result.value;\n return {\n ok: true,\n value: {\n id: `${latest.from}-${version.t}`,\n createdAt: version.t,\n name: version.name || undefined,\n metadata: version.custom,\n by: latest.by,\n },\n };\n },\n async restore(id) {\n const { to } = timestamps(id);\n const [before, document] = await Promise.all([\n getHistoryList(undefined, { limit: 1 }),\n client.getDocument({ gc: false }),\n ]);\n if (!before.ok) {\n return before;\n }\n if (!document.ok) {\n return document;\n }\n const ids = collectFragmentIds(fragment, document.value);\n if (before.value[0]) {\n const existing = await client.getVersion(before.value[0].to);\n if (!existing.ok) {\n return existing;\n }\n if (!existing.value) {\n const backup = await client.createVersion(\n before.value[0].to,\n beforeRestoreName,\n );\n if (!backup.ok) {\n return backup;\n }\n }\n }\n const rollback = await client.rollback({\n from: to + 1,\n contentIds: Y.encodeContentIds({ inserts: ids, deletes: ids }),\n });\n if (!rollback.ok) {\n return rollback;\n }\n // Fetch the authoritative post-rollback update rather than assuming the\n // websocket already delivered it. Apply to the live doc, never the fork.\n const restored = await client.getDocument({ gc: false });\n if (!restored.ok) {\n return restored.error.type === \"timeout\"\n ? { ok: false, error: { type: \"timeout\", outcome: \"unknown\" } }\n : restored;\n }\n Y.applyUpdate(fragment.doc!, restored.value);\n return { ok: true, value: undefined };\n },\n async rename(id, name) {\n const { to } = timestamps(id);\n const existing = await client.getVersion(to);\n if (!existing.ok) {\n return existing;\n }\n if (!existing.value && !name) {\n return { ok: true, value: undefined };\n }\n const result = existing.value\n ? await client.updateVersion(existing.value, name ?? \"\")\n : await client.createVersion(to, name ?? \"\");\n return result.ok ? { ok: true, value: undefined } : result;\n },\n async remove(id) {\n const existing = await client.getVersion(timestamps(id).to);\n if (!existing.ok) {\n return existing;\n }\n if (!existing.value) {\n return { ok: true, value: undefined };\n }\n if (\n existing.value.custom !== null &&\n existing.value.custom !== undefined\n ) {\n const result = await client.updateVersion(existing.value, \"\");\n return result.ok ? { ok: true, value: undefined } : result;\n } else {\n return client.deleteVersion(existing.value);\n }\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AAwDA,IAAa,KACX,GACA,MAEA,MAAW,KAAA,IACP,KAAA,IACA,OAAO,KAAW,WAChB,IACA,EAAO;AAQf,SAAgB,EAAoB,GAAgC;CAClE,OAAO,EAAK,MAAM,WAAc,CAAC;AACnC;AAOA,SAAS,GAAkB,GAAwC;CACjE,IAAM,IAAmC,EAAK,MAAM,UAAa,CAAC;CAClE,OAAO,OAAO,YACZ,OAAO,QAAQ,CAAM,CAAC,CAAC,QAAQ,CAAC,OAGvB,EADL,EAAK,KAAK,OAAO,MAAM,GAAe,CAAG,EAAE,EAAE,KAAK,SAAS,GAAA,CAC/C,MAAM,GAAG,CAAC,CAAC,SAAS,CAAyB,CAC5D,CACH;AACF;AAEA,SAAgB,EAAsB,GAAwB;CAC5D,OAAO,EAAK,KAAK,SAAS,uBACt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