@blocknote/core 0.48.0 → 0.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/dist/blocknote.cjs +1 -1
  2. package/dist/blocknote.js +3 -3
  3. package/dist/{blocks-DYl7UTS4.js → blocks-CSfJen16.js} +18 -2
  4. package/dist/blocks-CSfJen16.js.map +1 -0
  5. package/dist/{blocks-BEvIOzln.cjs → blocks-_lpGWKOa.cjs} +3 -3
  6. package/dist/blocks-_lpGWKOa.cjs.map +1 -0
  7. package/dist/blocks.cjs +1 -1
  8. package/dist/blocks.js +1 -1
  9. package/dist/comments.cjs +1 -1
  10. package/dist/comments.cjs.map +1 -1
  11. package/dist/comments.js +2 -2
  12. package/dist/comments.js.map +1 -1
  13. package/dist/extensions-BfYaEv6F.cjs +2 -0
  14. package/dist/extensions-BfYaEv6F.cjs.map +1 -0
  15. package/dist/{extensions-3nf9PPhA.js → extensions-C3nguvVr.js} +240 -248
  16. package/dist/extensions-C3nguvVr.js.map +1 -0
  17. package/dist/extensions.cjs +1 -1
  18. package/dist/extensions.js +2 -2
  19. package/dist/src-ChTwrMcE.cjs +5 -0
  20. package/dist/src-ChTwrMcE.cjs.map +1 -0
  21. package/dist/{src-Hjv1f5lc.js → src-DQfz4zLM.js} +757 -373
  22. package/dist/src-DQfz4zLM.js.map +1 -0
  23. package/dist/style.css +1 -1
  24. package/dist/webpack-stats.json +1 -1
  25. package/dist/yjs.cjs +1 -1
  26. package/dist/yjs.js +1 -1
  27. package/package.json +6 -8
  28. package/src/blocks/ListItem/NumberedListItem/IndexingPlugin.test.ts +14 -1
  29. package/src/blocks/Quote/block.ts +9 -0
  30. package/src/blocks/Table/block.ts +26 -0
  31. package/src/comments/extension.ts +5 -0
  32. package/src/comments/threadstore/yjs/YjsThreadStore.test.ts +3 -2
  33. package/src/comments/threadstore/yjs/YjsThreadStore.ts +4 -4
  34. package/src/editor/BlockNoteEditor.ts +84 -5
  35. package/src/editor/editor.css +5 -0
  36. package/src/editor/managers/ExtensionManager/extensions.ts +8 -26
  37. package/src/editor/managers/StyleManager.ts +90 -10
  38. package/src/extensions/FormattingToolbar/FormattingToolbar.ts +23 -16
  39. package/src/extensions/LinkToolbar/LinkToolbar.ts +30 -75
  40. package/src/extensions/Placeholder/Placeholder.ts +2 -2
  41. package/src/extensions/tiptap-extensions/Link/helpers/autolink.ts +179 -0
  42. package/src/extensions/tiptap-extensions/Link/helpers/clickHandler.ts +82 -0
  43. package/src/extensions/tiptap-extensions/Link/helpers/linkDetector.ts +414 -0
  44. package/src/extensions/tiptap-extensions/Link/helpers/pasteHandler.ts +53 -0
  45. package/src/extensions/tiptap-extensions/Link/helpers/tlds.ts +7 -0
  46. package/src/extensions/tiptap-extensions/Link/helpers/whitespace.ts +13 -0
  47. package/src/extensions/tiptap-extensions/Link/index.ts +2 -0
  48. package/src/extensions/tiptap-extensions/Link/link.test.ts +941 -0
  49. package/src/extensions/tiptap-extensions/Link/link.ts +207 -0
  50. package/src/extensions/tiptap-extensions/UniqueID/UniqueID.ts +3 -5
  51. package/src/schema/inlineContent/types.ts +1 -1
  52. package/types/src/editor/BlockNoteEditor.d.ts +69 -3
  53. package/types/src/editor/managers/StyleManager.d.ts +22 -0
  54. package/types/src/extensions/LinkToolbar/LinkToolbar.d.ts +28 -7
  55. package/types/src/extensions/tiptap-extensions/Link/helpers/autolink.d.ts +13 -0
  56. package/types/src/extensions/tiptap-extensions/Link/helpers/clickHandler.d.ts +12 -0
  57. package/types/src/extensions/tiptap-extensions/Link/helpers/linkDetector.d.ts +32 -0
  58. package/types/src/extensions/tiptap-extensions/Link/helpers/pasteHandler.d.ts +12 -0
  59. package/types/src/extensions/tiptap-extensions/Link/helpers/tlds.d.ts +1 -0
  60. package/types/src/extensions/tiptap-extensions/Link/helpers/whitespace.d.ts +4 -0
  61. package/types/src/extensions/tiptap-extensions/Link/index.d.ts +2 -0
  62. package/types/src/extensions/tiptap-extensions/Link/link.d.ts +13 -0
  63. package/types/src/extensions/tiptap-extensions/Link/link.test.d.ts +1 -0
  64. package/types/src/schema/inlineContent/types.d.ts +1 -2
  65. package/dist/blocks-BEvIOzln.cjs.map +0 -1
  66. package/dist/blocks-DYl7UTS4.js.map +0 -1
  67. package/dist/extensions-3nf9PPhA.js.map +0 -1
  68. package/dist/extensions-D9y6evn6.cjs +0 -2
  69. package/dist/extensions-D9y6evn6.cjs.map +0 -1
  70. package/dist/src-BKJH7Jla.cjs +0 -5
  71. package/dist/src-BKJH7Jla.cjs.map +0 -1
  72. package/dist/src-Hjv1f5lc.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"comments.js","names":[],"sources":["../src/comments/mark.ts","../src/comments/userstore/UserStore.ts","../src/comments/extension.ts","../src/comments/threadstore/ThreadStoreAuth.ts","../src/comments/threadstore/DefaultThreadStoreAuth.ts","../src/comments/threadstore/ThreadStore.ts","../src/comments/threadstore/TipTapThreadStore.ts","../src/comments/threadstore/yjs/yjsHelpers.ts","../src/comments/threadstore/yjs/YjsThreadStoreBase.ts","../src/comments/threadstore/yjs/RESTYjsThreadStore.ts","../src/comments/threadstore/yjs/YjsThreadStore.ts"],"sourcesContent":["import { Mark, mergeAttributes } from \"@tiptap/core\";\n\nexport const CommentMark = Mark.create({\n name: \"comment\",\n excludes: \"\",\n inclusive: false,\n keepOnSplit: true,\n\n addAttributes() {\n // Return an object with attribute configuration\n return {\n // orphans are marks that currently don't have an active thread. It could be\n // that users have resolved the thread. Resolved threads by default are not shown in the document,\n // but we need to keep the mark (positioning) data so we can still \"revive\" it when the thread is unresolved\n // or we enter a \"comments\" view that includes resolved threads.\n orphan: {\n parseHTML: (element) => !!element.getAttribute(\"data-orphan\"),\n renderHTML: (attributes) => {\n return (attributes as { orphan: boolean }).orphan\n ? {\n \"data-orphan\": \"true\",\n }\n : {};\n },\n default: false,\n },\n threadId: {\n parseHTML: (element) => element.getAttribute(\"data-bn-thread-id\"),\n renderHTML: (attributes) => {\n return {\n \"data-bn-thread-id\": (attributes as { threadId: string }).threadId,\n };\n },\n default: \"\",\n },\n };\n },\n\n renderHTML({ HTMLAttributes }: { HTMLAttributes: Record<string, any> }) {\n return [\n \"span\",\n mergeAttributes(HTMLAttributes, {\n class: \"bn-thread-mark\",\n }),\n ];\n },\n\n parseHTML() {\n return [{ tag: \"span.bn-thread-mark\" }];\n },\n\n extendMarkSchema(extension) {\n if (extension.name === \"comment\") {\n return {\n blocknoteIgnore: true,\n };\n }\n return {};\n },\n});\n","import type { User } from \"../types.js\";\nimport { EventEmitter } from \"../../util/EventEmitter.js\";\n\n/**\n * The `UserStore` is used to retrieve and cache information about users.\n *\n * It does this by calling `resolveUsers` (which is user-defined in the Editor Options)\n * for users that are not yet cached.\n */\nexport class UserStore<U extends User> extends EventEmitter<any> {\n private userCache: Map<string, U> = new Map();\n\n // avoid duplicate loads\n private loadingUsers = new Set<string>();\n\n public constructor(\n private readonly resolveUsers: (userIds: string[]) => Promise<U[]>,\n ) {\n super();\n }\n\n /**\n * Load information about users based on an array of user ids.\n */\n public async loadUsers(userIds: string[]) {\n const missingUsers = userIds.filter(\n (id) => !this.userCache.has(id) && !this.loadingUsers.has(id),\n );\n\n if (missingUsers.length === 0) {\n return;\n }\n\n for (const id of missingUsers) {\n this.loadingUsers.add(id);\n }\n\n try {\n const users = await this.resolveUsers(missingUsers);\n for (const user of users) {\n this.userCache.set(user.id, user);\n }\n this.emit(\"update\", this.userCache);\n } finally {\n for (const id of missingUsers) {\n // delete the users from the loading set\n // on a next call to `loadUsers` we will either\n // return the cached user or retry loading the user if the request failed failed\n this.loadingUsers.delete(id);\n }\n }\n }\n\n /**\n * Retrieve information about a user based on their id, if cached.\n *\n * The user will have to be loaded via `loadUsers` first\n */\n public getUser(userId: string): U | undefined {\n return this.userCache.get(userId);\n }\n\n /**\n * Subscribe to changes in the user store.\n *\n * @param cb - The callback to call when the user store changes.\n * @returns A function to unsubscribe from the user store.\n */\n public subscribe(cb: (users: Map<string, U>) => void): () => void {\n return this.on(\"update\", cb);\n }\n}\n","import { Node } from \"prosemirror-model\";\nimport { Plugin, PluginKey } from \"prosemirror-state\";\nimport { Decoration, DecorationSet } from \"prosemirror-view\";\nimport { getRelativeSelection, ySyncPluginKey } from \"y-prosemirror\";\nimport {\n createExtension,\n createStore,\n ExtensionOptions,\n} from \"../editor/BlockNoteExtension.js\";\nimport { ShowSelectionExtension } from \"../extensions/ShowSelection/ShowSelection.js\";\nimport { CustomBlockNoteSchema } from \"../schema/schema.js\";\nimport { CommentMark } from \"./mark.js\";\nimport type { ThreadStore } from \"./threadstore/ThreadStore.js\";\nimport type { CommentBody, ThreadData } from \"./types.js\";\nimport { User } from \"./types.js\";\nimport { UserStore } from \"./userstore/UserStore.js\";\n\nconst PLUGIN_KEY = new PluginKey(\"blocknote-comments\");\n\ntype CommentsPluginState = {\n /**\n * Decorations to be rendered, specifically to indicate the selected thread\n */\n decorations: DecorationSet;\n};\n\n/**\n * Calculate the thread positions from the current document state\n */\nfunction getUpdatedThreadPositions(doc: Node, markType: string) {\n const threadPositions = new Map<string, { from: number; to: number }>();\n\n // find all thread marks and store their position + create decoration for selected thread\n doc.descendants((node, pos) => {\n node.marks.forEach((mark) => {\n if (mark.type.name === markType) {\n const thisThreadId = (mark.attrs as { threadId: string | undefined })\n .threadId;\n if (!thisThreadId) {\n return;\n }\n const from = pos;\n const to = from + node.nodeSize;\n\n // FloatingThreads component uses \"to\" as the position, so always store the largest \"to\" found\n // AnchoredThreads component uses \"from\" as the position, so always store the smallest \"from\" found\n const currentPosition = threadPositions.get(thisThreadId) ?? {\n from: Infinity,\n to: 0,\n };\n threadPositions.set(thisThreadId, {\n from: Math.min(from, currentPosition.from),\n to: Math.max(to, currentPosition.to),\n });\n }\n });\n });\n return threadPositions;\n}\n\nexport const CommentsExtension = createExtension(\n ({\n editor,\n options: { schema: commentEditorSchema, threadStore, resolveUsers },\n }: ExtensionOptions<{\n /**\n * The thread store implementation to use for storing and retrieving comment threads\n */\n threadStore: ThreadStore;\n /**\n * Resolve user information for comments.\n *\n * See [Comments](https://www.blocknotejs.org/docs/features/collaboration/comments) for more info.\n */\n resolveUsers: (userIds: string[]) => Promise<User[]>;\n /**\n * A schema to use for the comment editor (which allows you to customize the blocks and styles that are available in the comment editor)\n */\n schema?: CustomBlockNoteSchema<any, any, any>;\n }>) => {\n if (!resolveUsers) {\n throw new Error(\n \"resolveUsers is required to be defined when using comments\",\n );\n }\n if (!threadStore) {\n throw new Error(\n \"threadStore is required to be defined when using comments\",\n );\n }\n const markType = CommentMark.name;\n\n const userStore = new UserStore<User>(resolveUsers);\n const store = createStore(\n {\n pendingComment: false,\n selectedThreadId: undefined as string | undefined,\n threadPositions: new Map<string, { from: number; to: number }>(),\n },\n {\n onUpdate() {\n // If the selected thread id changed, we need to update the decorations\n if (\n store.state.selectedThreadId !== store.prevState.selectedThreadId\n ) {\n // So, we issue a transaction to update the decorations\n editor.transact((tr) => tr.setMeta(PLUGIN_KEY, true));\n }\n },\n },\n );\n\n const updateMarksFromThreads = (threads: Map<string, ThreadData>) => {\n editor.transact((tr) => {\n tr.doc.descendants((node, pos) => {\n node.marks.forEach((mark) => {\n if (mark.type.name === markType) {\n const markTypeInstance = mark.type;\n const markThreadId = mark.attrs.threadId as string;\n const thread = threads.get(markThreadId);\n const isOrphan = !!(\n !thread ||\n thread.resolved ||\n thread.deletedAt\n );\n\n if (isOrphan !== mark.attrs.orphan) {\n const trimmedFrom = Math.max(pos, 0);\n const trimmedTo = Math.min(\n pos + node.nodeSize,\n tr.doc.content.size - 1,\n tr.doc.content.size - 1,\n );\n tr.removeMark(trimmedFrom, trimmedTo, mark);\n tr.addMark(\n trimmedFrom,\n trimmedTo,\n markTypeInstance.create({\n ...mark.attrs,\n orphan: isOrphan,\n }),\n );\n\n if (isOrphan && store.state.selectedThreadId === markThreadId) {\n // unselect\n store.setState((prev) => ({\n ...prev,\n selectedThreadId: undefined,\n }));\n }\n }\n }\n });\n });\n });\n };\n\n return {\n key: \"comments\",\n store,\n prosemirrorPlugins: [\n new Plugin<CommentsPluginState>({\n key: PLUGIN_KEY,\n state: {\n init() {\n return {\n decorations: DecorationSet.empty,\n };\n },\n apply(tr, state) {\n const action = tr.getMeta(PLUGIN_KEY);\n\n if (!tr.docChanged && !action) {\n return state;\n }\n\n // only update threadPositions if the doc changed\n const newThreadPositions = tr.docChanged\n ? getUpdatedThreadPositions(tr.doc, markType)\n : store.state.threadPositions;\n\n if (\n newThreadPositions.size > 0 ||\n store.state.threadPositions.size > 0\n ) {\n // small optimization; don't emit event if threadPositions before / after were both empty\n store.setState((prev) => ({\n ...prev,\n threadPositions: newThreadPositions,\n }));\n }\n\n // update decorations if doc or selected thread changed\n const decorations = [] as any[];\n\n if (store.state.selectedThreadId) {\n const selectedThreadPosition = newThreadPositions.get(\n store.state.selectedThreadId,\n );\n\n if (selectedThreadPosition) {\n decorations.push(\n Decoration.inline(\n selectedThreadPosition.from,\n selectedThreadPosition.to,\n {\n class: \"bn-thread-mark-selected\",\n },\n ),\n );\n }\n }\n\n return {\n decorations: DecorationSet.create(tr.doc, decorations),\n };\n },\n },\n props: {\n decorations(state) {\n return (\n PLUGIN_KEY.getState(state)?.decorations ?? DecorationSet.empty\n );\n },\n handleClick: (view, pos, event) => {\n if (event.button !== 0) {\n return;\n }\n\n const node = view.state.doc.nodeAt(pos);\n\n if (!node) {\n // unselect\n store.setState((prev) => ({\n ...prev,\n selectedThreadId: undefined,\n }));\n return;\n }\n\n const commentMark = node.marks.find(\n (mark) =>\n mark.type.name === markType && mark.attrs.orphan !== true,\n );\n\n const threadId = commentMark?.attrs.threadId as\n | string\n | undefined;\n if (threadId !== store.state.selectedThreadId) {\n store.setState((prev) => ({\n ...prev,\n selectedThreadId: threadId,\n }));\n }\n },\n },\n }),\n ],\n threadStore: threadStore,\n mount() {\n const unsubscribe = threadStore.subscribe(updateMarksFromThreads);\n updateMarksFromThreads(threadStore.getThreads());\n\n const unsubscribeOnSelectionChange = editor.onSelectionChange(() => {\n if (store.state.pendingComment) {\n store.setState((prev) => ({\n ...prev,\n pendingComment: false,\n }));\n }\n });\n\n return () => {\n unsubscribe();\n unsubscribeOnSelectionChange();\n };\n },\n selectThread(threadId: string | undefined, scrollToThread = true) {\n if (store.state.selectedThreadId === threadId) {\n return;\n }\n store.setState((prev) => ({\n ...prev,\n pendingComment: false,\n selectedThreadId: threadId,\n }));\n\n if (threadId && scrollToThread) {\n const selectedThreadPosition =\n store.state.threadPositions.get(threadId);\n if (!selectedThreadPosition) {\n return;\n }\n (\n editor.prosemirrorView?.domAtPos(selectedThreadPosition.from)\n .node as Element | undefined\n )?.scrollIntoView({\n behavior: \"smooth\",\n block: \"center\",\n });\n }\n },\n startPendingComment() {\n store.setState((prev) => ({\n ...prev,\n selectedThreadId: undefined,\n pendingComment: true,\n }));\n editor\n .getExtension(ShowSelectionExtension)\n ?.showSelection(true, \"comments\");\n },\n stopPendingComment() {\n store.setState((prev) => ({\n ...prev,\n selectedThreadId: undefined,\n pendingComment: false,\n }));\n editor\n .getExtension(ShowSelectionExtension)\n ?.showSelection(false, \"comments\");\n },\n async createThread(options: {\n initialComment: { body: CommentBody; metadata?: any };\n metadata?: any;\n }) {\n const thread = await threadStore.createThread(options);\n if (threadStore.addThreadToDocument) {\n const view = editor.prosemirrorView!;\n const pmSelection = view.state.selection;\n const ystate = ySyncPluginKey.getState(view.state);\n const selection = {\n prosemirror: {\n head: pmSelection.head,\n anchor: pmSelection.anchor,\n },\n yjs: ystate\n ? getRelativeSelection(ystate.binding, view.state)\n : undefined,\n };\n await threadStore.addThreadToDocument({\n threadId: thread.id,\n selection,\n });\n } else {\n (editor as any)._tiptapEditor.commands.setMark(markType, {\n orphan: false,\n threadId: thread.id,\n });\n }\n },\n userStore,\n commentEditorSchema,\n tiptapExtensions: [CommentMark],\n } as const;\n },\n);\n","import { CommentData, ThreadData } from \"../types.js\";\n\nexport abstract class ThreadStoreAuth {\n abstract canCreateThread(): boolean;\n abstract canAddComment(thread: ThreadData): boolean;\n abstract canUpdateComment(comment: CommentData): boolean;\n abstract canDeleteComment(comment: CommentData): boolean;\n abstract canDeleteThread(thread: ThreadData): boolean;\n abstract canResolveThread(thread: ThreadData): boolean;\n abstract canUnresolveThread(thread: ThreadData): boolean;\n abstract canAddReaction(comment: CommentData, emoji?: string): boolean;\n abstract canDeleteReaction(comment: CommentData, emoji?: string): boolean;\n}\n","import { CommentData, ThreadData } from \"../types.js\";\nimport { ThreadStoreAuth } from \"./ThreadStoreAuth.js\";\n\n/*\n * The DefaultThreadStoreAuth class defines the authorization rules for interacting with comments.\n * We take a role (\"comment\" or \"editor\") and implement the rules.\n *\n * This class is then used in the UI to show / hide specific interactions.\n *\n * Rules:\n * - View-only users should not be able to see any comments\n * - Comment-only users and editors can:\n * - - create new comments / replies / reactions\n * - - edit / delete their own comments / reactions\n * - - resolve / unresolve threads\n * - Editors can also delete any comment or thread\n */\nexport class DefaultThreadStoreAuth extends ThreadStoreAuth {\n constructor(\n private readonly userId: string,\n private readonly role: \"comment\" | \"editor\",\n ) {\n super();\n }\n\n /**\n * Auth: should be possible by anyone with comment access\n */\n canCreateThread(): boolean {\n return true;\n }\n\n /**\n * Auth: should be possible by anyone with comment access\n */\n canAddComment(_thread: ThreadData): boolean {\n return true;\n }\n\n /**\n * Auth: should only be possible by the comment author\n */\n canUpdateComment(comment: CommentData): boolean {\n return comment.userId === this.userId;\n }\n\n /**\n * Auth: should be possible by the comment author OR an editor of the document\n */\n canDeleteComment(comment: CommentData): boolean {\n return comment.userId === this.userId || this.role === \"editor\";\n }\n\n /**\n * Auth: should only be possible by an editor of the document\n */\n canDeleteThread(_thread: ThreadData): boolean {\n return this.role === \"editor\";\n }\n\n /**\n * Auth: should be possible by anyone with comment access\n */\n canResolveThread(_thread: ThreadData): boolean {\n return true;\n }\n\n /**\n * Auth: should be possible by anyone with comment access\n */\n canUnresolveThread(_thread: ThreadData): boolean {\n return true;\n }\n\n /**\n * Auth: should be possible by anyone with comment access\n *\n * Note: will also check if the user has already reacted with the same emoji. TBD: is that a nice design or should this responsibility be outside of auth?\n */\n canAddReaction(comment: CommentData, emoji?: string): boolean {\n if (!emoji) {\n return true;\n }\n\n return !comment.reactions.some(\n (reaction) =>\n reaction.emoji === emoji && reaction.userIds.includes(this.userId),\n );\n }\n\n /**\n * Auth: should be possible by anyone with comment access\n *\n * Note: will also check if the user has already reacted with the same emoji. TBD: is that a nice design or should this responsibility be outside of auth?\n */\n canDeleteReaction(comment: CommentData, emoji?: string): boolean {\n if (!emoji) {\n return true;\n }\n\n return comment.reactions.some(\n (reaction) =>\n reaction.emoji === emoji && reaction.userIds.includes(this.userId),\n );\n }\n}\n","import { CommentBody, CommentData, ThreadData } from \"../types.js\";\nimport { ThreadStoreAuth } from \"./ThreadStoreAuth.js\";\n\n/**\n * ThreadStore is an abstract class that defines the interface\n * to read / add / update / delete threads and comments.\n */\nexport abstract class ThreadStore {\n public readonly auth: ThreadStoreAuth;\n\n constructor(auth: ThreadStoreAuth) {\n this.auth = auth;\n }\n\n /**\n * A \"thread\" in the ThreadStore only contains information about the content\n * of the thread / comments. It does not contain information about the position.\n *\n * This function can be implemented to store the thread in the document (by creating a mark)\n * If not implemented, default behavior will apply (creating the mark via TipTap)\n * See CommentsPlugin.ts for more details.\n */\n abstract addThreadToDocument?(options: {\n threadId: string;\n selection: {\n prosemirror: {\n head: number;\n anchor: number;\n };\n yjs?: {\n head: any;\n anchor: any;\n };\n };\n }): Promise<void>;\n\n /**\n * Creates a new thread with an initial comment.\n */\n abstract createThread(options: {\n initialComment: {\n body: CommentBody;\n metadata?: any;\n };\n metadata?: any;\n }): Promise<ThreadData>;\n\n /**\n * Adds a comment to a thread.\n */\n abstract addComment(options: {\n comment: {\n body: CommentBody;\n metadata?: any;\n };\n threadId: string;\n }): Promise<CommentData>;\n\n /**\n * Updates a comment in a thread.\n */\n abstract updateComment(options: {\n comment: {\n body: CommentBody;\n metadata?: any;\n };\n threadId: string;\n commentId: string;\n }): Promise<void>;\n\n /**\n * Deletes a comment from a thread.\n */\n abstract deleteComment(options: {\n threadId: string;\n commentId: string;\n }): Promise<void>;\n\n /**\n * Deletes a thread.\n */\n abstract deleteThread(options: { threadId: string }): Promise<void>;\n\n /**\n * Marks a thread as resolved.\n */\n abstract resolveThread(options: { threadId: string }): Promise<void>;\n\n /**\n * Marks a thread as unresolved.\n */\n abstract unresolveThread(options: { threadId: string }): Promise<void>;\n\n /**\n * Adds a reaction to a comment.\n *\n * Auth: should be possible by anyone with comment access\n */\n abstract addReaction(options: {\n threadId: string;\n commentId: string;\n emoji: string;\n }): Promise<void>;\n\n /**\n * Deletes a reaction from a comment.\n *\n * Auth: should be possible by the reaction author\n */\n abstract deleteReaction(options: {\n threadId: string;\n commentId: string;\n emoji: string;\n }): Promise<void>;\n\n /**\n * Retrieve data for a specific thread.\n */\n abstract getThread(threadId: string): ThreadData;\n\n /**\n * Retrieve all threads.\n */\n abstract getThreads(): Map<string, ThreadData>;\n\n /**\n * Subscribe to changes in the thread store.\n *\n * @returns a function to unsubscribe from the thread store\n */\n abstract subscribe(\n cb: (threads: Map<string, ThreadData>) => void,\n ): () => void;\n}\n","import {\n CommentBody,\n CommentData,\n CommentReactionData,\n ThreadData,\n} from \"../types.js\";\nimport { ThreadStore } from \"./ThreadStore.js\";\nimport { ThreadStoreAuth } from \"./ThreadStoreAuth.js\";\nimport type {\n TCollabComment,\n TCollabThread,\n TiptapCollabProvider,\n} from \"./tiptap/types.js\";\n\ntype ReactionAsTiptapData = {\n emoji: string;\n createdAt: number;\n userId: string;\n};\n\n/**\n * The `TiptapThreadStore` integrates with Tiptap's collaboration provider for comment management.\n * You can pass a `TiptapCollabProvider` to the constructor which takes care of storing the comments.\n *\n * Under the hood, this actually works similarly to the `YjsThreadStore` implementation. (comments are stored in the Yjs document)\n */\nexport class TiptapThreadStore extends ThreadStore {\n constructor(\n private readonly userId: string,\n private readonly provider: TiptapCollabProvider,\n auth: ThreadStoreAuth, // TODO: use?\n ) {\n super(auth);\n }\n\n /**\n * Creates a new thread with an initial comment.\n */\n public async createThread(options: {\n initialComment: {\n body: CommentBody;\n metadata?: any;\n };\n metadata?: any;\n }): Promise<ThreadData> {\n let thread = this.provider.createThread({\n data: options.metadata,\n });\n\n thread = this.provider.addComment(thread.id, {\n content: options.initialComment.body,\n data: {\n metadata: options.initialComment.metadata,\n userId: this.userId,\n },\n });\n\n return this.tiptapThreadToThreadData(thread);\n }\n\n // TipTapThreadStore does not support addThreadToDocument\n public addThreadToDocument = undefined;\n\n /**\n * Adds a comment to a thread.\n */\n public async addComment(options: {\n comment: {\n body: CommentBody;\n metadata?: any;\n };\n threadId: string;\n }): Promise<CommentBody> {\n const thread = this.provider.addComment(options.threadId, {\n content: options.comment.body,\n data: {\n metadata: options.comment.metadata,\n userId: this.userId,\n },\n });\n\n return this.tiptapCommentToCommentData(\n thread.comments[thread.comments.length - 1],\n );\n }\n\n /**\n * Updates a comment in a thread.\n */\n public async updateComment(options: {\n comment: {\n body: CommentBody;\n metadata?: any;\n };\n threadId: string;\n commentId: string;\n }) {\n const comment = this.provider.getThreadComment(\n options.threadId,\n options.commentId,\n true,\n );\n\n if (!comment) {\n throw new Error(\"Comment not found\");\n }\n\n this.provider.updateComment(options.threadId, options.commentId, {\n content: options.comment.body,\n data: {\n ...comment.data,\n metadata: options.comment.metadata,\n },\n });\n }\n\n private tiptapCommentToCommentData(comment: TCollabComment): CommentData {\n const reactions: CommentReactionData[] = [];\n\n for (const reaction of (comment.data?.reactions ||\n []) as ReactionAsTiptapData[]) {\n const existingReaction = reactions.find(\n (r) => r.emoji === reaction.emoji,\n );\n if (existingReaction) {\n existingReaction.userIds.push(reaction.userId);\n existingReaction.createdAt = new Date(\n Math.min(existingReaction.createdAt.getTime(), reaction.createdAt),\n );\n } else {\n reactions.push({\n emoji: reaction.emoji,\n createdAt: new Date(reaction.createdAt),\n userIds: [reaction.userId],\n });\n }\n }\n\n return {\n type: \"comment\",\n id: comment.id,\n body: comment.content,\n metadata: comment.data?.metadata,\n userId: comment.data?.userId,\n createdAt: new Date(comment.createdAt),\n updatedAt: new Date(comment.updatedAt),\n reactions,\n };\n }\n\n private tiptapThreadToThreadData(thread: TCollabThread): ThreadData {\n return {\n type: \"thread\",\n id: thread.id,\n comments: thread.comments.map((comment) =>\n this.tiptapCommentToCommentData(comment),\n ),\n resolved: !!thread.resolvedAt,\n metadata: thread.data?.metadata,\n createdAt: new Date(thread.createdAt),\n updatedAt: new Date(thread.updatedAt),\n };\n }\n\n /**\n * Deletes a comment from a thread.\n */\n public async deleteComment(options: { threadId: string; commentId: string }) {\n this.provider.deleteComment(options.threadId, options.commentId);\n }\n\n /**\n * Deletes a thread.\n */\n public async deleteThread(options: { threadId: string }) {\n this.provider.deleteThread(options.threadId);\n }\n\n /**\n * Marks a thread as resolved.\n */\n public async resolveThread(options: { threadId: string }) {\n this.provider.updateThread(options.threadId, {\n resolvedAt: new Date().toISOString(),\n });\n }\n\n /**\n * Marks a thread as unresolved.\n */\n public async unresolveThread(options: { threadId: string }) {\n this.provider.updateThread(options.threadId, {\n resolvedAt: null,\n });\n }\n\n /**\n * Adds a reaction to a comment.\n *\n * Auth: should be possible by anyone with comment access\n */\n public async addReaction(options: {\n threadId: string;\n commentId: string;\n emoji: string;\n }) {\n const comment = this.provider.getThreadComment(\n options.threadId,\n options.commentId,\n true,\n );\n\n if (!comment) {\n throw new Error(\"Comment not found\");\n }\n\n this.provider.updateComment(options.threadId, options.commentId, {\n data: {\n ...comment.data,\n reactions: [\n ...((comment.data?.reactions || []) as ReactionAsTiptapData[]),\n {\n emoji: options.emoji,\n createdAt: Date.now(),\n userId: this.userId,\n },\n ],\n },\n });\n }\n\n /**\n * Deletes a reaction from a comment.\n *\n * Auth: should be possible by the reaction author\n */\n public async deleteReaction(options: {\n threadId: string;\n commentId: string;\n emoji: string;\n }) {\n const comment = this.provider.getThreadComment(\n options.threadId,\n options.commentId,\n true,\n );\n\n if (!comment) {\n throw new Error(\"Comment not found\");\n }\n\n this.provider.updateComment(options.threadId, options.commentId, {\n data: {\n ...comment.data,\n reactions: (\n (comment.data?.reactions || []) as ReactionAsTiptapData[]\n ).filter(\n (reaction) =>\n reaction.emoji !== options.emoji && reaction.userId !== this.userId,\n ),\n },\n });\n }\n\n public getThread(threadId: string): ThreadData {\n const thread = this.provider.getThread(threadId);\n\n if (!thread) {\n throw new Error(\"Thread not found\");\n }\n\n return this.tiptapThreadToThreadData(thread);\n }\n\n public getThreads(): Map<string, ThreadData> {\n return new Map(\n this.provider\n .getThreads()\n .map((thread) => [thread.id, this.tiptapThreadToThreadData(thread)]),\n );\n }\n\n public subscribe(cb: (threads: Map<string, ThreadData>) => void): () => void {\n const newCb = () => {\n cb(this.getThreads());\n };\n this.provider.watchThreads(newCb);\n return () => {\n this.provider.unwatchThreads(newCb);\n };\n }\n}\n","import * as Y from \"yjs\";\nimport { CommentData, CommentReactionData, ThreadData } from \"../../types.js\";\n\nexport function commentToYMap(comment: CommentData) {\n const yMap = new Y.Map<any>();\n yMap.set(\"id\", comment.id);\n yMap.set(\"userId\", comment.userId);\n yMap.set(\"createdAt\", comment.createdAt.getTime());\n yMap.set(\"updatedAt\", comment.updatedAt.getTime());\n if (comment.deletedAt) {\n yMap.set(\"deletedAt\", comment.deletedAt.getTime());\n yMap.set(\"body\", undefined);\n } else {\n yMap.set(\"body\", comment.body);\n }\n if (comment.reactions.length > 0) {\n throw new Error(\"Reactions should be empty in commentToYMap\");\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 yMapToReactions).\n */\n yMap.set(\"reactionsByUser\", new Y.Map());\n yMap.set(\"metadata\", comment.metadata);\n\n return yMap;\n}\n\nexport function threadToYMap(thread: ThreadData) {\n const yMap = new Y.Map();\n yMap.set(\"id\", thread.id);\n yMap.set(\"createdAt\", thread.createdAt.getTime());\n yMap.set(\"updatedAt\", thread.updatedAt.getTime());\n const commentsArray = new Y.Array<Y.Map<any>>();\n\n commentsArray.push(thread.comments.map((comment) => commentToYMap(comment)));\n\n yMap.set(\"comments\", commentsArray);\n yMap.set(\"resolved\", thread.resolved);\n yMap.set(\"resolvedUpdatedAt\", thread.resolvedUpdatedAt?.getTime());\n yMap.set(\"resolvedBy\", thread.resolvedBy);\n yMap.set(\"metadata\", thread.metadata);\n return yMap;\n}\n\ntype SingleUserCommentReactionData = {\n emoji: string;\n createdAt: Date;\n userId: string;\n};\n\nexport function yMapToReaction(\n yMap: Y.Map<any>,\n): SingleUserCommentReactionData {\n return {\n emoji: yMap.get(\"emoji\"),\n createdAt: new Date(yMap.get(\"createdAt\")),\n userId: yMap.get(\"userId\"),\n };\n}\n\nfunction yMapToReactions(yMap: Y.Map<any>): CommentReactionData[] {\n const flatReactions = [...yMap.values()].map((reaction: Y.Map<any>) =>\n yMapToReaction(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 yMapToComment(yMap: Y.Map<any>): CommentData {\n return {\n type: \"comment\",\n id: yMap.get(\"id\"),\n userId: yMap.get(\"userId\"),\n createdAt: new Date(yMap.get(\"createdAt\")),\n updatedAt: new Date(yMap.get(\"updatedAt\")),\n deletedAt: yMap.get(\"deletedAt\")\n ? new Date(yMap.get(\"deletedAt\"))\n : undefined,\n reactions: yMapToReactions(yMap.get(\"reactionsByUser\")),\n metadata: yMap.get(\"metadata\"),\n body: yMap.get(\"body\"),\n };\n}\n\nexport function yMapToThread(yMap: Y.Map<any>): ThreadData {\n return {\n type: \"thread\",\n id: yMap.get(\"id\"),\n createdAt: new Date(yMap.get(\"createdAt\")),\n updatedAt: new Date(yMap.get(\"updatedAt\")),\n comments: ((yMap.get(\"comments\") as Y.Array<Y.Map<any>>) || []).map(\n (comment) => yMapToComment(comment),\n ),\n resolved: yMap.get(\"resolved\"),\n resolvedUpdatedAt: new Date(yMap.get(\"resolvedUpdatedAt\")),\n resolvedBy: yMap.get(\"resolvedBy\"),\n metadata: yMap.get(\"metadata\"),\n };\n}\n","import * as Y from \"yjs\";\nimport { ThreadData } from \"../../types.js\";\nimport { ThreadStore } from \"../ThreadStore.js\";\nimport { ThreadStoreAuth } from \"../ThreadStoreAuth.js\";\nimport { yMapToThread } 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 Yjs Map.\n */\nexport abstract class YjsThreadStoreBase extends ThreadStore {\n constructor(\n protected readonly threadsYMap: Y.Map<any>,\n auth: ThreadStoreAuth,\n ) {\n super(auth);\n }\n\n // TODO: async / reactive interface?\n public getThread(threadId: string) {\n const yThread = this.threadsYMap.get(threadId);\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n const thread = yMapToThread(yThread);\n return thread;\n }\n\n public getThreads(): Map<string, ThreadData> {\n const threadMap = new Map<string, ThreadData>();\n this.threadsYMap.forEach((yThread, id) => {\n if (yThread instanceof Y.Map) {\n threadMap.set(id, yMapToThread(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.threadsYMap.observeDeep(observer);\n\n return () => {\n this.threadsYMap.unobserveDeep(observer);\n };\n }\n}\n","import * as Y from \"yjs\";\nimport { CommentBody } from \"../../types.js\";\nimport { ThreadStoreAuth } from \"../ThreadStoreAuth.js\";\nimport { YjsThreadStoreBase } from \"./YjsThreadStoreBase.js\";\n\n/**\n * This is a REST-based implementation of the YjsThreadStoreBase.\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 threadsYMap: Y.Map<any>,\n auth: ThreadStoreAuth,\n ) {\n super(threadsYMap, 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 prosemirror: {\n head: number;\n anchor: number;\n };\n yjs: {\n head: any;\n anchor: any;\n };\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 { v4 } from \"uuid\";\nimport * as Y from \"yjs\";\nimport { CommentBody, CommentData, ThreadData } from \"../../types.js\";\nimport { ThreadStoreAuth } from \"../ThreadStoreAuth.js\";\nimport { YjsThreadStoreBase } from \"./YjsThreadStoreBase.js\";\nimport {\n commentToYMap,\n threadToYMap,\n yMapToComment,\n yMapToThread,\n} from \"./yjsHelpers.js\";\n\n/**\n * This is a Yjs-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 threadsYMap: Y.Map<any>,\n auth: ThreadStoreAuth,\n ) {\n super(threadsYMap, 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.threadsYMap.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: v4(),\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: v4(),\n createdAt: date,\n updatedAt: date,\n comments: [comment],\n resolved: false,\n metadata: options.metadata,\n };\n\n this.threadsYMap.set(thread.id, threadToYMap(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.threadsYMap.get(options.threadId);\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n if (!this.auth.canAddComment(yMapToThread(yThread))) {\n throw new Error(\"Not authorized\");\n }\n\n const date = new Date();\n const comment: CommentData = {\n type: \"comment\",\n id: v4(),\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.get(\"comments\") as Y.Array<Y.Map<any>>).push([\n commentToYMap(comment),\n ]);\n\n yThread.set(\"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.threadsYMap.get(options.threadId);\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n const yCommentIndex = yArrayFindIndex(\n yThread.get(\"comments\"),\n (comment) => comment.get(\"id\") === options.commentId,\n );\n\n if (yCommentIndex === -1) {\n throw new Error(\"Comment not found\");\n }\n\n const yComment = yThread.get(\"comments\").get(yCommentIndex);\n\n if (!this.auth.canUpdateComment(yMapToComment(yComment))) {\n throw new Error(\"Not authorized\");\n }\n\n yComment.set(\"body\", options.comment.body);\n yComment.set(\"updatedAt\", new Date().getTime());\n yComment.set(\"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.threadsYMap.get(options.threadId);\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n const yCommentIndex = yArrayFindIndex(\n yThread.get(\"comments\"),\n (comment) => comment.get(\"id\") === options.commentId,\n );\n\n if (yCommentIndex === -1) {\n throw new Error(\"Comment not found\");\n }\n\n const yComment = yThread.get(\"comments\").get(yCommentIndex);\n\n if (!this.auth.canDeleteComment(yMapToComment(yComment))) {\n throw new Error(\"Not authorized\");\n }\n\n if (yComment.get(\"deletedAt\")) {\n throw new Error(\"Comment already deleted\");\n }\n\n if (options.softDelete) {\n yComment.set(\"deletedAt\", new Date().getTime());\n yComment.set(\"body\", undefined);\n } else {\n yThread.get(\"comments\").delete(yCommentIndex);\n }\n\n if (\n (yThread.get(\"comments\") as Y.Array<any>)\n .toArray()\n .every((comment) => comment.get(\"deletedAt\"))\n ) {\n // all comments deleted\n if (options.softDelete) {\n yThread.set(\"deletedAt\", new Date().getTime());\n } else {\n this.threadsYMap.delete(options.threadId);\n }\n }\n\n yThread.set(\"updatedAt\", new Date().getTime());\n },\n );\n\n public deleteThread = this.transact((options: { threadId: string }) => {\n if (\n !this.auth.canDeleteThread(\n yMapToThread(this.threadsYMap.get(options.threadId)),\n )\n ) {\n throw new Error(\"Not authorized\");\n }\n\n this.threadsYMap.delete(options.threadId);\n });\n\n public resolveThread = this.transact((options: { threadId: string }) => {\n const yThread = this.threadsYMap.get(options.threadId);\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n if (!this.auth.canResolveThread(yMapToThread(yThread))) {\n throw new Error(\"Not authorized\");\n }\n\n yThread.set(\"resolved\", true);\n yThread.set(\"resolvedUpdatedAt\", new Date().getTime());\n yThread.set(\"resolvedBy\", this.userId);\n });\n\n public unresolveThread = this.transact((options: { threadId: string }) => {\n const yThread = this.threadsYMap.get(options.threadId);\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n if (!this.auth.canUnresolveThread(yMapToThread(yThread))) {\n throw new Error(\"Not authorized\");\n }\n\n yThread.set(\"resolved\", false);\n yThread.set(\"resolvedUpdatedAt\", new Date().getTime());\n });\n\n public addReaction = this.transact(\n (options: { threadId: string; commentId: string; emoji: string }) => {\n const yThread = this.threadsYMap.get(options.threadId);\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n const yCommentIndex = yArrayFindIndex(\n yThread.get(\"comments\"),\n (comment) => comment.get(\"id\") === options.commentId,\n );\n\n if (yCommentIndex === -1) {\n throw new Error(\"Comment not found\");\n }\n\n const yComment = yThread.get(\"comments\").get(yCommentIndex);\n\n if (!this.auth.canAddReaction(yMapToComment(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.get(\"reactionsByUser\");\n\n if (reactionsByUser.has(key)) {\n // already exists\n return;\n } else {\n const reaction = new Y.Map();\n reaction.set(\"emoji\", options.emoji);\n reaction.set(\"createdAt\", date.getTime());\n reaction.set(\"userId\", this.userId);\n reactionsByUser.set(key, reaction);\n }\n },\n );\n\n public deleteReaction = this.transact(\n (options: { threadId: string; commentId: string; emoji: string }) => {\n const yThread = this.threadsYMap.get(options.threadId);\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n const yCommentIndex = yArrayFindIndex(\n yThread.get(\"comments\"),\n (comment) => comment.get(\"id\") === options.commentId,\n );\n\n if (yCommentIndex === -1) {\n throw new Error(\"Comment not found\");\n }\n\n const yComment = yThread.get(\"comments\").get(yCommentIndex);\n\n if (\n !this.auth.canDeleteReaction(yMapToComment(yComment), options.emoji)\n ) {\n throw new Error(\"Not authorized\");\n }\n\n const key = `${this.userId}-${options.emoji}`;\n\n const reactionsByUser = yComment.get(\"reactionsByUser\");\n\n reactionsByUser.delete(key);\n },\n );\n}\n\nfunction yArrayFindIndex(\n yArray: Y.Array<any>,\n predicate: (item: any) => boolean,\n) {\n for (let i = 0; i < yArray.length; i++) {\n if (predicate(yArray.get(i))) {\n return i;\n }\n }\n return -1;\n}\n"],"mappings":";;;;;;;;;;AAEA,IAAa,IAAc,EAAK,OAAO;CACrC,MAAM;CACN,UAAU;CACV,WAAW;CACX,aAAa;CAEb,gBAAgB;AAEd,SAAO;GAKL,QAAQ;IACN,YAAY,MAAY,CAAC,CAAC,EAAQ,aAAa,cAAc;IAC7D,aAAa,MACH,EAAmC,SACvC,EACE,eAAe,QAChB,GACD,EAAE;IAER,SAAS;IACV;GACD,UAAU;IACR,YAAY,MAAY,EAAQ,aAAa,oBAAoB;IACjE,aAAa,OACJ,EACL,qBAAsB,EAAoC,UAC3D;IAEH,SAAS;IACV;GACF;;CAGH,WAAW,EAAE,qBAA2D;AACtE,SAAO,CACL,QACA,EAAgB,GAAgB,EAC9B,OAAO,kBACR,CAAC,CACH;;CAGH,YAAY;AACV,SAAO,CAAC,EAAE,KAAK,uBAAuB,CAAC;;CAGzC,iBAAiB,GAAW;AAM1B,SALI,EAAU,SAAS,YACd,EACL,iBAAiB,IAClB,GAEI,EAAE;;CAEZ,CAAC,EClDW,IAAb,cAA+C,EAAkB;CAC/D,4BAAoC,IAAI,KAAK;CAG7C,+BAAuB,IAAI,KAAa;CAExC,YACE,GACA;AADiB,EAEjB,OAAO,EAFU,KAAA,eAAA;;CAQnB,MAAa,UAAU,GAAmB;EACxC,IAAM,IAAe,EAAQ,QAC1B,MAAO,CAAC,KAAK,UAAU,IAAI,EAAG,IAAI,CAAC,KAAK,aAAa,I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EAAQ,SAEhC,IAAkB,EAAS,IAAI,kBAAkB;AAEnD,SAAgB,IAAI,EAAI,EAGrB;GACL,IAAM,IAAW,IAAI,EAAE,KAAK;AAI5B,GAHA,EAAS,IAAI,SAAS,EAAQ,MAAM,EACpC,EAAS,IAAI,aAAa,EAAK,SAAS,CAAC,EACzC,EAAS,IAAI,UAAU,KAAK,OAAO,EACnC,EAAgB,IAAI,GAAK,EAAS;;GAGvC;CAED,iBAAwB,KAAK,UAC1B,MAAoE;EACnE,IAAM,IAAU,KAAK,YAAY,IAAI,EAAQ,SAAS;AACtD,MAAI,CAAC,EACH,OAAU,MAAM,mBAAmB;EAGrC,IAAM,IAAgB,EACpB,EAAQ,IAAI,WAAW,GACtB,MAAY,EAAQ,IAAI,KAAK,KAAK,EAAQ,UAC5C;AAED,MAAI,MAAkB,GACpB,OAAU,MAAM,oBAAoB;EAGtC,IAAM,IAAW,EAAQ,IAAI,WAAW,CAAC,IAAI,EAAc;AAE3D,MACE,CAAC,KAAK,KAAK,kBAAkB,EAAc,EAAS,EAAE,EAAQ,MAAM,CAEpE,OAAU,MAAM,iBAAiB;EAGnC,IAAM,IAAM,GAAG,KAAK,OAAO,GAAG,EAAQ;AAEd,IAAS,IAAI,kBAAkB,CAEvC,OAAO,EAAI;GAE9B;;AAGH,SAAS,EACP,GACA,GACA;AACA,MAAK,IAAI,IAAI,GAAG,IAAI,EAAO,QAAQ,IACjC,KAAI,EAAU,EAAO,IAAI,EAAE,CAAC,CAC1B,QAAO;AAGX,QAAO"}
1
+ {"version":3,"file":"comments.js","names":[],"sources":["../src/comments/mark.ts","../src/comments/userstore/UserStore.ts","../src/comments/extension.ts","../src/comments/threadstore/ThreadStoreAuth.ts","../src/comments/threadstore/DefaultThreadStoreAuth.ts","../src/comments/threadstore/ThreadStore.ts","../src/comments/threadstore/TipTapThreadStore.ts","../src/comments/threadstore/yjs/yjsHelpers.ts","../src/comments/threadstore/yjs/YjsThreadStoreBase.ts","../src/comments/threadstore/yjs/RESTYjsThreadStore.ts","../src/comments/threadstore/yjs/YjsThreadStore.ts"],"sourcesContent":["import { Mark, mergeAttributes } from \"@tiptap/core\";\n\nexport const CommentMark = Mark.create({\n name: \"comment\",\n excludes: \"\",\n inclusive: false,\n keepOnSplit: true,\n\n addAttributes() {\n // Return an object with attribute configuration\n return {\n // orphans are marks that currently don't have an active thread. It could be\n // that users have resolved the thread. Resolved threads by default are not shown in the document,\n // but we need to keep the mark (positioning) data so we can still \"revive\" it when the thread is unresolved\n // or we enter a \"comments\" view that includes resolved threads.\n orphan: {\n parseHTML: (element) => !!element.getAttribute(\"data-orphan\"),\n renderHTML: (attributes) => {\n return (attributes as { orphan: boolean }).orphan\n ? {\n \"data-orphan\": \"true\",\n }\n : {};\n },\n default: false,\n },\n threadId: {\n parseHTML: (element) => element.getAttribute(\"data-bn-thread-id\"),\n renderHTML: (attributes) => {\n return {\n \"data-bn-thread-id\": (attributes as { threadId: string }).threadId,\n };\n },\n default: \"\",\n },\n };\n },\n\n renderHTML({ HTMLAttributes }: { HTMLAttributes: Record<string, any> }) {\n return [\n \"span\",\n mergeAttributes(HTMLAttributes, {\n class: \"bn-thread-mark\",\n }),\n ];\n },\n\n parseHTML() {\n return [{ tag: \"span.bn-thread-mark\" }];\n },\n\n extendMarkSchema(extension) {\n if (extension.name === \"comment\") {\n return {\n blocknoteIgnore: true,\n };\n }\n return {};\n },\n});\n","import type { User } from \"../types.js\";\nimport { EventEmitter } from \"../../util/EventEmitter.js\";\n\n/**\n * The `UserStore` is used to retrieve and cache information about users.\n *\n * It does this by calling `resolveUsers` (which is user-defined in the Editor Options)\n * for users that are not yet cached.\n */\nexport class UserStore<U extends User> extends EventEmitter<any> {\n private userCache: Map<string, U> = new Map();\n\n // avoid duplicate loads\n private loadingUsers = new Set<string>();\n\n public constructor(\n private readonly resolveUsers: (userIds: string[]) => Promise<U[]>,\n ) {\n super();\n }\n\n /**\n * Load information about users based on an array of user ids.\n */\n public async loadUsers(userIds: string[]) {\n const missingUsers = userIds.filter(\n (id) => !this.userCache.has(id) && !this.loadingUsers.has(id),\n );\n\n if (missingUsers.length === 0) {\n return;\n }\n\n for (const id of missingUsers) {\n this.loadingUsers.add(id);\n }\n\n try {\n const users = await this.resolveUsers(missingUsers);\n for (const user of users) {\n this.userCache.set(user.id, user);\n }\n this.emit(\"update\", this.userCache);\n } finally {\n for (const id of missingUsers) {\n // delete the users from the loading set\n // on a next call to `loadUsers` we will either\n // return the cached user or retry loading the user if the request failed failed\n this.loadingUsers.delete(id);\n }\n }\n }\n\n /**\n * Retrieve information about a user based on their id, if cached.\n *\n * The user will have to be loaded via `loadUsers` first\n */\n public getUser(userId: string): U | undefined {\n return this.userCache.get(userId);\n }\n\n /**\n * Subscribe to changes in the user store.\n *\n * @param cb - The callback to call when the user store changes.\n * @returns A function to unsubscribe from the user store.\n */\n public subscribe(cb: (users: Map<string, U>) => void): () => void {\n return this.on(\"update\", cb);\n }\n}\n","import { Node } from \"prosemirror-model\";\nimport { Plugin, PluginKey } from \"prosemirror-state\";\nimport { Decoration, DecorationSet } from \"prosemirror-view\";\nimport { getRelativeSelection, ySyncPluginKey } from \"y-prosemirror\";\nimport {\n createExtension,\n createStore,\n ExtensionOptions,\n} from \"../editor/BlockNoteExtension.js\";\nimport { ShowSelectionExtension } from \"../extensions/ShowSelection/ShowSelection.js\";\nimport { CustomBlockNoteSchema } from \"../schema/schema.js\";\nimport { CommentMark } from \"./mark.js\";\nimport type { ThreadStore } from \"./threadstore/ThreadStore.js\";\nimport type { CommentBody, ThreadData } from \"./types.js\";\nimport { User } from \"./types.js\";\nimport { UserStore } from \"./userstore/UserStore.js\";\n\nconst PLUGIN_KEY = new PluginKey(\"blocknote-comments\");\n\ntype CommentsPluginState = {\n /**\n * Decorations to be rendered, specifically to indicate the selected thread\n */\n decorations: DecorationSet;\n};\n\n/**\n * Calculate the thread positions from the current document state\n */\nfunction getUpdatedThreadPositions(doc: Node, markType: string) {\n const threadPositions = new Map<string, { from: number; to: number }>();\n\n // find all thread marks and store their position + create decoration for selected thread\n doc.descendants((node, pos) => {\n node.marks.forEach((mark) => {\n if (mark.type.name === markType) {\n const thisThreadId = (mark.attrs as { threadId: string | undefined })\n .threadId;\n if (!thisThreadId) {\n return;\n }\n const from = pos;\n const to = from + node.nodeSize;\n\n // FloatingThreads component uses \"to\" as the position, so always store the largest \"to\" found\n // AnchoredThreads component uses \"from\" as the position, so always store the smallest \"from\" found\n const currentPosition = threadPositions.get(thisThreadId) ?? {\n from: Infinity,\n to: 0,\n };\n threadPositions.set(thisThreadId, {\n from: Math.min(from, currentPosition.from),\n to: Math.max(to, currentPosition.to),\n });\n }\n });\n });\n return threadPositions;\n}\n\nexport const CommentsExtension = createExtension(\n ({\n editor,\n options: { schema: commentEditorSchema, threadStore, resolveUsers },\n }: ExtensionOptions<{\n /**\n * The thread store implementation to use for storing and retrieving comment threads\n */\n threadStore: ThreadStore;\n /**\n * Resolve user information for comments.\n *\n * See [Comments](https://www.blocknotejs.org/docs/features/collaboration/comments) for more info.\n */\n resolveUsers: (userIds: string[]) => Promise<User[]>;\n /**\n * A schema to use for the comment editor (which allows you to customize the blocks and styles that are available in the comment editor)\n */\n schema?: CustomBlockNoteSchema<any, any, any>;\n }>) => {\n if (!resolveUsers) {\n throw new Error(\n \"resolveUsers is required to be defined when using comments\",\n );\n }\n if (!threadStore) {\n throw new Error(\n \"threadStore is required to be defined when using comments\",\n );\n }\n const markType = CommentMark.name;\n\n const userStore = new UserStore<User>(resolveUsers);\n const store = createStore(\n {\n pendingComment: false,\n selectedThreadId: undefined as string | undefined,\n threadPositions: new Map<string, { from: number; to: number }>(),\n },\n {\n onUpdate() {\n // If the selected thread id changed, we need to update the decorations\n if (\n store.state.selectedThreadId !== store.prevState.selectedThreadId\n ) {\n // So, we issue a transaction to update the decorations\n editor.transact((tr) => tr.setMeta(PLUGIN_KEY, true));\n }\n },\n },\n );\n\n const updateMarksFromThreads = (threads: Map<string, ThreadData>) => {\n editor.transact((tr) => {\n tr.doc.descendants((node, pos) => {\n node.marks.forEach((mark) => {\n if (mark.type.name === markType) {\n const markTypeInstance = mark.type;\n const markThreadId = mark.attrs.threadId as string;\n const thread = threads.get(markThreadId);\n const isOrphan = !!(\n !thread ||\n thread.resolved ||\n thread.deletedAt\n );\n\n if (isOrphan !== mark.attrs.orphan) {\n const trimmedFrom = Math.max(pos, 0);\n const trimmedTo = Math.min(\n pos + node.nodeSize,\n tr.doc.content.size - 1,\n tr.doc.content.size - 1,\n );\n tr.removeMark(trimmedFrom, trimmedTo, mark);\n tr.addMark(\n trimmedFrom,\n trimmedTo,\n markTypeInstance.create({\n ...mark.attrs,\n orphan: isOrphan,\n }),\n );\n\n if (isOrphan && store.state.selectedThreadId === markThreadId) {\n // unselect\n store.setState((prev) => ({\n ...prev,\n selectedThreadId: undefined,\n }));\n }\n }\n }\n });\n });\n });\n };\n\n return {\n key: \"comments\",\n store,\n prosemirrorPlugins: [\n new Plugin<CommentsPluginState>({\n key: PLUGIN_KEY,\n state: {\n init() {\n return {\n decorations: DecorationSet.empty,\n };\n },\n apply(tr, state) {\n const action = tr.getMeta(PLUGIN_KEY);\n\n if (!tr.docChanged && !action) {\n return state;\n }\n\n // only update threadPositions if the doc changed\n const newThreadPositions = tr.docChanged\n ? getUpdatedThreadPositions(tr.doc, markType)\n : store.state.threadPositions;\n\n if (\n newThreadPositions.size > 0 ||\n store.state.threadPositions.size > 0\n ) {\n // small optimization; don't emit event if threadPositions before / after were both empty\n store.setState((prev) => ({\n ...prev,\n threadPositions: newThreadPositions,\n }));\n }\n\n // update decorations if doc or selected thread changed\n const decorations = [] as any[];\n\n if (store.state.selectedThreadId) {\n const selectedThreadPosition = newThreadPositions.get(\n store.state.selectedThreadId,\n );\n\n if (selectedThreadPosition) {\n decorations.push(\n Decoration.inline(\n selectedThreadPosition.from,\n selectedThreadPosition.to,\n {\n class: \"bn-thread-mark-selected\",\n },\n ),\n );\n }\n }\n\n return {\n decorations: DecorationSet.create(tr.doc, decorations),\n };\n },\n },\n props: {\n decorations(state) {\n return (\n PLUGIN_KEY.getState(state)?.decorations ?? DecorationSet.empty\n );\n },\n handleClick: (view, pos, event) => {\n if (event.button !== 0) {\n return;\n }\n\n const node = view.state.doc.nodeAt(pos);\n\n if (!node) {\n // unselect\n store.setState((prev) => ({\n ...prev,\n selectedThreadId: undefined,\n }));\n return;\n }\n\n const commentMark = node.marks.find(\n (mark) =>\n mark.type.name === markType && mark.attrs.orphan !== true,\n );\n\n const threadId = commentMark?.attrs.threadId as\n | string\n | undefined;\n if (threadId !== store.state.selectedThreadId) {\n store.setState((prev) => ({\n ...prev,\n selectedThreadId: threadId,\n }));\n }\n },\n },\n }),\n ],\n threadStore: threadStore,\n mount() {\n const unsubscribe = threadStore.subscribe(updateMarksFromThreads);\n updateMarksFromThreads(threadStore.getThreads());\n\n const unsubscribeOnSelectionChange = editor.onSelectionChange(() => {\n if (store.state.pendingComment) {\n store.setState((prev) => ({\n ...prev,\n pendingComment: false,\n }));\n }\n });\n\n return () => {\n unsubscribe();\n unsubscribeOnSelectionChange();\n };\n },\n selectThread(threadId: string | undefined, scrollToThread = true) {\n if (store.state.selectedThreadId === threadId) {\n return;\n }\n store.setState((prev) => ({\n ...prev,\n pendingComment: false,\n selectedThreadId: threadId,\n }));\n\n if (threadId && scrollToThread) {\n const selectedThreadPosition =\n store.state.threadPositions.get(threadId);\n if (!selectedThreadPosition) {\n return;\n }\n (\n editor.prosemirrorView?.domAtPos(selectedThreadPosition.from)\n .node as Element | undefined\n )?.scrollIntoView({\n behavior: \"smooth\",\n block: \"center\",\n });\n }\n },\n startPendingComment() {\n store.setState((prev) => ({\n ...prev,\n selectedThreadId: undefined,\n pendingComment: true,\n }));\n // Use `editor.domElement` as `editor.focus()` doesn't do anything if\n // the editor is non-editable. Editor needs to be focused as\n // `showSelection` will otherwise trigger a selection update which\n // triggers `stopPendingComment`.\n editor.domElement?.focus();\n editor\n .getExtension(ShowSelectionExtension)\n ?.showSelection(true, \"comments\");\n },\n stopPendingComment() {\n store.setState((prev) => ({\n ...prev,\n selectedThreadId: undefined,\n pendingComment: false,\n }));\n editor\n .getExtension(ShowSelectionExtension)\n ?.showSelection(false, \"comments\");\n },\n async createThread(options: {\n initialComment: { body: CommentBody; metadata?: any };\n metadata?: any;\n }) {\n const thread = await threadStore.createThread(options);\n if (threadStore.addThreadToDocument) {\n const view = editor.prosemirrorView!;\n const pmSelection = view.state.selection;\n const ystate = ySyncPluginKey.getState(view.state);\n const selection = {\n prosemirror: {\n head: pmSelection.head,\n anchor: pmSelection.anchor,\n },\n yjs: ystate\n ? getRelativeSelection(ystate.binding, view.state)\n : undefined,\n };\n await threadStore.addThreadToDocument({\n threadId: thread.id,\n selection,\n });\n } else {\n (editor as any)._tiptapEditor.commands.setMark(markType, {\n orphan: false,\n threadId: thread.id,\n });\n }\n },\n userStore,\n commentEditorSchema,\n tiptapExtensions: [CommentMark],\n } as const;\n },\n);\n","import { CommentData, ThreadData } from \"../types.js\";\n\nexport abstract class ThreadStoreAuth {\n abstract canCreateThread(): boolean;\n abstract canAddComment(thread: ThreadData): boolean;\n abstract canUpdateComment(comment: CommentData): boolean;\n abstract canDeleteComment(comment: CommentData): boolean;\n abstract canDeleteThread(thread: ThreadData): boolean;\n abstract canResolveThread(thread: ThreadData): boolean;\n abstract canUnresolveThread(thread: ThreadData): boolean;\n abstract canAddReaction(comment: CommentData, emoji?: string): boolean;\n abstract canDeleteReaction(comment: CommentData, emoji?: string): boolean;\n}\n","import { CommentData, ThreadData } from \"../types.js\";\nimport { ThreadStoreAuth } from \"./ThreadStoreAuth.js\";\n\n/*\n * The DefaultThreadStoreAuth class defines the authorization rules for interacting with comments.\n * We take a role (\"comment\" or \"editor\") and implement the rules.\n *\n * This class is then used in the UI to show / hide specific interactions.\n *\n * Rules:\n * - View-only users should not be able to see any comments\n * - Comment-only users and editors can:\n * - - create new comments / replies / reactions\n * - - edit / delete their own comments / reactions\n * - - resolve / unresolve threads\n * - Editors can also delete any comment or thread\n */\nexport class DefaultThreadStoreAuth extends ThreadStoreAuth {\n constructor(\n private readonly userId: string,\n private readonly role: \"comment\" | \"editor\",\n ) {\n super();\n }\n\n /**\n * Auth: should be possible by anyone with comment access\n */\n canCreateThread(): boolean {\n return true;\n }\n\n /**\n * Auth: should be possible by anyone with comment access\n */\n canAddComment(_thread: ThreadData): boolean {\n return true;\n }\n\n /**\n * Auth: should only be possible by the comment author\n */\n canUpdateComment(comment: CommentData): boolean {\n return comment.userId === this.userId;\n }\n\n /**\n * Auth: should be possible by the comment author OR an editor of the document\n */\n canDeleteComment(comment: CommentData): boolean {\n return comment.userId === this.userId || this.role === \"editor\";\n }\n\n /**\n * Auth: should only be possible by an editor of the document\n */\n canDeleteThread(_thread: ThreadData): boolean {\n return this.role === \"editor\";\n }\n\n /**\n * Auth: should be possible by anyone with comment access\n */\n canResolveThread(_thread: ThreadData): boolean {\n return true;\n }\n\n /**\n * Auth: should be possible by anyone with comment access\n */\n canUnresolveThread(_thread: ThreadData): boolean {\n return true;\n }\n\n /**\n * Auth: should be possible by anyone with comment access\n *\n * Note: will also check if the user has already reacted with the same emoji. TBD: is that a nice design or should this responsibility be outside of auth?\n */\n canAddReaction(comment: CommentData, emoji?: string): boolean {\n if (!emoji) {\n return true;\n }\n\n return !comment.reactions.some(\n (reaction) =>\n reaction.emoji === emoji && reaction.userIds.includes(this.userId),\n );\n }\n\n /**\n * Auth: should be possible by anyone with comment access\n *\n * Note: will also check if the user has already reacted with the same emoji. TBD: is that a nice design or should this responsibility be outside of auth?\n */\n canDeleteReaction(comment: CommentData, emoji?: string): boolean {\n if (!emoji) {\n return true;\n }\n\n return comment.reactions.some(\n (reaction) =>\n reaction.emoji === emoji && reaction.userIds.includes(this.userId),\n );\n }\n}\n","import { CommentBody, CommentData, ThreadData } from \"../types.js\";\nimport { ThreadStoreAuth } from \"./ThreadStoreAuth.js\";\n\n/**\n * ThreadStore is an abstract class that defines the interface\n * to read / add / update / delete threads and comments.\n */\nexport abstract class ThreadStore {\n public readonly auth: ThreadStoreAuth;\n\n constructor(auth: ThreadStoreAuth) {\n this.auth = auth;\n }\n\n /**\n * A \"thread\" in the ThreadStore only contains information about the content\n * of the thread / comments. It does not contain information about the position.\n *\n * This function can be implemented to store the thread in the document (by creating a mark)\n * If not implemented, default behavior will apply (creating the mark via TipTap)\n * See CommentsPlugin.ts for more details.\n */\n abstract addThreadToDocument?(options: {\n threadId: string;\n selection: {\n prosemirror: {\n head: number;\n anchor: number;\n };\n yjs?: {\n head: any;\n anchor: any;\n };\n };\n }): Promise<void>;\n\n /**\n * Creates a new thread with an initial comment.\n */\n abstract createThread(options: {\n initialComment: {\n body: CommentBody;\n metadata?: any;\n };\n metadata?: any;\n }): Promise<ThreadData>;\n\n /**\n * Adds a comment to a thread.\n */\n abstract addComment(options: {\n comment: {\n body: CommentBody;\n metadata?: any;\n };\n threadId: string;\n }): Promise<CommentData>;\n\n /**\n * Updates a comment in a thread.\n */\n abstract updateComment(options: {\n comment: {\n body: CommentBody;\n metadata?: any;\n };\n threadId: string;\n commentId: string;\n }): Promise<void>;\n\n /**\n * Deletes a comment from a thread.\n */\n abstract deleteComment(options: {\n threadId: string;\n commentId: string;\n }): Promise<void>;\n\n /**\n * Deletes a thread.\n */\n abstract deleteThread(options: { threadId: string }): Promise<void>;\n\n /**\n * Marks a thread as resolved.\n */\n abstract resolveThread(options: { threadId: string }): Promise<void>;\n\n /**\n * Marks a thread as unresolved.\n */\n abstract unresolveThread(options: { threadId: string }): Promise<void>;\n\n /**\n * Adds a reaction to a comment.\n *\n * Auth: should be possible by anyone with comment access\n */\n abstract addReaction(options: {\n threadId: string;\n commentId: string;\n emoji: string;\n }): Promise<void>;\n\n /**\n * Deletes a reaction from a comment.\n *\n * Auth: should be possible by the reaction author\n */\n abstract deleteReaction(options: {\n threadId: string;\n commentId: string;\n emoji: string;\n }): Promise<void>;\n\n /**\n * Retrieve data for a specific thread.\n */\n abstract getThread(threadId: string): ThreadData;\n\n /**\n * Retrieve all threads.\n */\n abstract getThreads(): Map<string, ThreadData>;\n\n /**\n * Subscribe to changes in the thread store.\n *\n * @returns a function to unsubscribe from the thread store\n */\n abstract subscribe(\n cb: (threads: Map<string, ThreadData>) => void,\n ): () => void;\n}\n","import {\n CommentBody,\n CommentData,\n CommentReactionData,\n ThreadData,\n} from \"../types.js\";\nimport { ThreadStore } from \"./ThreadStore.js\";\nimport { ThreadStoreAuth } from \"./ThreadStoreAuth.js\";\nimport type {\n TCollabComment,\n TCollabThread,\n TiptapCollabProvider,\n} from \"./tiptap/types.js\";\n\ntype ReactionAsTiptapData = {\n emoji: string;\n createdAt: number;\n userId: string;\n};\n\n/**\n * The `TiptapThreadStore` integrates with Tiptap's collaboration provider for comment management.\n * You can pass a `TiptapCollabProvider` to the constructor which takes care of storing the comments.\n *\n * Under the hood, this actually works similarly to the `YjsThreadStore` implementation. (comments are stored in the Yjs document)\n */\nexport class TiptapThreadStore extends ThreadStore {\n constructor(\n private readonly userId: string,\n private readonly provider: TiptapCollabProvider,\n auth: ThreadStoreAuth, // TODO: use?\n ) {\n super(auth);\n }\n\n /**\n * Creates a new thread with an initial comment.\n */\n public async createThread(options: {\n initialComment: {\n body: CommentBody;\n metadata?: any;\n };\n metadata?: any;\n }): Promise<ThreadData> {\n let thread = this.provider.createThread({\n data: options.metadata,\n });\n\n thread = this.provider.addComment(thread.id, {\n content: options.initialComment.body,\n data: {\n metadata: options.initialComment.metadata,\n userId: this.userId,\n },\n });\n\n return this.tiptapThreadToThreadData(thread);\n }\n\n // TipTapThreadStore does not support addThreadToDocument\n public addThreadToDocument = undefined;\n\n /**\n * Adds a comment to a thread.\n */\n public async addComment(options: {\n comment: {\n body: CommentBody;\n metadata?: any;\n };\n threadId: string;\n }): Promise<CommentBody> {\n const thread = this.provider.addComment(options.threadId, {\n content: options.comment.body,\n data: {\n metadata: options.comment.metadata,\n userId: this.userId,\n },\n });\n\n return this.tiptapCommentToCommentData(\n thread.comments[thread.comments.length - 1],\n );\n }\n\n /**\n * Updates a comment in a thread.\n */\n public async updateComment(options: {\n comment: {\n body: CommentBody;\n metadata?: any;\n };\n threadId: string;\n commentId: string;\n }) {\n const comment = this.provider.getThreadComment(\n options.threadId,\n options.commentId,\n true,\n );\n\n if (!comment) {\n throw new Error(\"Comment not found\");\n }\n\n this.provider.updateComment(options.threadId, options.commentId, {\n content: options.comment.body,\n data: {\n ...comment.data,\n metadata: options.comment.metadata,\n },\n });\n }\n\n private tiptapCommentToCommentData(comment: TCollabComment): CommentData {\n const reactions: CommentReactionData[] = [];\n\n for (const reaction of (comment.data?.reactions ||\n []) as ReactionAsTiptapData[]) {\n const existingReaction = reactions.find(\n (r) => r.emoji === reaction.emoji,\n );\n if (existingReaction) {\n existingReaction.userIds.push(reaction.userId);\n existingReaction.createdAt = new Date(\n Math.min(existingReaction.createdAt.getTime(), reaction.createdAt),\n );\n } else {\n reactions.push({\n emoji: reaction.emoji,\n createdAt: new Date(reaction.createdAt),\n userIds: [reaction.userId],\n });\n }\n }\n\n return {\n type: \"comment\",\n id: comment.id,\n body: comment.content,\n metadata: comment.data?.metadata,\n userId: comment.data?.userId,\n createdAt: new Date(comment.createdAt),\n updatedAt: new Date(comment.updatedAt),\n reactions,\n };\n }\n\n private tiptapThreadToThreadData(thread: TCollabThread): ThreadData {\n return {\n type: \"thread\",\n id: thread.id,\n comments: thread.comments.map((comment) =>\n this.tiptapCommentToCommentData(comment),\n ),\n resolved: !!thread.resolvedAt,\n metadata: thread.data?.metadata,\n createdAt: new Date(thread.createdAt),\n updatedAt: new Date(thread.updatedAt),\n };\n }\n\n /**\n * Deletes a comment from a thread.\n */\n public async deleteComment(options: { threadId: string; commentId: string }) {\n this.provider.deleteComment(options.threadId, options.commentId);\n }\n\n /**\n * Deletes a thread.\n */\n public async deleteThread(options: { threadId: string }) {\n this.provider.deleteThread(options.threadId);\n }\n\n /**\n * Marks a thread as resolved.\n */\n public async resolveThread(options: { threadId: string }) {\n this.provider.updateThread(options.threadId, {\n resolvedAt: new Date().toISOString(),\n });\n }\n\n /**\n * Marks a thread as unresolved.\n */\n public async unresolveThread(options: { threadId: string }) {\n this.provider.updateThread(options.threadId, {\n resolvedAt: null,\n });\n }\n\n /**\n * Adds a reaction to a comment.\n *\n * Auth: should be possible by anyone with comment access\n */\n public async addReaction(options: {\n threadId: string;\n commentId: string;\n emoji: string;\n }) {\n const comment = this.provider.getThreadComment(\n options.threadId,\n options.commentId,\n true,\n );\n\n if (!comment) {\n throw new Error(\"Comment not found\");\n }\n\n this.provider.updateComment(options.threadId, options.commentId, {\n data: {\n ...comment.data,\n reactions: [\n ...((comment.data?.reactions || []) as ReactionAsTiptapData[]),\n {\n emoji: options.emoji,\n createdAt: Date.now(),\n userId: this.userId,\n },\n ],\n },\n });\n }\n\n /**\n * Deletes a reaction from a comment.\n *\n * Auth: should be possible by the reaction author\n */\n public async deleteReaction(options: {\n threadId: string;\n commentId: string;\n emoji: string;\n }) {\n const comment = this.provider.getThreadComment(\n options.threadId,\n options.commentId,\n true,\n );\n\n if (!comment) {\n throw new Error(\"Comment not found\");\n }\n\n this.provider.updateComment(options.threadId, options.commentId, {\n data: {\n ...comment.data,\n reactions: (\n (comment.data?.reactions || []) as ReactionAsTiptapData[]\n ).filter(\n (reaction) =>\n reaction.emoji !== options.emoji && reaction.userId !== this.userId,\n ),\n },\n });\n }\n\n public getThread(threadId: string): ThreadData {\n const thread = this.provider.getThread(threadId);\n\n if (!thread) {\n throw new Error(\"Thread not found\");\n }\n\n return this.tiptapThreadToThreadData(thread);\n }\n\n public getThreads(): Map<string, ThreadData> {\n return new Map(\n this.provider\n .getThreads()\n .map((thread) => [thread.id, this.tiptapThreadToThreadData(thread)]),\n );\n }\n\n public subscribe(cb: (threads: Map<string, ThreadData>) => void): () => void {\n const newCb = () => {\n cb(this.getThreads());\n };\n this.provider.watchThreads(newCb);\n return () => {\n this.provider.unwatchThreads(newCb);\n };\n }\n}\n","import * as Y from \"yjs\";\nimport { CommentData, CommentReactionData, ThreadData } from \"../../types.js\";\n\nexport function commentToYMap(comment: CommentData) {\n const yMap = new Y.Map<any>();\n yMap.set(\"id\", comment.id);\n yMap.set(\"userId\", comment.userId);\n yMap.set(\"createdAt\", comment.createdAt.getTime());\n yMap.set(\"updatedAt\", comment.updatedAt.getTime());\n if (comment.deletedAt) {\n yMap.set(\"deletedAt\", comment.deletedAt.getTime());\n yMap.set(\"body\", undefined);\n } else {\n yMap.set(\"body\", comment.body);\n }\n if (comment.reactions.length > 0) {\n throw new Error(\"Reactions should be empty in commentToYMap\");\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 yMapToReactions).\n */\n yMap.set(\"reactionsByUser\", new Y.Map());\n yMap.set(\"metadata\", comment.metadata);\n\n return yMap;\n}\n\nexport function threadToYMap(thread: ThreadData) {\n const yMap = new Y.Map();\n yMap.set(\"id\", thread.id);\n yMap.set(\"createdAt\", thread.createdAt.getTime());\n yMap.set(\"updatedAt\", thread.updatedAt.getTime());\n const commentsArray = new Y.Array<Y.Map<any>>();\n\n commentsArray.push(thread.comments.map((comment) => commentToYMap(comment)));\n\n yMap.set(\"comments\", commentsArray);\n yMap.set(\"resolved\", thread.resolved);\n yMap.set(\"resolvedUpdatedAt\", thread.resolvedUpdatedAt?.getTime());\n yMap.set(\"resolvedBy\", thread.resolvedBy);\n yMap.set(\"metadata\", thread.metadata);\n return yMap;\n}\n\ntype SingleUserCommentReactionData = {\n emoji: string;\n createdAt: Date;\n userId: string;\n};\n\nexport function yMapToReaction(\n yMap: Y.Map<any>,\n): SingleUserCommentReactionData {\n return {\n emoji: yMap.get(\"emoji\"),\n createdAt: new Date(yMap.get(\"createdAt\")),\n userId: yMap.get(\"userId\"),\n };\n}\n\nfunction yMapToReactions(yMap: Y.Map<any>): CommentReactionData[] {\n const flatReactions = [...yMap.values()].map((reaction: Y.Map<any>) =>\n yMapToReaction(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 yMapToComment(yMap: Y.Map<any>): CommentData {\n return {\n type: \"comment\",\n id: yMap.get(\"id\"),\n userId: yMap.get(\"userId\"),\n createdAt: new Date(yMap.get(\"createdAt\")),\n updatedAt: new Date(yMap.get(\"updatedAt\")),\n deletedAt: yMap.get(\"deletedAt\")\n ? new Date(yMap.get(\"deletedAt\"))\n : undefined,\n reactions: yMapToReactions(yMap.get(\"reactionsByUser\")),\n metadata: yMap.get(\"metadata\"),\n body: yMap.get(\"body\"),\n };\n}\n\nexport function yMapToThread(yMap: Y.Map<any>): ThreadData {\n return {\n type: \"thread\",\n id: yMap.get(\"id\"),\n createdAt: new Date(yMap.get(\"createdAt\")),\n updatedAt: new Date(yMap.get(\"updatedAt\")),\n comments: ((yMap.get(\"comments\") as Y.Array<Y.Map<any>>) || []).map(\n (comment) => yMapToComment(comment),\n ),\n resolved: yMap.get(\"resolved\"),\n resolvedUpdatedAt: new Date(yMap.get(\"resolvedUpdatedAt\")),\n resolvedBy: yMap.get(\"resolvedBy\"),\n metadata: yMap.get(\"metadata\"),\n };\n}\n","import * as Y from \"yjs\";\nimport { ThreadData } from \"../../types.js\";\nimport { ThreadStore } from \"../ThreadStore.js\";\nimport { ThreadStoreAuth } from \"../ThreadStoreAuth.js\";\nimport { yMapToThread } 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 Yjs Map.\n */\nexport abstract class YjsThreadStoreBase extends ThreadStore {\n constructor(\n protected readonly threadsYMap: Y.Map<any>,\n auth: ThreadStoreAuth,\n ) {\n super(auth);\n }\n\n // TODO: async / reactive interface?\n public getThread(threadId: string) {\n const yThread = this.threadsYMap.get(threadId);\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n const thread = yMapToThread(yThread);\n return thread;\n }\n\n public getThreads(): Map<string, ThreadData> {\n const threadMap = new Map<string, ThreadData>();\n this.threadsYMap.forEach((yThread, id) => {\n if (yThread instanceof Y.Map) {\n threadMap.set(id, yMapToThread(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.threadsYMap.observeDeep(observer);\n\n return () => {\n this.threadsYMap.unobserveDeep(observer);\n };\n }\n}\n","import * as Y from \"yjs\";\nimport { CommentBody } from \"../../types.js\";\nimport { ThreadStoreAuth } from \"../ThreadStoreAuth.js\";\nimport { YjsThreadStoreBase } from \"./YjsThreadStoreBase.js\";\n\n/**\n * This is a REST-based implementation of the YjsThreadStoreBase.\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 threadsYMap: Y.Map<any>,\n auth: ThreadStoreAuth,\n ) {\n super(threadsYMap, 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 prosemirror: {\n head: number;\n anchor: number;\n };\n yjs: {\n head: any;\n anchor: any;\n };\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 \"yjs\";\nimport { CommentBody, CommentData, ThreadData } from \"../../types.js\";\nimport { ThreadStoreAuth } from \"../ThreadStoreAuth.js\";\nimport { YjsThreadStoreBase } from \"./YjsThreadStoreBase.js\";\nimport {\n commentToYMap,\n threadToYMap,\n yMapToComment,\n yMapToThread,\n} from \"./yjsHelpers.js\";\n\n/**\n * This is a Yjs-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 threadsYMap: Y.Map<any>,\n auth: ThreadStoreAuth,\n ) {\n super(threadsYMap, 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.threadsYMap.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.threadsYMap.set(thread.id, threadToYMap(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.threadsYMap.get(options.threadId);\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n if (!this.auth.canAddComment(yMapToThread(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.get(\"comments\") as Y.Array<Y.Map<any>>).push([\n commentToYMap(comment),\n ]);\n\n yThread.set(\"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.threadsYMap.get(options.threadId);\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n const yCommentIndex = yArrayFindIndex(\n yThread.get(\"comments\"),\n (comment) => comment.get(\"id\") === options.commentId,\n );\n\n if (yCommentIndex === -1) {\n throw new Error(\"Comment not found\");\n }\n\n const yComment = yThread.get(\"comments\").get(yCommentIndex);\n\n if (!this.auth.canUpdateComment(yMapToComment(yComment))) {\n throw new Error(\"Not authorized\");\n }\n\n yComment.set(\"body\", options.comment.body);\n yComment.set(\"updatedAt\", new Date().getTime());\n yComment.set(\"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.threadsYMap.get(options.threadId);\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n const yCommentIndex = yArrayFindIndex(\n yThread.get(\"comments\"),\n (comment) => comment.get(\"id\") === options.commentId,\n );\n\n if (yCommentIndex === -1) {\n throw new Error(\"Comment not found\");\n }\n\n const yComment = yThread.get(\"comments\").get(yCommentIndex);\n\n if (!this.auth.canDeleteComment(yMapToComment(yComment))) {\n throw new Error(\"Not authorized\");\n }\n\n if (yComment.get(\"deletedAt\")) {\n throw new Error(\"Comment already deleted\");\n }\n\n if (options.softDelete) {\n yComment.set(\"deletedAt\", new Date().getTime());\n yComment.set(\"body\", undefined);\n } else {\n yThread.get(\"comments\").delete(yCommentIndex);\n }\n\n if (\n (yThread.get(\"comments\") as Y.Array<any>)\n .toArray()\n .every((comment) => comment.get(\"deletedAt\"))\n ) {\n // all comments deleted\n if (options.softDelete) {\n yThread.set(\"deletedAt\", new Date().getTime());\n } else {\n this.threadsYMap.delete(options.threadId);\n }\n }\n\n yThread.set(\"updatedAt\", new Date().getTime());\n },\n );\n\n public deleteThread = this.transact((options: { threadId: string }) => {\n if (\n !this.auth.canDeleteThread(\n yMapToThread(this.threadsYMap.get(options.threadId)),\n )\n ) {\n throw new Error(\"Not authorized\");\n }\n\n this.threadsYMap.delete(options.threadId);\n });\n\n public resolveThread = this.transact((options: { threadId: string }) => {\n const yThread = this.threadsYMap.get(options.threadId);\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n if (!this.auth.canResolveThread(yMapToThread(yThread))) {\n throw new Error(\"Not authorized\");\n }\n\n yThread.set(\"resolved\", true);\n yThread.set(\"resolvedUpdatedAt\", new Date().getTime());\n yThread.set(\"resolvedBy\", this.userId);\n });\n\n public unresolveThread = this.transact((options: { threadId: string }) => {\n const yThread = this.threadsYMap.get(options.threadId);\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n if (!this.auth.canUnresolveThread(yMapToThread(yThread))) {\n throw new Error(\"Not authorized\");\n }\n\n yThread.set(\"resolved\", false);\n yThread.set(\"resolvedUpdatedAt\", new Date().getTime());\n });\n\n public addReaction = this.transact(\n (options: { threadId: string; commentId: string; emoji: string }) => {\n const yThread = this.threadsYMap.get(options.threadId);\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n const yCommentIndex = yArrayFindIndex(\n yThread.get(\"comments\"),\n (comment) => comment.get(\"id\") === options.commentId,\n );\n\n if (yCommentIndex === -1) {\n throw new Error(\"Comment not found\");\n }\n\n const yComment = yThread.get(\"comments\").get(yCommentIndex);\n\n if (!this.auth.canAddReaction(yMapToComment(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.get(\"reactionsByUser\");\n\n if (reactionsByUser.has(key)) {\n // already exists\n return;\n } else {\n const reaction = new Y.Map();\n reaction.set(\"emoji\", options.emoji);\n reaction.set(\"createdAt\", date.getTime());\n reaction.set(\"userId\", this.userId);\n reactionsByUser.set(key, reaction);\n }\n },\n );\n\n public deleteReaction = this.transact(\n (options: { threadId: string; commentId: string; emoji: string }) => {\n const yThread = this.threadsYMap.get(options.threadId);\n if (!yThread) {\n throw new Error(\"Thread not found\");\n }\n\n const yCommentIndex = yArrayFindIndex(\n yThread.get(\"comments\"),\n (comment) => comment.get(\"id\") === options.commentId,\n );\n\n if (yCommentIndex === -1) {\n throw new Error(\"Comment not found\");\n }\n\n const yComment = yThread.get(\"comments\").get(yCommentIndex);\n\n if (\n !this.auth.canDeleteReaction(yMapToComment(yComment), options.emoji)\n ) {\n throw new Error(\"Not authorized\");\n }\n\n const key = `${this.userId}-${options.emoji}`;\n\n const reactionsByUser = yComment.get(\"reactionsByUser\");\n\n reactionsByUser.delete(key);\n },\n );\n}\n\nfunction yArrayFindIndex(\n yArray: Y.Array<any>,\n predicate: (item: any) => boolean,\n) {\n for (let i = 0; i < yArray.length; i++) {\n if (predicate(yArray.get(i))) {\n return i;\n }\n }\n return -1;\n}\n"],"mappings":";;;;;;;;;;AAEA,IAAa,IAAc,EAAK,OAAO;CACrC,MAAM;CACN,UAAU;CACV,WAAW;CACX,aAAa;CAEb,gBAAgB;AAEd,SAAO;GAKL,QAAQ;IACN,YAAY,MAAY,CAAC,CAAC,EAAQ,aAAa,cAAc;IAC7D,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MAAkB,GACpB,OAAU,MAAM,oBAAoB;EAGtC,IAAM,IAAW,EAAQ,IAAI,WAAW,CAAC,IAAI,EAAc;AAE3D,MACE,CAAC,KAAK,KAAK,kBAAkB,EAAc,EAAS,EAAE,EAAQ,MAAM,CAEpE,OAAU,MAAM,iBAAiB;EAGnC,IAAM,IAAM,GAAG,KAAK,OAAO,GAAG,EAAQ;AAEd,IAAS,IAAI,kBAAkB,CAEvC,OAAO,EAAI;GAE9B;;AAGH,SAAS,EACP,GACA,GACA;AACA,MAAK,IAAI,IAAI,GAAG,IAAI,EAAO,QAAQ,IACjC,KAAI,EAAU,EAAO,IAAI,EAAE,CAAC,CAC1B,QAAO;AAGX,QAAO"}
@@ -0,0 +1,2 @@
1
+ const e=require(`./BlockNoteExtension-ab0REuob.cjs`),t=require(`./blocks-_lpGWKOa.cjs`);let n=require(`prosemirror-model`),r=require(`prosemirror-transform`),i=require(`@tiptap/core`),a=require(`prosemirror-state`),o=require(`lib0/random`),s=require(`@tiptap/pm/model`),c=require(`prosemirror-tables`),l=require(`@tiptap/pm/state`),u=require(`prosemirror-view`),d=require(`y-prosemirror`),f=require(`fast-deep-equal`);f=e.i(f,1);let p=require(`yjs`);p=e.i(p,1);let m=require(`@tiptap/pm/history`),h=require(`rehype-parse`);h=e.i(h,1);let g=require(`rehype-remark`);g=e.i(g,1);let _=require(`remark-gfm`);_=e.i(_,1);let v=require(`remark-stringify`);v=e.i(v,1);let ee=require(`unified`),te=require(`hast-util-from-dom`),ne=require(`unist-util-visit`);function y(e){let t=Array.from(e.classList).filter(e=>!e.startsWith(`bn-`))||[];t.length>0?e.className=t.join(` `):e.removeAttribute(`class`)}function b(e,r,i,a){let o;if(!r)throw Error(`blockContent is required`);if(typeof r==`string`)o=t.kt([r],e.pmSchema);else if(Array.isArray(r))o=t.kt(r,e.pmSchema);else if(r.type===`tableContent`)o=t.At(r,e.pmSchema);else throw new t.Rn(r.type);let s=(a?.document??document).createDocumentFragment();for(let r of o)if(r.type.name!==`text`&&e.schema.inlineContentSchema[r.type.name]){let n=e.schema.inlineContentSpecs[r.type.name].implementation;if(n){let o=t.an(r,e.schema.inlineContentSchema,e.schema.styleSchema),c=n.toExternalHTML?n.toExternalHTML(o,e):n.render.call({renderType:`dom`,props:void 0},o,()=>{},e);if(c){if(s.appendChild(c.dom),c.contentDOM){let e=i.serializeFragment(r.content,a);c.contentDOM.dataset.editable=``,c.contentDOM.appendChild(e)}continue}}}else if(r.type.name===`text`){let t=document.createTextNode(r.textContent);for(let i of r.marks.toReversed())if(i.type.name in e.schema.styleSpecs){let n=(e.schema.styleSpecs[i.type.name].implementation.toExternalHTML??e.schema.styleSpecs[i.type.name].implementation.render)(i.attrs.stringValue,e);n.contentDOM.appendChild(t),t=n.dom}else{let e=i.type.spec.toDOM(i,!0),r=n.DOMSerializer.renderSpec(document,e);r.contentDOM.appendChild(t),t=r.dom}s.appendChild(t)}else{let e=i.serializeFragment(n.Fragment.from([r]),a);s.appendChild(e)}return s.childNodes.length===1&&s.firstChild?.nodeType===1&&y(s.firstChild),s}function re(e,t,n,r,i,a,o,s){let c=s?.document??document,l=t.pmSchema.nodes.blockContainer,u=n.props||{};for(let[e,r]of Object.entries(t.schema.blockSchema[n.type].propSchema))!(e in u)&&r.default!==void 0&&(u[e]=r.default);let d=l.spec?.toDOM?.(l.create({id:n.id,...u})),f=Array.from(d.dom.attributes),p=t.blockImplementations[n.type].implementation,m=p.toExternalHTML?.call({},{...n,props:u},t,{nestingLevel:o})||p.render.call({},{...n,props:u},t),h=c.createDocumentFragment();if(m.dom.classList.contains(`bn-block-content`)){let e=[...f,...Array.from(m.dom.attributes)].filter(e=>e.name.startsWith(`data`)&&e.name!==`data-content-type`&&e.name!==`data-file-block`&&e.name!==`data-node-view-wrapper`&&e.name!==`data-node-type`&&e.name!==`data-id`&&e.name!==`data-editable`);for(let t of e)m.dom.firstChild.setAttribute(t.name,t.value);y(m.dom.firstChild),o>0&&m.dom.firstChild.setAttribute(`data-nesting-level`,o.toString()),h.append(...Array.from(m.dom.childNodes))}else h.append(m.dom),o>0&&m.dom.setAttribute(`data-nesting-level`,o.toString());if(m.contentDOM&&n.content){let e=b(t,n.content,r,s);m.contentDOM.appendChild(e)}let g;if(i.has(n.type)?g=`OL`:a.has(n.type)&&(g=`UL`),g){if(e.lastChild?.nodeName!==g){let t=c.createElement(g);g===`OL`&&`start`in u&&u.start&&u?.start!==1&&t.setAttribute(`start`,u.start+``),e.append(t)}e.lastChild.appendChild(h)}else e.append(h);if(n.children&&n.children.length>0){let l=c.createDocumentFragment();if(x(l,t,n.children,r,i,a,o+1,s),e.lastChild?.nodeName===`UL`||e.lastChild?.nodeName===`OL`)for(;l.firstChild?.nodeName===`UL`||l.firstChild?.nodeName===`OL`;)e.lastChild.lastChild.appendChild(l.firstChild);`childrenDOM`in m&&m.childrenDOM?m.childrenDOM.append(l):t.pmSchema.nodes[n.type].isInGroup(`blockContent`)?e.append(l):m.contentDOM?.append(l)}}var x=(e,t,n,r,i,a,o=0,s)=>{for(let c of n)re(e,t,c,r,i,a,o,s)},ie=(e,t,n,r,i,a)=>{let o=(a?.document??document).createDocumentFragment();return x(o,e,t,n,r,i,0,a),o},S=(e,t)=>{let r=n.DOMSerializer.fromSchema(e);return{exportBlocks:(e,n)=>{let i=ie(t,e,r,new Set([`numberedListItem`]),new Set([`bulletListItem`,`checkListItem`,`toggleListItem`]),n),a=document.createElement(`div`);return a.append(i),a.innerHTML},exportInlineContent:(e,n)=>{let i=b(t,e,r,n),a=document.createElement(`div`);return a.append(i.cloneNode(!0)),a.innerHTML}}};function ae(e,n){if(n===0)return;let r=e.resolve(n);for(let e=r.depth;e>0;e--){let n=r.node(e);if(t.Dt(n))return n.attrs.id}}function oe(e){return e.getMeta(`paste`)?{type:`paste`}:e.getMeta(`uiEvent`)===`drop`?{type:`drop`}:e.getMeta(`history$`)?{type:e.getMeta(`history$`).redo?`redo`:`undo`}:e.getMeta(`y-sync$`)?e.getMeta(`y-sync$`).isUndoRedoOperation?{type:`undo-redo`}:{type:`yjs-remote`}:{type:`local`}}function C(e){let n={},r={},i=t.dn(e);return e.descendants((a,o)=>{if(!t.Dt(a))return!0;let s=ae(e,o),c=s??`__root__`;r[c]||(r[c]=[]);let l=t.in(a,i);return n[a.attrs.id]={block:l,parentId:s},r[c].push(a.attrs.id),!0}),{byId:n,childrenByParent:r}}function se(e,t){let n=new Set;if(!e||!t)return n;let r=new Set(e),i=t.filter(e=>r.has(e)),a=e.filter(e=>i.includes(e));if(a.length<=1||i.length<=1)return n;let o={};for(let e=0;e<a.length;e++)o[a[e]]=e;let s=i.map(e=>o[e]),c=s.length,l=[],u=[],d=Array(c).fill(-1),f=(e,t)=>{let n=0,r=e.length;for(;n<r;){let i=n+r>>>1;e[i]<t?n=i+1:r=i}return n};for(let e=0;e<c;e++){let t=s[e],n=f(l,t);n>0&&(d[e]=u[n-1]),n===l.length?(l.push(t),u.push(e)):(l[n]=t,u[n]=e)}let p=new Set,m=u[u.length-1]??-1;for(;m!==-1;)p.add(m),m=d[m];for(let e=0;e<i.length;e++)p.has(e)||n.add(i[e]);return n}function w(e,t=[]){let n=oe(e),r=(0,i.combineTransactionSteps)(e.before,[e,...t]),a=C(r.before),o=C(r.doc),s=[],c=new Set;Object.keys(o.byId).filter(e=>!(e in a.byId)).forEach(e=>{s.push({type:`insert`,block:o.byId[e].block,source:n,prevBlock:void 0}),c.add(e)}),Object.keys(a.byId).filter(e=>!(e in o.byId)).forEach(e=>{s.push({type:`delete`,block:a.byId[e].block,source:n,prevBlock:void 0}),c.add(e)}),Object.keys(o.byId).filter(e=>e in a.byId).forEach(e=>{let t=a.byId[e],r=o.byId[e];t.parentId===r.parentId?(0,f.default)({...t.block,children:void 0},{...r.block,children:void 0})||(s.push({type:`update`,block:r.block,prevBlock:t.block,source:n}),c.add(e)):(s.push({type:`move`,block:r.block,prevBlock:t.block,source:n,prevParent:t.parentId?a.byId[t.parentId]?.block:void 0,currentParent:r.parentId?o.byId[r.parentId]?.block:void 0}),c.add(e))});let l=a.childrenByParent,u=o.childrenByParent,d=new Set([...Object.keys(l),...Object.keys(u)]),p=new Set;return d.forEach(e=>{let t=se(l[e],u[e]);t.size!==0&&t.forEach(t=>{let r=a.byId[t],i=o.byId[t];!r||!i||r.parentId===i.parentId&&(c.has(t)||(r.parentId??`__root__`)===e&&(p.has(t)||(p.add(t),s.push({type:`move`,block:i.block,prevBlock:r.block,source:n,prevParent:r.parentId?a.byId[r.parentId]?.block:void 0,currentParent:i.parentId?o.byId[i.parentId]?.block:void 0}),c.add(t))))})}),s}var ce=e.t(()=>{let e=[];return{key:`blockChange`,prosemirrorPlugins:[new a.Plugin({key:new a.PluginKey(`blockChange`),filterTransaction:t=>{let n;return e.reduce((e,r)=>e===!1?e:r({getChanges(){return n||(n=w(t),n)},tr:t})!==!1,!0)}})],subscribe(t){return e.push(t),()=>{e.splice(e.indexOf(t),1)}}}});function T(e){let t=e.charAt(0)===`#`?e.substring(1,7):e,n=parseInt(t.substring(0,2),16),r=parseInt(t.substring(2,4),16),i=parseInt(t.substring(4,6),16),a=[n/255,r/255,i/255].map(e=>e<=.03928?e/12.92:((e+.055)/1.055)**2.4);return .2126*a[0]+.7152*a[1]+.0722*a[2]<=.179}function le(e){let t=document.createElement(`span`);t.classList.add(`bn-collaboration-cursor__base`);let n=document.createElement(`span`);n.setAttribute(`contentedEditable`,`false`),n.classList.add(`bn-collaboration-cursor__caret`),n.setAttribute(`style`,`background-color: ${e.color}; color: ${T(e.color)?`white`:`black`}`);let r=document.createElement(`span`);return r.classList.add(`bn-collaboration-cursor__label`),r.setAttribute(`style`,`background-color: ${e.color}; color: ${T(e.color)?`white`:`black`}`),r.insertBefore(document.createTextNode(e.name),null),n.insertBefore(r,null),t.insertBefore(document.createTextNode(`⁠`),null),t.insertBefore(n,null),t.insertBefore(document.createTextNode(`⁠`),null),t}var E=e.t(({options:e})=>{let t=new Map,n=e.provider&&`awareness`in e.provider&&typeof e.provider.awareness==`object`?e.provider.awareness:void 0;return n&&(`setLocalStateField`in n&&typeof n.setLocalStateField==`function`&&n.setLocalStateField(`user`,e.user),`on`in n&&typeof n.on==`function`&&e.showCursorLabels!==`always`&&n.on(`change`,({updated:e})=>{for(let n of e){let e=t.get(n);e&&(setTimeout(()=>{e.element.setAttribute(`data-active`,``)},10),e.hideTimeout&&clearTimeout(e.hideTimeout),t.set(n,{element:e.element,hideTimeout:setTimeout(()=>{e.element.removeAttribute(`data-active`)},2e3)}))}})),{key:`yCursor`,prosemirrorPlugins:[n?(0,d.yCursorPlugin)(n,{selectionBuilder:d.defaultSelectionBuilder,cursorBuilder(n,r){let i=t.get(r);if(!i){let a=(e.renderCursor??le)(n);e.showCursorLabels!==`always`&&(a.addEventListener(`mouseenter`,()=>{let e=t.get(r);e.element.setAttribute(`data-active`,``),e.hideTimeout&&(clearTimeout(e.hideTimeout),t.set(r,{element:e.element,hideTimeout:void 0}))}),a.addEventListener(`mouseleave`,()=>{let e=t.get(r);t.set(r,{element:e.element,hideTimeout:setTimeout(()=>{e.element.removeAttribute(`data-active`)},2e3)})})),i={element:a,hideTimeout:void 0},t.set(r,i)}return i.element}}):void 0].filter(Boolean),dependsOn:[`ySync`],updateUser(e){n?.setLocalStateField(`user`,e)}}}),D=e.t(({options:e})=>({key:`ySync`,prosemirrorPlugins:[(0,d.ySyncPlugin)(e.fragment)],runsBefore:[`default`]})),O=e.t(()=>({key:`yUndo`,prosemirrorPlugins:[(0,d.yUndoPlugin)()],dependsOn:[`yCursor`,`ySync`],undoCommand:d.undoCommand,redoCommand:d.redoCommand}));function ue(e,t){let n=e.doc;if(e._item===null){let r=Array.from(n.share.keys()).find(t=>n.share.get(t)===e);if(r==null)throw Error(`type does not exist in other ydoc`);return t.get(r,e.constructor)}else{let n=e._item,r=t.store.clients.get(n.id.client)??[];return r[p.findIndexSS(r,n.id.clock)].content.type}}var de=e.t(({editor:t,options:n})=>{let r,i=e.n({isForked:!1});return{key:`yForkDoc`,store:i,fork(){if(r)return;let e=n.fragment;if(!e)throw Error(`No fragment to fork from`);let a=new p.Doc;p.applyUpdate(a,p.encodeStateAsUpdate(e.doc));let o=ue(e,a);r={undoStack:d.yUndoPluginKey.getState(t.prosemirrorState).undoManager.undoStack,originalFragment:e,forkedFragment:o},t.unregisterExtension([O,E,D]);let s={...n,fragment:o};t.registerExtension([D(s),O()]),i.setState({isForked:!0})},merge({keepChanges:e}){if(!r)return;t.unregisterExtension([`ySync`,`yCursor`,`yUndo`]);let{originalFragment:a,forkedFragment:o,undoStack:s}=r;if(t.registerExtension([D(n),E(n),O()]),d.yUndoPluginKey.getState(t.prosemirrorState).undoManager.undoStack=s,e){let e=p.encodeStateAsUpdate(o.doc,p.encodeStateVector(a.doc));p.applyUpdate(a.doc,e,t)}r=void 0,i.setState({isForked:!1})}}}),k=(e,t)=>{t(e),e.forEach(e=>{e instanceof p.XmlElement&&k(e,t)})},fe=[(e,n)=>{let r=new Map;return e.forEach(e=>{e instanceof p.XmlElement&&k(e,e=>{if(e.nodeName===`blockContainer`&&e.hasAttribute(`id`)){let n=e.getAttribute(`textColor`),i=e.getAttribute(`backgroundColor`),a={textColor:n===t.ht.textColor.default?void 0:n,backgroundColor:i===t.ht.backgroundColor.default?void 0:i};(a.textColor||a.backgroundColor)&&r.set(e.getAttribute(`id`),a)}})}),r.size===0?!1:(n.doc.descendants((e,t)=>{if(e.type.name===`blockContainer`&&r.has(e.attrs.id)){let i=n.doc.nodeAt(t+1);if(!i)throw Error(`No element found`);n.setNodeMarkup(t+1,void 0,{...i.attrs,...r.get(e.attrs.id)})}}),!0)}],pe=e.t(({options:e})=>{let t=!1;return{key:`schemaMigration`,prosemirrorPlugins:[new l.Plugin({key:new l.PluginKey(`schemaMigration`),appendTransaction:(n,r,i)=>{if(t||!n.some(e=>e.getMeta(`y-sync$`))||n.every(e=>!e.docChanged)||!e.fragment.firstChild)return;let a=i.tr;for(let t of fe)t(e.fragment,a);if(t=!0,a.docChanged)return a}})]}});function A(e,t){return!e||!t?!1:!!e.closest(`.${t}`)}function me(e,t,n,r,i){let a=e.state.doc.resolve(t.pos);if(a.parent.inlineContent||t.orientation===`inline`)return null;let o=a.nodeBefore,s=a.nodeAfter;if(!o&&!s)return null;let c=t.orientation===`block-vertical-left`||t.orientation===`block-vertical-right`,l=c?t.pos:t.pos-(o?o.nodeSize:0),u=e.nodeDOM(l);if(!u)return null;let d=u.getBoundingClientRect();if(c){let e=n/2*r,i=t.orientation===`block-vertical-left`?d.left:d.right;return{left:i-e,right:i+e,top:d.top,bottom:d.bottom}}let f=o?d.bottom:d.top;o&&s&&(f=(f+e.nodeDOM(t.pos).getBoundingClientRect().top)/2);let p=n/2*i;return{left:d.left,right:d.right,top:f-p,bottom:f+p}}function he(e,t,n,r){let i=e.coordsAtPos(t.pos),a=n/2*r;return{left:i.left-a,right:i.left+a,top:i.top,bottom:i.bottom}}function ge(e,t){e.classList.toggle(`prosemirror-dropcursor-inline`,t===`inline`),e.classList.toggle(`prosemirror-dropcursor-block-horizontal`,t===`block-horizontal`),e.classList.toggle(`prosemirror-dropcursor-block-vertical-left`,t===`block-vertical-left`),e.classList.toggle(`prosemirror-dropcursor-block-vertical-right`,t===`block-vertical-right`),e.classList.toggle(`prosemirror-dropcursor-block`,t===`block-horizontal`),e.classList.toggle(`prosemirror-dropcursor-vertical`,t===`block-vertical-left`||t===`block-vertical-right`)}function _e(e){if(!e||e===document.body&&getComputedStyle(e).position===`static`)return{parentLeft:-window.pageXOffset,parentTop:-window.pageYOffset};let t=e.getBoundingClientRect(),n=t.width/e.offsetWidth,r=t.height/e.offsetHeight;return{parentLeft:t.left-e.scrollLeft*n,parentTop:t.top-e.scrollTop*r}}var ve=`bn-drag-exclude`,ye=e.t(({editor:e,options:t})=>{let n=null,i=null,a=-1,o=null,s={width:t.dropCursor?.width??5,color:t.dropCursor?.color??`#ddeeff`,exclude:t.dropCursor?.exclude??`bn-drag-exclude`,hooks:t.dropCursor?.hooks},c=e=>{e?.pos===n?.pos&&e?.orientation===n?.orientation||(n=e,e==null?(i&&i.parentNode&&i.parentNode.removeChild(i),i=null):l())},l=()=>{if(!n)return;let t=e.prosemirrorView,r=t.dom,a=r.getBoundingClientRect(),o=a.width/r.offsetWidth,c=a.height/r.offsetHeight,l=me(t,n,s.width,o,c)??he(t,n,s.width,o),u=t.dom.offsetParent;i||(i=u.appendChild(document.createElement(`div`)),i.style.cssText=`position: absolute; z-index: 50; pointer-events: none;`,s.color&&(i.style.backgroundColor=s.color)),ge(i,n.orientation);let{parentLeft:d,parentTop:f}=_e(u);i.style.left=(l.left-d)/o+`px`,i.style.top=(l.top-f)/c+`px`,i.style.width=(l.right-l.left)/o+`px`,i.style.height=(l.bottom-l.top)/c+`px`},u=e=>{clearTimeout(a),a=window.setTimeout(()=>c(null),e)},d=e=>{let t=e;o=t.target instanceof Element?t.target:null},f=t=>{let n=t;if(o&&A(o,s.exclude)||n.target instanceof Element&&A(n.target,s.exclude))return;let i=e.prosemirrorView;if(!i.editable)return;let a=i.posAtCoords({left:n.clientX,top:n.clientY}),l=a&&a.inside>=0&&i.state.doc.nodeAt(a.inside),d=l&&l.type.spec.disableDropCursor,f=typeof d==`function`?d(i,a,n):d;if(a&&!f){let t=a.pos;if(i.dragging&&i.dragging.slice){let e=(0,r.dropPoint)(i.state.doc,t,i.dragging.slice);e!=null&&(t=e)}let o=!i.state.doc.resolve(t).parent.inlineContent,l={pos:t,orientation:o?`block-horizontal`:`inline`},d=l;if(s.hooks?.computeDropPosition){let t=s.hooks.computeDropPosition({editor:e,event:n,view:i,defaultPosition:l});if(t===null){c(null);return}d=t}c(d),u(5e3)}},p=t=>{let n=t;(!(n.relatedTarget instanceof Node)||!e.prosemirrorView.dom.contains(n.relatedTarget))&&c(null)},m=()=>{u(20)},h=()=>{u(20),o=null};return{key:`dropCursor`,mount({signal:e,dom:t,root:n}){n.addEventListener(`dragstart`,d,{capture:!0,signal:e}),t.addEventListener(`dragover`,f,{signal:e}),t.addEventListener(`dragleave`,p,{signal:e}),t.addEventListener(`drop`,m,{signal:e}),t.addEventListener(`dragend`,h,{signal:e}),e.addEventListener(`abort`,()=>{clearTimeout(a),c(null)})}}}),be=e.t(({editor:t})=>{let n=e.n(!1),r=()=>t.transact(e=>{if(e.selection.empty||e.selection instanceof a.TextSelection&&e.doc.textBetween(e.selection.from,e.selection.to).length===0)return!1;let t=!1;return e.selection.content().content.descendants(e=>(e.type.spec.code&&(t=!0),!t)),!t});return{key:`formattingToolbar`,store:n,mount({dom:e,signal:i}){let a=!1,o=!1,s=t.onChange(()=>{a||o||n.setState(r())}),c=t.onSelectionChange(()=>{a||o||n.setState(r())});e.addEventListener(`pointerdown`,()=>{a=!0,n.setState(!1)},{signal:i}),t.prosemirrorView.root.addEventListener(`pointerup`,()=>{a=!1,t.isFocused()&&n.setState(r())},{signal:i,capture:!0}),e.addEventListener(`pointercancel`,()=>{a=!0},{signal:i,capture:!0}),t.prosemirrorView.root.addEventListener(`dragstart`,()=>{o=!0,n.setState(!1)},{signal:i}),t.prosemirrorView.root.addEventListener(`dragend`,()=>{o=!1},{signal:i}),i.addEventListener(`abort`,()=>{s(),c()})}}}),j=e.t(()=>({key:`history`,prosemirrorPlugins:[(0,m.history)()],undoCommand:m.undo,redoCommand:m.redo})),M=e.t(({editor:e})=>{function t(t){let n=e.prosemirrorView.nodeDOM(t);for(;n&&n.parentElement;){if(n.nodeName===`A`)return n;n=n.parentElement}return null}function n(t){let n=e.getLinkMarkAtPos(t);if(n)return{range:{from:n.from,to:n.to},mark:{attrs:{href:n.href}},get text(){return n.text},get position(){return(0,i.posToDOMRect)(e.prosemirrorView,n.from,n.to).toJSON()}}}function r(){return e.transact(e=>{if(e.selection.empty)return n(e.selection.anchor)})}return{key:`linkToolbar`,getLinkAtSelection:r,getLinkElementAtPos:t,getMarkAtPos(e,t){return n(e)},getLinkAtElement(t){return e.transact(()=>n(e.prosemirrorView.posAtDOM(t,0)+1))},editLink(t,n,r=e.transact(e=>e.selection.anchor)){e.editLink(t,n,r)},deleteLink(t=e.transact(e=>e.selection.anchor)){e.deleteLink(t)}}}),N=[`http`,`https`,`ftp`,`ftps`,`mailto`,`tel`,`callto`,`sms`,`cid`,`xmpp`],xe=`https`,Se=new a.PluginKey(`node-selection-keyboard`),Ce=e.t(()=>({key:`nodeSelectionKeyboard`,prosemirrorPlugins:[new a.Plugin({key:Se,props:{handleKeyDown:(e,t)=>{if(`node`in e.state.selection){if(t.ctrlKey||t.metaKey)return!1;if(t.key.length===1)return t.preventDefault(),!0;if(t.key===`Enter`&&!t.isComposing&&!t.shiftKey&&!t.altKey&&!t.ctrlKey&&!t.metaKey){let t=e.state.tr;return e.dispatch(t.insert(e.state.tr.selection.$to.after(),e.state.schema.nodes.paragraph.createChecked()).setSelection(new a.TextSelection(t.doc.resolve(e.state.tr.selection.$to.after()+1)))),!0}}return!1}}})]})),we=new a.PluginKey(`blocknote-placeholder`),Te=e.t(({editor:e,options:t})=>{let n=t.placeholders;return{key:`placeholder`,prosemirrorPlugins:[new a.Plugin({key:we,view:t=>{let r=`placeholder-selector-${(0,o.uuidv4)()}`;t.dom.classList.add(r);let i=document.createElement(`style`),a=e._tiptapEditor.options.injectNonce;a&&i.setAttribute(`nonce`,a),t.root instanceof window.ShadowRoot?t.root.append(i):t.root.head.appendChild(i);let s=i.sheet,c=(e=``)=>`.${r} .bn-block-content${e}:has(.ProseMirror-trailingBreak:only-child):after`;try{let{default:e,emptyDocument:t,...r}=n||{};for(let[e,t]of Object.entries(r)){let n=`[data-content-type="${e}"]`;s.insertRule(`${c(n)} { content: ${JSON.stringify(t)}; }`)}s.insertRule(`${c(`[data-is-only-empty-block]`)} { content: ${JSON.stringify(t)}; }`),s.insertRule(`${c(`[data-is-empty-and-focused]`)} { content: ${JSON.stringify(e)}; }`)}catch(e){console.warn(`Failed to insert placeholder CSS rule - this is likely due to the browser not supporting certain CSS pseudo-element selectors (:has, :only-child:, or :before)`,e)}return{destroy:()=>{t.root instanceof window.ShadowRoot?t.root.removeChild(i):t.root.head.removeChild(i)}}},props:{decorations:t=>{let{doc:n,selection:r}=t;if(!e.isEditable||!r.empty||r.$from.parent.type.spec.code)return;let i=[];t.doc.content.size===6&&i.push(u.Decoration.node(2,4,{"data-is-only-empty-block":`true`}));let a=r.$anchor,o=a.parent;if(o.content.size===0){let e=a.before();i.push(u.Decoration.node(e,e+o.nodeSize,{"data-is-empty-and-focused":`true`}))}return u.DecorationSet.create(n,i)}}})]}}),P=new a.PluginKey(`previous-blocks`),Ee={index:`index`,level:`level`,type:`type`,depth:`depth`,"depth-change":`depth-change`},De=e.t(()=>{let e;return{key:`previousBlockType`,prosemirrorPlugins:[new a.Plugin({key:P,view(t){return{update:async(t,n)=>{this.key?.getState(t.state).updatedBlocks.size>0&&(e=setTimeout(()=>{t.dispatch(t.state.tr.setMeta(P,{clearUpdate:!0}))},0))},destroy:()=>{e&&clearTimeout(e)}}},state:{init(){return{prevTransactionOldBlockAttrs:{},currentTransactionOldBlockAttrs:{},updatedBlocks:new Set}},apply(e,t,n,r){if(t.currentTransactionOldBlockAttrs={},t.updatedBlocks.clear(),!e.docChanged)return t;let a=e.changedRange();if(!a)return t;let o=e.mapping.invert(),s={from:o.map(a.from,-1),to:o.map(a.to,1)},c={},l=(0,i.findChildrenInRange)(n.doc,s,e=>e.attrs.id),u=new Map(l.map(e=>[e.node.attrs.id,e])),d=(0,i.findChildrenInRange)(r.doc,a,e=>e.attrs.id);for(let e of d){let i=u.get(e.node.attrs.id),a=i?.node.firstChild,o=e.node.firstChild;if(i&&a&&o){let s={index:o.attrs.index,level:o.attrs.level,type:o.type.name,depth:r.doc.resolve(e.pos).depth},l={index:a.attrs.index,level:a.attrs.level,type:a.type.name,depth:n.doc.resolve(i.pos).depth};c[e.node.attrs.id]=l,t.currentTransactionOldBlockAttrs[e.node.attrs.id]=l,(l.index!==s.index||l.level!==s.level||l.type!==s.type||l.depth!==s.depth)&&(l[`depth-change`]=l.depth-s.depth,t.updatedBlocks.add(e.node.attrs.id))}}return t.prevTransactionOldBlockAttrs=c,t}},props:{decorations(e){let t=this.getState(e);if(t.updatedBlocks.size===0)return;let n=[];return e.doc.descendants((e,r)=>{if(!e.attrs.id||!t.updatedBlocks.has(e.attrs.id))return;let i=t.currentTransactionOldBlockAttrs[e.attrs.id],a={};for(let[e,t]of Object.entries(i))a[`data-prev-`+Ee[e]]=t||`none`;n.push(u.Decoration.node(r,r+e.nodeSize,{...a}))}),u.DecorationSet.create(e.doc,n)}}})]}});function F(e,t){for(;e&&e.parentElement&&e.parentElement!==t.dom&&e.getAttribute?.(`data-node-type`)!==`blockContainer`;)e=e.parentElement;if(e.getAttribute?.(`data-node-type`)===`blockContainer`)return{node:e,id:e.getAttribute(`data-id`)}}function Oe(){let e=t=>{let n=t.children.length;for(let r=0;r<n;r++){let i=t.children[r];if(i.type===`element`&&(e(i),i.tagName===`u`))if(i.children.length>0){t.children.splice(r,1,...i.children);let e=i.children.length-1;n+=e,r+=e}else t.children.splice(r,1),n--,r--}};return e}function ke(){let e=t=>{if(t.children&&`length`in t.children&&t.children.length)for(let n=t.children.length-1;n>=0;n--){let r=t.children[n],i=n+1<t.children.length?t.children[n+1]:void 0;r.type===`element`&&r.tagName===`input`&&r.properties?.type===`checkbox`&&i?.type===`element`&&i.tagName===`p`?(i.tagName=`span`,i.children.splice(0,0,(0,te.fromDom)(document.createTextNode(` `)))):e(r)}};return e}function Ae(){return e=>{(0,ne.visit)(e,`element`,(e,t,n)=>{if(n&&e.tagName===`video`){let r=e.properties?.src||e.properties?.[`data-url`]||``,i=e.properties?.title||e.properties?.[`data-name`]||``;n.children[t]={type:`text`,value:`![${i}](${r})`}}})}}function I(e){return(0,ee.unified)().use(h.default,{fragment:!0}).use(Ae).use(Oe).use(ke).use(g.default).use(_.default).use(v.default,{handlers:{text:e=>e.value}}).processSync(e).value}function L(e,t,n,r){return I(S(t,n).exportBlocks(e,r))}function R(e){let n=[];return e.descendants(e=>{let r=t.dn(e);return e.type.name===`blockContainer`&&e.firstChild?.type.name===`blockGroup`?!0:e.type.name===`columnList`&&e.childCount===1?(e.firstChild?.forEach(e=>{n.push(t.in(e,r))}),!1):e.type.isInGroup(`bnBlock`)?(n.push(t.in(e,r)),!1):!0}),n}var z=class e extends a.Selection{nodes;constructor(e,t){super(e,t);let n=e.node();this.nodes=[],e.doc.nodesBetween(e.pos,t.pos,(e,t,r)=>{if(r!==null&&r.eq(n))return this.nodes.push(e),!1})}static create(t,n,r=n){return new e(t.resolve(n),t.resolve(r))}content(){return new n.Slice(n.Fragment.from(this.nodes),0,0)}eq(t){if(!(t instanceof e)||this.nodes.length!==t.nodes.length||this.from!==t.from||this.to!==t.to)return!1;for(let e=0;e<this.nodes.length;e++)if(!this.nodes[e].eq(t.nodes[e]))return!1;return!0}map(t,n){let r=n.mapResult(this.from),i=n.mapResult(this.to);return i.deleted?a.Selection.near(t.resolve(r.pos)):r.deleted?a.Selection.near(t.resolve(i.pos)):new e(t.resolve(r.pos),t.resolve(i.pos))}toJSON(){return{type:`multiple-node`,anchor:this.anchor,head:this.head}}};a.Selection.jsonID(`multiple-node`,z);var B;function je(e,t){let n,r,i=t.resolve(e.from).node().type.spec.group===`blockContent`,a=t.resolve(e.to).node().type.spec.group===`blockContent`,o=Math.min(e.$anchor.depth,e.$head.depth);if(i&&a){let i=e.$from.start(o-1),a=e.$to.end(o-1);n=t.resolve(i-1).pos,r=t.resolve(a+1).pos}else n=e.from,r=e.to;return{from:n,to:r}}function V(e,t,n=t){t===n&&(n+=e.state.doc.resolve(t+1).node().nodeSize);let r=e.domAtPos(t).node.cloneNode(!0),i=e.domAtPos(t).node,a=(e,t)=>Array.prototype.indexOf.call(e.children,t),o=a(i,e.domAtPos(t+1).node.parentElement),s=a(i,e.domAtPos(n-1).node.parentElement);for(let e=i.childElementCount-1;e>=0;e--)(e>s||e<o)&&r.removeChild(r.children[e]);H(e.root),B=r;let c=B.getElementsByTagName(`iframe`);for(let e=0;e<c.length;e++){let t=c[e],n=t.parentElement;n&&n.removeChild(t)}let l=e.dom.className.split(` `).filter(e=>e!==`ProseMirror`&&e!==`bn-root`&&e!==`bn-editor`).join(` `);B.className=B.className+` bn-drag-preview `+l,e.root instanceof ShadowRoot?e.root.appendChild(B):e.root.body.appendChild(B)}function H(e){B!==void 0&&(e instanceof ShadowRoot?e.removeChild(B):e.body.removeChild(B),B=void 0)}function Me(e,n,r){if(!e.dataTransfer||r.headless)return;let i=r.prosemirrorView,o=t.Et(n.id,i.state.doc);if(!o)throw Error(`Block with ID ${n.id} not found`);let s=o.posBeforeNode;if(s!=null){let t=i.state.selection,n=i.state.doc,{from:o,to:c}=je(t,n),l=o<=s&&s<c,u=t.$anchor.node()!==t.$head.node()||t instanceof z;l&&u?(i.dispatch(i.state.tr.setSelection(z.create(n,o,c))),V(i,o,c)):(i.dispatch(i.state.tr.setSelection(a.NodeSelection.create(i.state.doc,s))),V(i,s));let d=i.state.selection.content(),f=r.pmSchema,p=i.serializeForClipboard(d).dom.innerHTML,m=S(f,r),h=R(d.content),g=m.exportBlocks(h,{}),_=I(g);e.dataTransfer.clearData(),e.dataTransfer.setData(`blocknote/html`,p),e.dataTransfer.setData(`text/html`,g),e.dataTransfer.setData(`text/plain`,_),e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setDragImage(B,0,0)}}var U=250;function W(e,t,n=!0){let r=e.root.elementsFromPoint(t.left,t.top);for(let i of r)if(e.dom.contains(i))return n&&i.closest(`[data-node-type=columnList]`)?W(e,{left:t.left+50,top:t.top},!1):F(i,e)}function Ne(e,t){if(!t.dom.firstChild)return;let n=t.dom.firstChild.getBoundingClientRect(),r=W(t,{left:Math.min(Math.max(n.left+10,e.x),n.right-10),top:e.y});if(r)return W(t,{left:r.node.getBoundingClientRect().right-10,top:e.y},!1)}var G=class{state;emitUpdate;mousePos;hoveredBlock;menuFrozen=!1;isDragOrigin=!1;constructor(e,t,n){this.editor=e,this.pmView=t,this.emitUpdate=()=>{if(!this.state)throw Error(`Attempting to update uninitialized side menu`);n(this.state)},this.pmView.root.addEventListener(`dragstart`,this.onDragStart),this.pmView.root.addEventListener(`dragover`,this.onDragOver),this.pmView.root.addEventListener(`drop`,this.onDrop,!0),this.pmView.root.addEventListener(`dragend`,this.onDragEnd,!0),this.pmView.root.addEventListener(`mousemove`,this.onMouseMove,!0),this.pmView.root.addEventListener(`keydown`,this.onKeyDown,!0)}updateState=e=>{this.state=e,this.emitUpdate(this.state)};updateStateFromMousePos=()=>{if(this.menuFrozen||!this.mousePos)return;let e=this.findClosestEditorElement({clientX:this.mousePos.x,clientY:this.mousePos.y});if(e?.element!==this.pmView.dom||e.distance>U){this.state?.show&&(this.state.show=!1,this.updateState(this.state));return}let t=Ne(this.mousePos,this.pmView);if(!t||!this.editor.isEditable){this.state?.show&&(this.state.show=!1,this.updateState(this.state));return}if(!(this.state?.show&&this.hoveredBlock?.hasAttribute(`data-id`)&&this.hoveredBlock?.getAttribute(`data-id`)===t.id)&&(this.hoveredBlock=t.node,this.editor.isEditable)){let e=t.node.getBoundingClientRect(),n=t.node.closest(`[data-node-type=column]`);this.state={show:!0,referencePos:new DOMRect(n?n.firstElementChild.getBoundingClientRect().x:this.pmView.dom.firstChild.getBoundingClientRect().x,e.y,e.width,e.height),block:this.editor.getBlock(this.hoveredBlock.getAttribute(`data-id`))},this.updateState(this.state)}};onDragStart=e=>{let t=e.dataTransfer?.getData(`blocknote/html`);if(!t||this.pmView.dragging)return;let n=document.createElement(`div`);n.innerHTML=t;let r=s.DOMParser.fromSchema(this.pmView.state.schema).parse(n,{topNode:this.pmView.state.schema.nodes.blockGroup.create()});this.pmView.dragging={slice:new s.Slice(r.content,0,0),move:!0}};findClosestEditorElement=e=>{let t=Array.from(this.pmView.root.querySelectorAll(`.bn-editor`));if(t.length===0)return null;let n=t[0],r=Number.MAX_VALUE;return t.forEach(t=>{let i=t.querySelector(`.bn-block-group`).getBoundingClientRect(),a=e.clientX<i.left?i.left-e.clientX:e.clientX>i.right?e.clientX-i.right:0,o=e.clientY<i.top?i.top-e.clientY:e.clientY>i.bottom?e.clientY-i.bottom:0,s=Math.sqrt(a**2+o**2);s<r&&(r=s,n=t)}),{element:n,distance:r}};onDragOver=e=>{if(e.synthetic||!(this.pmView.dragging!==null||this.isDragOrigin||e.dataTransfer?.types.includes(`blocknote/html`)||e.target instanceof Node&&this.pmView.dom.contains(e.target)))return;let t=this.getDragEventContext(e);if(!t||!t.isDropPoint){this.closeDropCursor();return}t.isDropPoint&&!t.isDropWithinEditorBounds&&this.dispatchSyntheticEvent(e)};closeDropCursor=()=>{let e=new Event(`dragleave`,{bubbles:!1});e.synthetic=!0,this.pmView.dom.dispatchEvent(e)};getDragEventContext=e=>{if(!(this.pmView.dragging!==null||this.isDragOrigin||e.dataTransfer?.types.includes(`blocknote/html`)||e.target instanceof Node&&this.pmView.dom.contains(e.target)))return;let t=!e.dataTransfer?.types.includes(`blocknote/html`)&&!!this.pmView.dragging,n=!!this.isDragOrigin,r=t||n,i=this.findClosestEditorElement(e);if(!i||i.distance>U)return;let a=i.element===this.pmView.dom,o=a&&i.distance===0;if(!(!a&&!r))return{isDropPoint:a,isDropWithinEditorBounds:o,isDragOrigin:r}};onDrop=e=>{if(e.synthetic||!(this.pmView.dragging!==null||this.isDragOrigin||e.dataTransfer?.types.includes(`blocknote/html`)||e.target instanceof Node&&this.pmView.dom.contains(e.target)))return;let t=this.getDragEventContext(e);if(!t){this.closeDropCursor();return}let{isDropPoint:n,isDropWithinEditorBounds:r,isDragOrigin:i}=t;if(!r&&n&&this.dispatchSyntheticEvent(e),n){if(this.pmView.dragging)return;this.pmView.dispatch(this.pmView.state.tr.setSelection(l.TextSelection.create(this.pmView.state.tr.doc,this.pmView.state.tr.selection.anchor)));return}else if(i){setTimeout(()=>this.pmView.dispatch(this.pmView.state.tr.deleteSelection()),0);return}};onDragEnd=e=>{e.synthetic||(this.pmView.dragging=null)};onKeyDown=e=>{this.state?.show&&this.editor.isFocused()&&(this.state.show=!1,this.emitUpdate(this.state))};onMouseMove=e=>{if(this.menuFrozen)return;this.mousePos={x:e.clientX,y:e.clientY};let t=this.pmView.dom.getBoundingClientRect();if(this.mousePos.x>t.left&&this.mousePos.x<t.right&&this.mousePos.y>t.top&&this.mousePos.y<t.bottom&&e&&e.target&&!this.editor.isWithinEditor(e.target)){this.state?.show&&(this.state.show=!1,this.emitUpdate(this.state));return}this.updateStateFromMousePos()};dispatchSyntheticEvent(e){let t=new Event(e.type,e),n=this.pmView.dom.firstChild.getBoundingClientRect();t.clientX=e.clientX,t.clientY=e.clientY,t.clientX=Math.min(Math.max(e.clientX,n.left),n.left+n.width),t.clientY=Math.min(Math.max(e.clientY,n.top),n.top+n.height),t.dataTransfer=e.dataTransfer,t.preventDefault=()=>e.preventDefault(),t.synthetic=!0,this.pmView.dom.dispatchEvent(t)}update(e,t){!t.doc.eq(this.pmView.state.doc)&&this.state?.show&&this.updateStateFromMousePos()}destroy(){this.state?.show&&(this.state.show=!1,this.emitUpdate(this.state)),this.pmView.root.removeEventListener(`mousemove`,this.onMouseMove,!0),this.pmView.root.removeEventListener(`dragstart`,this.onDragStart),this.pmView.root.removeEventListener(`dragover`,this.onDragOver),this.pmView.root.removeEventListener(`drop`,this.onDrop,!0),this.pmView.root.removeEventListener(`dragend`,this.onDragEnd,!0),this.pmView.root.removeEventListener(`keydown`,this.onKeyDown,!0)}},K=new l.PluginKey(`SideMenuPlugin`),Pe=e.t(({editor:t})=>{let n,r=e.n(void 0);return{key:`sideMenu`,store:r,prosemirrorPlugins:[new l.Plugin({key:K,view:e=>(n=new G(t,e,e=>{r.setState({...e})}),n)})],blockDragStart(e,r){n&&(n.isDragOrigin=!0),Me(e,r,t)},blockDragEnd(){H(t.prosemirrorView.root),n&&(n.isDragOrigin=!1),t.blur()},freezeMenu(){n.menuFrozen=!0,n.state.show=!0,n.emitUpdate(n.state)},unfreezeMenu(){n.menuFrozen=!1,n.state.show=!1,n.emitUpdate(n.state)},hideMenuIfNotFrozen(){!n.menuFrozen&&n.state.show&&(n.state.show=!1,n.emitUpdate(n.state))}}}),q;async function Fe(){return q||(q=(async()=>{let[e,t]=await Promise.all([import(`emoji-mart`),import(`@emoji-mart/data`)]),n=`default`in e?e.default:e,r=`default`in t?t.default:t;return await n.init({data:r}),{emojiMart:n,emojiData:r}})(),q)}async function Ie(e,n){if(!(`text`in e.schema.inlineContentSchema)||e.schema.inlineContentSchema.text!==t.r.text)return[];let{emojiData:r,emojiMart:i}=await Fe();return(n.trim()===``?Object.values(r.emojis):await i.SearchIndex.search(n)).map(t=>({id:t.skins[0].native,onItemClick:()=>e.insertInlineContent(t.skins[0].native+` `)}))}var J;function Y(e){J||(J=document.createElement(`div`),J.innerHTML=`_`,J.style.opacity=`0`,J.style.height=`1px`,J.style.width=`1px`,e instanceof Document?e.body.appendChild(J):e.appendChild(J))}function Le(e){J&&=(e instanceof Document?e.body.removeChild(J):e.removeChild(J),void 0)}function X(e){return Array.prototype.indexOf.call(e.parentElement.childNodes,e)}function Re(e){let t=e;for(;t&&t.nodeName!==`TD`&&t.nodeName!==`TH`&&!t.classList.contains(`tableWrapper`);){if(t.classList.contains(`ProseMirror`))return;let e=t.parentNode;if(!e||!(e instanceof Element))return;t=e}return t.nodeName===`TD`||t.nodeName===`TH`?{type:`cell`,domNode:t,tbodyNode:t.closest(`tbody`)}:{type:`wrapper`,domNode:t,tbodyNode:t.querySelector(`tbody`)}}function ze(e,t){let n=t.querySelectorAll(e);for(let e=0;e<n.length;e++)n[e].style.visibility=`hidden`}var Z=class{state;emitUpdate;tableId;tablePos;tableElement;menuFrozen=!1;mouseState=`up`;prevWasEditable=null;constructor(e,t,n){this.editor=e,this.pmView=t,this.emitUpdate=()=>{if(!this.state)throw Error(`Attempting to update uninitialized image toolbar`);n(this.state)},t.dom.addEventListener(`mousemove`,this.mouseMoveHandler),t.dom.addEventListener(`mousedown`,this.viewMousedownHandler),window.addEventListener(`mouseup`,this.mouseUpHandler),t.root.addEventListener(`dragover`,this.dragOverHandler),t.root.addEventListener(`drop`,this.dropHandler)}viewMousedownHandler=()=>{this.mouseState=`down`};mouseUpHandler=e=>{this.mouseState=`up`,this.mouseMoveHandler(e)};mouseMoveHandler=e=>{if(this.menuFrozen||this.mouseState===`selecting`||!(e.target instanceof Element)||!this.pmView.dom.contains(e.target))return;let n=Re(e.target);if(n?.type===`cell`&&this.mouseState===`down`&&!this.state?.draggingState){this.mouseState=`selecting`,this.state?.show&&(this.state.show=!1,this.state.showAddOrRemoveRowsButton=!1,this.state.showAddOrRemoveColumnsButton=!1,this.emitUpdate());return}if(!n||!this.editor.isEditable){this.state?.show&&(this.state.show=!1,this.state.showAddOrRemoveRowsButton=!1,this.state.showAddOrRemoveColumnsButton=!1,this.emitUpdate());return}if(!n.tbodyNode)return;let r=n.tbodyNode.getBoundingClientRect(),i=F(n.domNode,this.pmView);if(!i)return;this.tableElement=i.node;let a,o=this.editor.transact(e=>t.Et(i.id,e.doc));if(!o)throw Error(`Block with ID ${i.id} not found`);let s=t.in(o.node,this.editor.pmSchema,this.editor.schema.blockSchema,this.editor.schema.inlineContentSchema,this.editor.schema.styleSchema);if(t.h(this.editor,`table`)&&(this.tablePos=o.posBeforeNode+1,a=s),!a)return;this.tableId=i.id;let c=n.domNode.closest(`.tableWrapper`)?.querySelector(`.table-widgets-container`);if(n?.type===`wrapper`){let t=e.clientY>=r.bottom-1&&e.clientY<r.bottom+20,n=e.clientX>=r.right-1&&e.clientX<r.right+20,i=this.state?.block.id!==a.id||e.clientX>r.right||e.clientY>r.bottom;this.state={...this.state,show:!0,showAddOrRemoveRowsButton:t,showAddOrRemoveColumnsButton:n,referencePosTable:r,block:a,widgetContainer:c,colIndex:i?void 0:this.state?.colIndex,rowIndex:i?void 0:this.state?.rowIndex,referencePosCell:i?void 0:this.state?.referencePosCell}}else{let e=X(n.domNode),t=X(n.domNode.parentElement),o=n.domNode.getBoundingClientRect();if(this.state!==void 0&&this.state.show&&this.tableId===i.id&&this.state.rowIndex===t&&this.state.colIndex===e)return;this.state={show:!0,showAddOrRemoveColumnsButton:e===a.content.rows[0].cells.length-1,showAddOrRemoveRowsButton:t===a.content.rows.length-1,referencePosTable:r,block:a,draggingState:void 0,referencePosCell:o,colIndex:e,rowIndex:t,widgetContainer:c}}return this.emitUpdate(),!1};dragOverHandler=e=>{if(this.state?.draggingState===void 0)return;e.preventDefault(),e.dataTransfer.dropEffect=`move`,ze(`.prosemirror-dropcursor-block, .prosemirror-dropcursor-inline`,this.pmView.root);let t={left:Math.min(Math.max(e.clientX,this.state.referencePosTable.left+1),this.state.referencePosTable.right-1),top:Math.min(Math.max(e.clientY,this.state.referencePosTable.top+1),this.state.referencePosTable.bottom-1)},n=this.pmView.root.elementsFromPoint(t.left,t.top).filter(e=>e.tagName===`TD`||e.tagName===`TH`);if(n.length===0)return;let r=n[0],i=!1,a=X(r.parentElement),o=X(r),s=this.state.draggingState.draggedCellOrientation===`row`?this.state.rowIndex:this.state.colIndex,c=(this.state.draggingState.draggedCellOrientation===`row`?a:o)!==s;(this.state.rowIndex!==a||this.state.colIndex!==o)&&(this.state.rowIndex=a,this.state.colIndex=o,this.state.referencePosCell=r.getBoundingClientRect(),i=!0);let l=this.state.draggingState.draggedCellOrientation===`row`?t.top:t.left;this.state.draggingState.mousePos!==l&&(this.state.draggingState.mousePos=l,i=!0),i&&this.emitUpdate(),c&&this.editor.transact(e=>e.setMeta(Q,!0))};dropHandler=e=>{if(this.mouseState=`up`,this.state===void 0||this.state.draggingState===void 0)return!1;if(this.state.rowIndex===void 0||this.state.colIndex===void 0)throw Error(`Attempted to drop table row or column, but no table block was hovered prior.`);e.preventDefault();let{draggingState:n,colIndex:r,rowIndex:i}=this.state,a=this.state.block.content.columnWidths;if(n.draggedCellOrientation===`row`){if(!t.Pt(this.state.block,n.originalIndex,i))return!1;let e=t.Bt(this.state.block,n.originalIndex,i);this.editor.updateBlock(this.state.block,{type:`table`,content:{...this.state.block.content,rows:e}})}else{if(!t.Nt(this.state.block,n.originalIndex,r))return!1;let e=t.zt(this.state.block,n.originalIndex,r),[i]=a.splice(n.originalIndex,1);a.splice(r,0,i),this.editor.updateBlock(this.state.block,{type:`table`,content:{...this.state.block.content,columnWidths:a,rows:e}})}return this.editor.setTextCursorPosition(this.state.block.id),!0};update(){if(!this.state||!this.state.show)return;if(this.state.block=this.editor.getBlock(this.state.block.id),!this.state.block||this.state.block.type!==`table`||!this.tableElement?.isConnected){this.state.show=!1,this.state.showAddOrRemoveRowsButton=!1,this.state.showAddOrRemoveColumnsButton=!1,this.emitUpdate();return}let{height:e,width:n}=t.Rt(this.state.block);this.state.rowIndex!==void 0&&this.state.colIndex!==void 0&&(this.state.rowIndex>=e&&(this.state.rowIndex=e-1),this.state.colIndex>=n&&(this.state.colIndex=n-1));let r=this.tableElement.querySelector(`tbody`);if(!r)throw Error(`Table block does not contain a 'tbody' HTML element. This should never happen.`);if(this.state.rowIndex!==void 0&&this.state.colIndex!==void 0){let e=r.children[this.state.rowIndex].children[this.state.colIndex];e?this.state.referencePosCell=e.getBoundingClientRect():(this.state.rowIndex=void 0,this.state.colIndex=void 0)}this.state.referencePosTable=r.getBoundingClientRect(),this.emitUpdate()}destroy(){this.pmView.dom.removeEventListener(`mousemove`,this.mouseMoveHandler),window.removeEventListener(`mouseup`,this.mouseUpHandler),this.pmView.dom.removeEventListener(`mousedown`,this.viewMousedownHandler),this.pmView.root.removeEventListener(`dragover`,this.dragOverHandler),this.pmView.root.removeEventListener(`drop`,this.dropHandler)}},Q=new a.PluginKey(`TableHandlesPlugin`),Be=e.t(({editor:n})=>{let r,i=e.n(void 0);return{key:`tableHandles`,store:i,prosemirrorPlugins:[new a.Plugin({key:Q,view:e=>(r=new Z(n,e,e=>{i.setState(e.block?{...e,draggingState:e.draggingState?{...e.draggingState}:void 0}:void 0)}),r),props:{decorations:e=>{if(r===void 0||r.state===void 0||r.state.draggingState===void 0||r.tablePos===void 0)return;let n=r.state.draggingState.draggedCellOrientation===`row`?r.state.rowIndex:r.state.colIndex;if(n===void 0)return;let i=[],{block:a,draggingState:o}=r.state,{originalIndex:s,draggedCellOrientation:c}=o;if(n===s||!a||c===`row`&&!t.Pt(a,s,n)||c===`col`&&!t.Nt(a,s,n))return u.DecorationSet.create(e.doc,i);let l=e.doc.resolve(r.tablePos+1);return r.state.draggingState.draggedCellOrientation===`row`?t.Lt(r.state.block,n).forEach(({row:t,col:r})=>{let a=e.doc.resolve(l.posAtIndex(t)+1),o=e.doc.resolve(a.posAtIndex(r)+1),c=o.node(),d=o.pos+(n>s?c.nodeSize-2:0);i.push(u.Decoration.widget(d,()=>{let e=document.createElement(`div`);return e.className=`bn-table-drop-cursor`,e.style.left=`0`,e.style.right=`0`,n>s?e.style.bottom=`-2px`:e.style.top=`-3px`,e.style.height=`4px`,e}))}):t.It(r.state.block,n).forEach(({row:t,col:r})=>{let a=e.doc.resolve(l.posAtIndex(t)+1),o=e.doc.resolve(a.posAtIndex(r)+1),c=o.node(),d=o.pos+(n>s?c.nodeSize-2:0);i.push(u.Decoration.widget(d,()=>{let e=document.createElement(`div`);return e.className=`bn-table-drop-cursor`,e.style.top=`0`,e.style.bottom=`0`,n>s?e.style.right=`-2px`:e.style.left=`-3px`,e.style.width=`4px`,e}))}),u.DecorationSet.create(e.doc,i)}}})],colDragStart(e){if(r===void 0||r.state===void 0||r.state.colIndex===void 0)throw Error(`Attempted to drag table column, but no table block was hovered prior.`);r.state.draggingState={draggedCellOrientation:`col`,originalIndex:r.state.colIndex,mousePos:e.clientX},r.emitUpdate(),n.transact(e=>e.setMeta(Q,{draggedCellOrientation:r.state.draggingState.draggedCellOrientation,originalIndex:r.state.colIndex,newIndex:r.state.colIndex,tablePos:r.tablePos})),!n.headless&&(Y(n.prosemirrorView.root),e.dataTransfer.setDragImage(J,0,0),e.dataTransfer.effectAllowed=`move`)},rowDragStart(e){if(r.state===void 0||r.state.rowIndex===void 0)throw Error(`Attempted to drag table row, but no table block was hovered prior.`);r.state.draggingState={draggedCellOrientation:`row`,originalIndex:r.state.rowIndex,mousePos:e.clientY},r.emitUpdate(),n.transact(e=>e.setMeta(Q,{draggedCellOrientation:r.state.draggingState.draggedCellOrientation,originalIndex:r.state.rowIndex,newIndex:r.state.rowIndex,tablePos:r.tablePos})),!n.headless&&(Y(n.prosemirrorView.root),e.dataTransfer.setDragImage(J,0,0),e.dataTransfer.effectAllowed=`copyMove`)},dragEnd(){if(r.state===void 0)throw Error(`Attempted to drag table row, but no table block was hovered prior.`);r.state.draggingState=void 0,r.emitUpdate(),n.transact(e=>e.setMeta(Q,null)),!n.headless&&Le(n.prosemirrorView.root)},freezeHandles(){r.menuFrozen=!0},unfreezeHandles(){r.menuFrozen=!1},hideHandlesIfNotFrozen(){!r.menuFrozen&&r.state?.show&&(r.state.show=!1,r.state.showAddOrRemoveRowsButton=!1,r.state.showAddOrRemoveColumnsButton=!1,r.emitUpdate())},getCellsAtRowHandle(e,n){return t.Lt(e,n)},getCellsAtColumnHandle(e,n){return t.It(e,n)},setCellSelection(e,t,n=t){if(!r)throw Error(`Table handles view not initialized`);let i=e.doc.resolve(r.tablePos+1),a=e.doc.resolve(i.posAtIndex(t.row)+1),o=e.doc.resolve(a.posAtIndex(t.col)),s=e.doc.resolve(i.posAtIndex(n.row)+1),l=e.doc.resolve(s.posAtIndex(n.col)),u=e.tr;return u.setSelection(new c.CellSelection(o,l)),e.apply(u)},addRowOrColumn(e,t){n.exec((n,r)=>{let i=this.setCellSelection(n,t.orientation===`row`?{row:e,col:0}:{row:0,col:e});return t.orientation===`row`?t.side===`above`?(0,c.addRowBefore)(i,r):(0,c.addRowAfter)(i,r):t.side===`left`?(0,c.addColumnBefore)(i,r):(0,c.addColumnAfter)(i,r)})},removeRowOrColumn(e,t){return t===`row`?n.exec((t,n)=>(0,c.deleteRow)(this.setCellSelection(t,{row:e,col:0}),n)):n.exec((t,n)=>(0,c.deleteColumn)(this.setCellSelection(t,{row:0,col:e}),n))},mergeCells(e){return n.exec((t,n)=>(0,c.mergeCells)(e?this.setCellSelection(t,e.relativeStartCell,e.relativeEndCell):t,n))},splitCell(e){return n.exec((t,n)=>(0,c.splitCell)(e?this.setCellSelection(t,e):t,n))},getCellSelection(){return n.transact(e=>{let n=e.selection,r=n.$from,i=n.$to;if(t.g(n)){let{ranges:e}=n;e.forEach(e=>{r=e.$from.min(r??e.$from),i=e.$to.max(i??e.$to)})}else if(r=e.doc.resolve(n.$from.pos-n.$from.parentOffset-1),i=e.doc.resolve(n.$to.pos-n.$to.parentOffset-1),r.pos===0||i.pos===0)return;let a=e.doc.resolve(r.pos-r.parentOffset-1),o=e.doc.resolve(i.pos-i.parentOffset-1),s=e.doc.resolve(a.pos-a.parentOffset-1),c=r.index(a.depth),l=a.index(s.depth),u=i.index(o.depth),d=o.index(s.depth),f=[];for(let e=l;e<=d;e++)for(let t=c;t<=u;t++)f.push({row:e,col:t});return{from:{row:l,col:c},to:{row:d,col:u},cells:f}})},getMergeDirection(e){return n.transact(n=>{let r=t.g(n.selection)?n.selection:void 0;if(!r||!e||r.ranges.length<=1)return;let i=this.getCellSelection();if(i)return t.Mt(i.from,i.to,e)?`vertical`:`horizontal`})},cropEmptyRowsOrColumns(e,n){return t.Ft(e,n)},addRowsOrColumns(e,n,r){return t.jt(e,n,r)}}}),$=new a.PluginKey(`trailingNode`),Ve=e.t(()=>({key:`trailingNode`,prosemirrorPlugins:[new a.Plugin({key:$,appendTransaction:(e,t,n)=>{let{doc:r,tr:i,schema:a}=n,o=$.getState(n),s=r.content.size-2,c=a.nodes.blockContainer,l=a.nodes.paragraph;if(o)return i.insert(s,c.create(void 0,l.create()))},state:{init:(e,t)=>{},apply:(e,t)=>{if(!e.docChanged)return t;let n=e.doc.lastChild;if(!n||n.type.name!==`blockGroup`)throw Error(`Expected blockGroup`);if(n=n.lastChild,!n||n.type.name!==`blockContainer`)return!0;let r=n.firstChild;if(!r)throw Error(`Expected blockContent`);return n.nodeSize>4||r.type.spec.content!==`inline*`}}})]}));Object.defineProperty(exports,`C`,{enumerable:!0,get:function(){return de}}),Object.defineProperty(exports,`D`,{enumerable:!0,get:function(){return ce}}),Object.defineProperty(exports,`E`,{enumerable:!0,get:function(){return E}}),Object.defineProperty(exports,`O`,{enumerable:!0,get:function(){return w}}),Object.defineProperty(exports,`S`,{enumerable:!0,get:function(){return pe}}),Object.defineProperty(exports,`T`,{enumerable:!0,get:function(){return D}}),Object.defineProperty(exports,`_`,{enumerable:!0,get:function(){return M}}),Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return Ie}}),Object.defineProperty(exports,`b`,{enumerable:!0,get:function(){return ve}}),Object.defineProperty(exports,`c`,{enumerable:!0,get:function(){return K}}),Object.defineProperty(exports,`d`,{enumerable:!0,get:function(){return I}}),Object.defineProperty(exports,`f`,{enumerable:!0,get:function(){return De}}),Object.defineProperty(exports,`g`,{enumerable:!0,get:function(){return N}}),Object.defineProperty(exports,`h`,{enumerable:!0,get:function(){return xe}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return Q}}),Object.defineProperty(exports,`k`,{enumerable:!0,get:function(){return S}}),Object.defineProperty(exports,`l`,{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,`m`,{enumerable:!0,get:function(){return Ce}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return Be}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return Pe}}),Object.defineProperty(exports,`p`,{enumerable:!0,get:function(){return Te}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return Z}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return G}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return Ve}}),Object.defineProperty(exports,`u`,{enumerable:!0,get:function(){return L}}),Object.defineProperty(exports,`v`,{enumerable:!0,get:function(){return j}}),Object.defineProperty(exports,`w`,{enumerable:!0,get:function(){return O}}),Object.defineProperty(exports,`x`,{enumerable:!0,get:function(){return ye}}),Object.defineProperty(exports,`y`,{enumerable:!0,get:function(){return be}});
2
+ //# sourceMappingURL=extensions-BfYaEv6F.cjs.map