@carlonicora/nextjs-jsonapi 6.28.0 → 6.29.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 (43) hide show
  1. package/dist/{BlockNoteEditor-2LO34HXR.mjs → BlockNoteEditor-BHCNJ2JA.mjs} +8 -60
  2. package/dist/BlockNoteEditor-BHCNJ2JA.mjs.map +1 -0
  3. package/dist/{BlockNoteEditor-SWDRMNLT.js → BlockNoteEditor-KGCHQQVY.js} +21 -73
  4. package/dist/BlockNoteEditor-KGCHQQVY.js.map +1 -0
  5. package/dist/billing/index.js +378 -378
  6. package/dist/billing/index.mjs +1 -1
  7. package/dist/{chunk-NV3NNNS6.mjs → chunk-UQFDOZVF.mjs} +66 -5
  8. package/dist/chunk-UQFDOZVF.mjs.map +1 -0
  9. package/dist/{chunk-6RWEYSYE.js → chunk-WXTEAATG.js} +67 -6
  10. package/dist/chunk-WXTEAATG.js.map +1 -0
  11. package/dist/client/index.js +2 -2
  12. package/dist/client/index.mjs +1 -1
  13. package/dist/components/editors/BlockNoteEditorMentionHoverCard.d.ts.map +1 -1
  14. package/dist/components/editors/BlockNoteEditorMentionInlineContent.d.ts +2 -0
  15. package/dist/components/editors/BlockNoteEditorMentionInlineContent.d.ts.map +1 -1
  16. package/dist/components/editors/index.d.ts +1 -0
  17. package/dist/components/editors/index.d.ts.map +1 -1
  18. package/dist/components/index.js +4 -2
  19. package/dist/components/index.js.map +1 -1
  20. package/dist/components/index.mjs +3 -1
  21. package/dist/contexts/index.js +2 -2
  22. package/dist/contexts/index.mjs +1 -1
  23. package/dist/email-automations/index.js +78 -78
  24. package/dist/email-automations/index.mjs +1 -1
  25. package/dist/features/analytics/index.js +107 -107
  26. package/dist/features/analytics/index.mjs +1 -1
  27. package/dist/features/blog/index.js +93 -93
  28. package/dist/features/blog/index.mjs +1 -1
  29. package/dist/features/help/index.js +31 -31
  30. package/dist/features/help/index.mjs +1 -1
  31. package/dist/features/tokenusage/index.js +102 -102
  32. package/dist/features/tokenusage/index.mjs +1 -1
  33. package/package.json +1 -1
  34. package/src/components/editors/BlockNoteEditorMentionHoverCard.tsx +8 -1
  35. package/src/components/editors/BlockNoteEditorMentionInlineContent.tsx +3 -1
  36. package/src/components/editors/__tests__/BlockNoteEditorMentionHoverCard.spec.tsx +42 -0
  37. package/src/components/editors/__tests__/BlockNoteEditorMentionInlineContent.spec.ts +30 -2
  38. package/src/components/editors/__tests__/blocknote-editor-options.spec.ts +8 -0
  39. package/src/components/editors/index.ts +1 -0
  40. package/dist/BlockNoteEditor-2LO34HXR.mjs.map +0 -1
  41. package/dist/BlockNoteEditor-SWDRMNLT.js.map +0 -1
  42. package/dist/chunk-6RWEYSYE.js.map +0 -1
  43. package/dist/chunk-NV3NNNS6.mjs.map +0 -1
@@ -3,10 +3,14 @@ import {
3
3
  BlockNoteEditorMentionHoverCard,
4
4
  BlockNoteEditorMentionSuggestionMenu,
5
5
  Button,
6
+ buildBlockNoteEditorOptions,
6
7
  createMentionInlineContentSpec,
7
8
  errorToast,
9
+ isDocumentEmpty,
10
+ removeTrailingEmptyBlocks,
11
+ resolveEditable,
8
12
  useCurrentUserContextOptional
9
- } from "./chunk-NV3NNNS6.mjs";
13
+ } from "./chunk-UQFDOZVF.mjs";
10
14
  import "./chunk-5T2AQMQ2.mjs";
11
15
  import "./chunk-VOXD3ZLY.mjs";
12
16
  import {
@@ -38,7 +42,7 @@ import {
38
42
 
39
43
  // src/components/editors/BlockNoteEditor.tsx
40
44
  import { BlockNoteSchema, defaultInlineContentSpecs, filterSuggestionItems } from "@blocknote/core";
41
- import * as coreLocales2 from "@blocknote/core/locales";
45
+ import * as coreLocales from "@blocknote/core/locales";
42
46
  import {
43
47
  createReactInlineContentSpec,
44
48
  getDefaultReactSlashMenuItems,
@@ -130,62 +134,6 @@ function BlockNoteEditorFormattingToolbar({ showAI = false }) {
130
134
  }
131
135
  __name(BlockNoteEditorFormattingToolbar, "BlockNoteEditorFormattingToolbar");
132
136
 
133
- // src/components/editors/blockNoteEditorOptions.ts
134
- import * as coreLocales from "@blocknote/core/locales";
135
- import { withCollaboration } from "@blocknote/core/yjs";
136
- function buildBlockNoteEditorOptions(params) {
137
- const { aiExtension, coreDictionary, aiDictionary, collaboration } = params;
138
- const options = {
139
- placeholders: {
140
- emptyDocument: params.placeholder
141
- },
142
- schema: params.schema,
143
- uploadFile: params.disableUploads ? void 0 : params.uploadFile,
144
- extensions: aiExtension ? [aiExtension] : void 0,
145
- dictionary: aiExtension ? { ...coreDictionary, ai: aiDictionary } : coreDictionary === coreLocales.en ? void 0 : coreDictionary
146
- };
147
- if (collaboration) return withCollaboration({ ...options, collaboration });
148
- return { ...options, initialContent: params.initialContent };
149
- }
150
- __name(buildBlockNoteEditorOptions, "buildBlockNoteEditorOptions");
151
- function resolveEditable(params) {
152
- return params.editable !== void 0 ? params.editable : params.onChange !== void 0;
153
- }
154
- __name(resolveEditable, "resolveEditable");
155
- function isBlockEmpty(block) {
156
- if (!block || typeof block !== "object") return true;
157
- if (block.type !== "paragraph") return false;
158
- if (Array.isArray(block.children) && block.children.length > 0 && !isDocumentEmpty(block.children)) {
159
- return false;
160
- }
161
- if (Array.isArray(block.content)) {
162
- for (const inline of block.content) {
163
- if (typeof inline === "string") {
164
- if (inline.trim()) return false;
165
- } else if (inline && typeof inline === "object") {
166
- if (inline.type !== "text") return false;
167
- if (typeof inline.text === "string" && inline.text.trim()) return false;
168
- }
169
- }
170
- } else if (typeof block.content === "string" && block.content.trim()) {
171
- return false;
172
- }
173
- return true;
174
- }
175
- __name(isBlockEmpty, "isBlockEmpty");
176
- function isDocumentEmpty(blocks) {
177
- if (!Array.isArray(blocks) || blocks.length === 0) return true;
178
- return blocks.every(isBlockEmpty);
179
- }
180
- __name(isDocumentEmpty, "isDocumentEmpty");
181
- function removeTrailingEmptyBlocks(blocks) {
182
- if (!blocks || blocks.length === 0) return blocks;
183
- const result = [...blocks];
184
- while (result.length > 1 && isBlockEmpty(result[result.length - 1])) result.pop();
185
- return result;
186
- }
187
- __name(removeTrailingEmptyBlocks, "removeTrailingEmptyBlocks");
188
-
189
137
  // src/components/editors/BlockNoteEditor.tsx
190
138
  import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
191
139
  var createDiffActionsInlineContentSpec = /* @__PURE__ */ __name((handleAcceptChange, handleRejectChange, labels) => {
@@ -599,7 +547,7 @@ function BlockNoteEditor({
599
547
  return void 0;
600
548
  }, [processedContent]);
601
549
  const language = locale.split("-")[0];
602
- const coreDictionary = coreLocales2[language] ?? coreLocales2.en;
550
+ const coreDictionary = coreLocales[language] ?? coreLocales.en;
603
551
  const aiDictionary = aiLocales[language] ?? aiLocales.en;
604
552
  const editor = useCreateBlockNote(
605
553
  useMemo(
@@ -916,4 +864,4 @@ __name(BlockNoteEditor, "BlockNoteEditor");
916
864
  export {
917
865
  BlockNoteEditor as default
918
866
  };
919
- //# sourceMappingURL=BlockNoteEditor-2LO34HXR.mjs.map
867
+ //# sourceMappingURL=BlockNoteEditor-BHCNJ2JA.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/components/editors/BlockNoteEditor.tsx","../src/components/editors/BlockNoteEditorAiActions.tsx","../src/components/editors/BlockNoteEditorFormattingToolbar.tsx"],"sourcesContent":["\"use client\";\n\nimport { BlockNoteSchema, defaultInlineContentSpecs, filterSuggestionItems, PartialBlock } from \"@blocknote/core\";\nimport * as coreLocales from \"@blocknote/core/locales\";\nimport {\n createReactInlineContentSpec,\n DefaultReactSuggestionItem,\n getDefaultReactSlashMenuItems,\n SuggestionMenuController,\n SuggestionMenuProps,\n useBlockNoteEditor,\n useCreateBlockNote,\n useExtension,\n useExtensionState,\n} from \"@blocknote/react\";\nimport { BlockNoteView } from \"@blocknote/shadcn\";\nimport \"@blocknote/shadcn/style.css\";\nimport {\n AIExtension,\n AIMenuController,\n getAISlashMenuItems,\n getDefaultAIMenuItems,\n PromptSuggestionMenu,\n useAIDictionary,\n} from \"@blocknote/xl-ai\";\nimport * as aiLocales from \"@blocknote/xl-ai/locales\";\nimport \"@blocknote/xl-ai/style.css\";\nimport { DefaultChatTransport } from \"ai\";\nimport { CheckIcon, LanguagesIcon, SparklesIcon, TypeIcon, WandSparklesIcon, XIcon } from \"lucide-react\";\nimport { useTranslations } from \"next-intl\";\nimport { useTheme } from \"next-themes\";\nimport React, { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { getPublicApiUrl } from \"../../client/config\";\nimport { getClientToken } from \"../../client/token\";\nimport { useCurrentUserContextOptional } from \"../../contexts\";\nimport { S3Interface } from \"../../features/s3/data\";\nimport { S3Service } from \"../../features/s3/data/s3.service\";\nimport { UserInterface } from \"../../features/user/data\";\nimport { useI18nLocale } from \"../../i18n/config\";\nimport { Button } from \"../../shadcnui\";\nimport { BlockNoteDiffUtil, BlockNoteWordDiffRendererUtil, cn } from \"../../utils\";\nimport { errorToast } from \"../errors\";\nimport { BlockNoteAiGenerateAction, generateActionItems } from \"./BlockNoteEditorAiActions\";\nimport { BlockNoteEditorFormattingToolbar } from \"./BlockNoteEditorFormattingToolbar\";\nimport {\n type BlockNoteCollaboration,\n buildBlockNoteEditorOptions,\n isDocumentEmpty,\n removeTrailingEmptyBlocks as trimTrailingEmptyBlocks,\n resolveEditable,\n} from \"./blockNoteEditorOptions\";\nimport { BlockNoteEditorMentionHoverCard } from \"./BlockNoteEditorMentionHoverCard\";\nimport {\n createMentionInlineContentSpec,\n type MentionNameResolver,\n type MentionResolveFn,\n} from \"./BlockNoteEditorMentionInlineContent\";\nimport { BlockNoteEditorMentionSuggestionMenu } from \"./BlockNoteEditorSuggestionMenuController\";\n\n/**\n * Lets app code trigger a whole-document AI action from OUTSIDE the editor\n * (a visible button next to the field label, for instance) without owning the\n * BlockNote instance. Delivered through a plain prop, not a React `ref`:\n * `BlockNoteEditorContainer` is a `next/dynamic` import wrapped in\n * `React.memo`, and refs do not pass through that reliably.\n */\nexport type BlockNoteAiHandle = { invokeAi: (type: BlockNoteAiGenerateAction) => void };\n\nexport type BlockNoteAiConfig = {\n endpoint: string;\n entityType: string;\n entityId?: string;\n /** Whole-document actions shown when nothing is selected. Default: [\"fill-template\"]. */\n actions?: BlockNoteAiGenerateAction[];\n};\n\nexport type BlockNoteEditorProps = {\n id: string;\n type: string;\n initialContent?: PartialBlock[];\n onChange?: (content: any, isEmpty: boolean, hasUnresolvedDiff: boolean) => void;\n size?: \"sm\" | \"md\";\n className?: string;\n markdownContent?: string;\n diffContent?: PartialBlock[];\n placeholder?: string;\n bordered?: boolean;\n /**\n * Storage folder for pasted images, used instead of the current company's\n * `companies/<companyId>/<type>` folder: the image key becomes\n * `<uploadKeyPrefix>/<id>/<file name>`. For platform content edited by users\n * who belong to no company (the blog). Omitted: the company folder, as before.\n */\n uploadKeyPrefix?: string;\n inlineContentSpecs?: Record<string, any>;\n renderOverlays?: (editor: any) => React.ReactNode;\n enableMentions?: boolean;\n disableMentions?: boolean;\n mentionSearchFn?: (\n query: string,\n params?: Record<string, string>,\n ) => Promise<import(\"./BlockNoteEditorSuggestionMenuController\").MentionItem[]>;\n mentionSearchParams?: Record<string, string>;\n mentionResolveFn?: MentionResolveFn;\n suggestionMenuComponent?: React.FC<SuggestionMenuProps<DefaultReactSuggestionItem>>;\n mentionNameResolver?: MentionNameResolver;\n onWarmMentions?: (blocks: PartialBlock[]) => void;\n aiConfig?: BlockNoteAiConfig;\n // When the editor is inside a bounded flex column (parent gives it a real\n // height via flex-1+min-h-0), set this so `.bn-container` shrinks to that\n // height and scrolls internally. Without it the editor grows to fit its\n // content and pushes the surrounding form to scroll instead.\n stretch?: boolean;\n // Gates AI on top of `aiConfig` (credit availability, etc.). Defaults to\n // true so existing callers that only pass `aiConfig` are unaffected. When\n // false, the AI toolbar button and AI slash items are hidden, the editor\n // falls back to the plain slash menu, an open AI menu or run is closed, and\n // no AI request is sent. The AI extension itself stays: toggling this never\n // rebuilds the editor, so unsaved text survives credits running out.\n aiEnabled?: boolean;\n // Filled with a {@link BlockNoteAiHandle} while the editor is mounted and AI\n // is on, so a control outside the editor can run a whole-document AI action.\n // Cleared on unmount and whenever AI is unavailable.\n aiHandleRef?: React.MutableRefObject<BlockNoteAiHandle | null>;\n /**\n * Live co-editing (Yjs). When set, the Yjs document is the content: used\n * instead of `initialContent`/`onChange`. Changing `collaboration.fragment`\n * rebuilds the editor.\n */\n collaboration?: BlockNoteCollaboration;\n /** true: image uploads are off (no paste/drop upload, no upload tab). */\n disableUploads?: boolean;\n /**\n * Overrides the default `onChange !== undefined` editability, e.g. for a\n * collaborative editor, which has no `onChange`.\n */\n editable?: boolean;\n};\n\nconst createDiffActionsInlineContentSpec = (\n handleAcceptChange: (diffId: string) => void,\n handleRejectChange: (diffId: string) => void,\n labels: { accept: string; reject: string },\n) => {\n return createReactInlineContentSpec(\n {\n type: \"diffActions\",\n propSchema: {\n diffIds: {\n default: \"\",\n },\n },\n content: \"none\",\n },\n {\n render: (props) => {\n const diffIds = props.inlineContent.props.diffIds;\n\n return (\n <span className=\"diff-actions-container mx-2 inline-flex items-center gap-1 align-middle\">\n <Button\n title={labels.accept}\n onClick={(e) => {\n e.preventDefault();\n e.stopPropagation();\n diffIds.split(\",\").forEach((id: string) => handleAcceptChange(id.trim()));\n }}\n >\n <CheckIcon className=\"text-success h-3 w-3\" />\n </Button>\n <Button\n title={labels.reject}\n className=\"mx-2 p-0\"\n onClick={(e) => {\n e.preventDefault();\n e.stopPropagation();\n diffIds.split(\",\").forEach((id: string) => handleRejectChange(id.trim()));\n }}\n >\n <XIcon className=\"text-destructive h-3 w-3\" />\n </Button>\n </span>\n );\n },\n },\n );\n};\n\n/**\n * Custom AI menu wrapper. Surfaces our backend-driven action items\n * (Improve Writing, Fix Spelling) above the free-form prompt input.\n *\n * Why a custom wrapper instead of `<AIMenu items={…}>` with the BlockNote\n * defaults: BlockNote's `PromptSuggestionMenu` hijacks Enter to pick the\n * highlighted item whenever `items.length > 0`. We gate items on\n * - status === \"user-input\"\n * - editor has a selection\n * - prompt input is empty\n * so the moment the user types, items disappear and Enter falls back to\n * free-form submission. Outside `user-input` (review / error states) we\n * keep BlockNote's default review buttons (accept/revert/retry/cancel).\n *\n * Each custom item passes a `type` discriminator on `chatRequestOptions.body`.\n * That field flows through `chat.sendMessage(msg, opts)` to the transport's\n * `prepareSendMessagesRequest({messages, body})` (see types.ts in\n * `@blocknote/xl-ai` — `ChatRequestOptions = Parameters<Chat[\"sendMessage\"]>[1]`).\n * The backend dispatcher reads `body.type` and routes to a per-type handler\n * with its own canonical prompt. NO prompt text lives in this file.\n */\nfunction NarrAIMenu({ actions }: { actions?: BlockNoteAiGenerateAction[] }) {\n const t = useTranslations();\n const editor = useBlockNoteEditor();\n const ai = useExtension(AIExtension);\n const dict = useAIDictionary();\n const status = useExtensionState(AIExtension, {\n selector: (s) => (s.aiMenuState !== \"closed\" ? s.aiMenuState.status : \"closed\"),\n });\n const [prompt, setPrompt] = useState(\"\");\n // Set by items that pre-fill the input (Translate) so handleSubmit knows\n // which `type` to attach when the user submits the captured text. Cleared\n // after submit or on status change.\n const pendingTypeRef = useRef<string | null>(null);\n\n useEffect(() => {\n if (status === \"ai-writing\" || status === \"user-reviewing\" || status === \"error\" || status === \"closed\") {\n setPrompt(\"\");\n pendingTypeRef.current = null;\n }\n }, [status]);\n\n // Selection-edit ops operate per-block. If the user's selection only\n // covers part of a block (cursor mid-paragraph dragged to mid-next), the\n // rewrite would silently replace the WHOLE containing blocks — beyond\n // what the user highlighted. Expand the selection to whole-block bounds\n // BEFORE invokeAI so the user sees exactly what will be rewritten.\n const expandSelectionToBlocks = useCallback(() => {\n const sel = editor.getSelection?.();\n const blocks = (sel as any)?.blocks;\n if (!Array.isArray(blocks) || blocks.length === 0) return;\n const first = blocks[0];\n const last = blocks[blocks.length - 1];\n try {\n (editor as any).setSelection?.(first, last);\n } catch {\n // If BlockNote's setSelection signature changes, fail silently — the\n // backend still operates per-block, so we just lose the visual hint.\n }\n }, [editor]);\n\n const items = useMemo(() => {\n // Outside user-input (reviewing / error), use BlockNote's default\n // review buttons (accept/revert/retry/cancel). Need to wrap onItemClick\n // because the default items expect a setPrompt argument.\n if (status !== \"user-input\") {\n return getDefaultAIMenuItems(editor, status).map((item) => ({\n ...item,\n onItemClick: () => item.onItemClick(setPrompt),\n }));\n }\n const hasSelection = editor.getSelection() !== undefined;\n const hasTyped = prompt.trim().length > 0;\n // Once the user starts typing, hide all items so Enter submits the\n // free-form (or pending-type) prompt instead of being hijacked.\n if (hasTyped) return [];\n\n const invokeGenerate = (type: BlockNoteAiGenerateAction) => {\n void ai.invokeAI({\n userPrompt: type,\n useSelection: false,\n chatRequestOptions: { body: { type } },\n });\n };\n // Whole-document items are shown in BOTH contexts (with and without\n // selection) because they operate on the whole document — they ignore any\n // active selection. Listed first so the first one is the\n // default-highlighted item.\n const generateItems = generateActionItems(actions, invokeGenerate, t);\n\n if (hasSelection) {\n // Selection-edit items + the always-available whole-document items.\n // Each selection item invokes ai.invokeAI with chatRequestOptions\n // carrying the `type` body field. The userPrompt is a short tag — the\n // backend ignores it and uses the canonical prompt for the type instead.\n return [\n ...generateItems,\n {\n key: \"improve_writing\",\n title: t(\"ui.editor.ai.improve_writing\"),\n aliases: [\"improve\", \"rewrite\", \"polish\"],\n icon: <SparklesIcon size={18} />,\n size: \"small\" as const,\n onItemClick: () => {\n expandSelectionToBlocks();\n void ai.invokeAI({\n userPrompt: \"improve-writing\",\n useSelection: true,\n chatRequestOptions: { body: { type: \"improve-writing\" } },\n });\n },\n },\n {\n key: \"fix_spelling\",\n title: t(\"ui.editor.ai.fix_spelling\"),\n aliases: [\"spelling\", \"grammar\", \"typo\"],\n icon: <TypeIcon size={18} />,\n size: \"small\" as const,\n onItemClick: () => {\n expandSelectionToBlocks();\n void ai.invokeAI({\n userPrompt: \"fix-spelling\",\n useSelection: true,\n chatRequestOptions: { body: { type: \"fix-spelling\" } },\n });\n },\n },\n {\n key: \"translate\",\n title: t(\"ui.editor.ai.translate\"),\n aliases: [\"translate\", \"language\"],\n icon: <LanguagesIcon size={18} />,\n size: \"small\" as const,\n // Pre-fills the input with a placeholder. User appends/replaces\n // with the target language and submits via Enter. handleSubmit\n // reads pendingTypeRef and forwards `type: \"translate\"`. We\n // expand the selection now so the user sees the scope before\n // typing the language — handleSubmit doesn't re-expand.\n onItemClick: () => {\n expandSelectionToBlocks();\n pendingTypeRef.current = \"translate\";\n setPrompt(t(\"ui.editor.ai.translate_prefill\"));\n },\n },\n {\n key: \"simplify\",\n title: t(\"ui.editor.ai.simplify\"),\n aliases: [\"simplify\", \"easier\", \"plain\"],\n icon: <WandSparklesIcon size={18} />,\n size: \"small\" as const,\n onItemClick: () => {\n expandSelectionToBlocks();\n void ai.invokeAI({\n userPrompt: \"simplify\",\n useSelection: true,\n chatRequestOptions: { body: { type: \"simplify\" } },\n });\n },\n },\n ];\n }\n\n // No selection (the /ai slash menu path): just the whole-document items.\n // Free-form typing still works — once the user types, items hide and\n // Enter submits with no type (backend defaults to fill-template).\n return generateItems;\n }, [editor, status, prompt, ai, expandSelectionToBlocks, actions, t]);\n\n const handleSubmit = useCallback(\n async (userPrompt: string) => {\n if (!userPrompt.trim()) return;\n const pendingType = pendingTypeRef.current;\n pendingTypeRef.current = null;\n const body = pendingType ? { type: pendingType } : undefined;\n await ai.invokeAI({\n userPrompt,\n useSelection: editor.getSelection() !== undefined,\n ...(body ? { chatRequestOptions: { body } } : {}),\n });\n },\n [ai, editor],\n );\n\n const placeholder =\n status === \"thinking\"\n ? dict.ai_menu.status.thinking\n : status === \"ai-writing\"\n ? dict.ai_menu.status.editing\n : status === \"error\"\n ? dict.ai_menu.status.error\n : dict.ai_menu.input_placeholder;\n\n const disabled = status === \"thinking\" || status === \"ai-writing\";\n\n return (\n <PromptSuggestionMenu\n items={items}\n onManualPromptSubmit={handleSubmit}\n promptText={prompt}\n onPromptTextChange={setPrompt}\n placeholder={placeholder}\n disabled={disabled}\n icon={\n <div className=\"bn-combobox-icon\">\n <SparklesIcon size={16} />\n </div>\n }\n />\n );\n}\n\nexport default function BlockNoteEditor({\n id,\n type,\n initialContent,\n onChange,\n size,\n className,\n markdownContent,\n diffContent,\n placeholder,\n bordered,\n uploadKeyPrefix,\n inlineContentSpecs,\n renderOverlays,\n enableMentions,\n disableMentions,\n mentionSearchFn,\n mentionSearchParams,\n mentionResolveFn,\n suggestionMenuComponent,\n mentionNameResolver,\n onWarmMentions,\n aiConfig,\n stretch,\n aiEnabled = true,\n aiHandleRef,\n collaboration,\n disableUploads,\n editable,\n}: BlockNoteEditorProps): React.JSX.Element {\n const isEditable = resolveEditable({ editable, onChange });\n const t = useTranslations();\n const locale = useI18nLocale();\n const { resolvedTheme } = useTheme();\n // Optional on purpose: a host app may mount its own user context instead of\n // this package's, and the editor already degrades without a company — image\n // upload reports it (`uploadImage`) and the AI transport simply omits the\n // company header. Throwing here would take the whole page down instead.\n const company = useCurrentUserContextOptional<UserInterface>()?.company ?? null;\n\n const [acceptedChanges, setAcceptedChanges] = useState<Set<string>>(new Set());\n const [rejectedChanges, setRejectedChanges] = useState<Set<string>>(new Set());\n\n const editorRef = useRef<HTMLDivElement>(null);\n\n // Ensure side menu buttons don't trigger form submission\n useEffect(() => {\n if (!editorRef.current) return;\n const setButtonTypes = () => {\n editorRef.current?.querySelectorAll(\".bn-side-menu button\").forEach((btn) => {\n if (!btn.getAttribute(\"type\")) {\n btn.setAttribute(\"type\", \"button\");\n }\n });\n };\n const observer = new MutationObserver(setButtonTypes);\n observer.observe(editorRef.current, { childList: true, subtree: true });\n return () => observer.disconnect();\n }, []);\n\n const handleAcceptChange = useCallback((diffId: string) => {\n setAcceptedChanges((prev) => new Set([...prev, diffId]));\n setRejectedChanges((prev) => {\n const newSet = new Set(prev);\n newSet.delete(diffId);\n return newSet;\n });\n }, []);\n\n const handleRejectChange = useCallback((diffId: string) => {\n setRejectedChanges((prev) => new Set([...prev, diffId]));\n setAcceptedChanges((prev) => {\n const newSet = new Set(prev);\n newSet.delete(diffId);\n return newSet;\n });\n }, []);\n\n const DiffActionsInlineContent = useMemo(\n () =>\n createDiffActionsInlineContentSpec(handleAcceptChange, handleRejectChange, {\n accept: t(\"ui.editor.accept_change\"),\n reject: t(\"ui.editor.reject_change\"),\n }),\n [handleAcceptChange, handleRejectChange, t],\n );\n\n const mentionSpec = useMemo(\n () => createMentionInlineContentSpec(mentionResolveFn, disableMentions, mentionNameResolver),\n [disableMentions, mentionResolveFn, mentionNameResolver],\n );\n\n const schema = useMemo(\n () =>\n BlockNoteSchema.create({\n inlineContentSpecs: {\n ...defaultInlineContentSpecs,\n diffActions: DiffActionsInlineContent,\n mention: mentionSpec,\n ...inlineContentSpecs,\n },\n } as any),\n [DiffActionsInlineContent, mentionSpec, inlineContentSpecs],\n );\n\n const docRef = useRef<{ getDoc: () => any[] }>({ getDoc: () => [] });\n // Selection getter used by the AI transport to attach `selectionBlocks` to\n // the outgoing request metadata. Populated in a useEffect once the editor\n // instance exists; reads the current BlockNote selection on every send.\n const selectionRef = useRef<{ getSelectedBlocks: () => any[] }>({ getSelectedBlocks: () => [] });\n\n // Callers pass `aiConfig` as an inline object, the company arrives after the\n // first render and `aiEnabled` flips with credits, so none of them may key\n // the AI extension: every new extension means a new editor, which restarts\n // from `initialContent` and drops unsaved text. The transport and the outside\n // handle read them through this ref at send time.\n const aiRequestRef = useRef({ aiConfig, companyId: company?.id, aiEnabled });\n useEffect(() => {\n aiRequestRef.current = { aiConfig, companyId: company?.id, aiEnabled };\n });\n\n const hasAiConfig = !!aiConfig;\n const aiEndpoint = aiConfig?.endpoint;\n const aiExtension = useMemo(() => {\n if (!hasAiConfig || !aiEndpoint) return undefined;\n const base = getPublicApiUrl();\n const url = new URL(aiEndpoint, base.endsWith(\"/\") ? base : base + \"/\").toString();\n return AIExtension({\n transport: new DefaultChatTransport({\n api: url,\n credentials: \"include\",\n headers: async () => {\n const headers: Record<string, string> = { \"x-language\": locale };\n const token = await getClientToken();\n if (token) headers[\"Authorization\"] = `Bearer ${token}`;\n const companyId = aiRequestRef.current.companyId;\n if (companyId) headers[\"x-companyid\"] = companyId;\n return headers;\n },\n prepareSendMessagesRequest: ({ messages, body }: any) => {\n // Last guard before the network: AI switched off while a request was\n // being started never reaches the endpoint. Throwing here puts the\n // AI menu in its error state instead of sending.\n if (!aiRequestRef.current.aiEnabled) throw new Error(\"AI is disabled\");\n const latestAiConfig = aiRequestRef.current.aiConfig;\n let lastUserIdx = -1;\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i]?.role === \"user\") {\n lastUserIdx = i;\n break;\n }\n }\n const selectedBlocks = selectionRef.current.getSelectedBlocks();\n const augmented = messages.map((m: any, i: number) =>\n i === lastUserIdx\n ? {\n ...m,\n metadata: {\n ...(m.metadata ?? {}),\n entityType: latestAiConfig?.entityType,\n entityId: latestAiConfig?.entityId,\n blocks: docRef.current.getDoc(),\n selectionBlocks: selectedBlocks,\n },\n }\n : m,\n );\n return { body: { ...(body ?? {}), messages: augmented } };\n },\n }),\n });\n }, [hasAiConfig, aiEndpoint, locale]);\n\n const uploadImage = useCallback(\n async (file: File): Promise<string> => {\n if (!company && !uploadKeyPrefix) {\n errorToast({\n title: t(`common.errors.upload`),\n error: t(`common.errors.upload_description`),\n });\n throw new Error(t(`common.errors.upload`));\n }\n\n const fileType = file.type;\n const key = uploadKeyPrefix\n ? `${uploadKeyPrefix}/${id}/${file.name}`\n : `companies/${company!.id}/${type}/${id}/${file.name}`;\n\n const s3: S3Interface = await S3Service.getPreSignedUrl({\n key: key,\n contentType: fileType,\n isPublic: true,\n });\n\n await fetch(s3.url, {\n method: \"PUT\",\n headers: s3.headers,\n body: file,\n });\n\n const signedImage: S3Interface = await S3Service.getSignedUrl({\n key: key,\n isPublic: true,\n });\n\n return signedImage.url;\n },\n [company, id, t, type, uploadKeyPrefix],\n );\n\n // Utility: Remove trailing empty blocks for read-only display\n const removeTrailingEmptyBlocks = useCallback(\n (blocks: PartialBlock[]): PartialBlock[] => {\n if (!blocks || blocks.length === 0) return blocks;\n\n // Only remove trailing empty blocks in read-only mode\n if (onChange !== undefined) return blocks;\n\n return trimTrailingEmptyBlocks(blocks);\n },\n [onChange],\n );\n\n const processedContent = useMemo(() => {\n if (diffContent && initialContent) {\n try {\n const diffResult = BlockNoteDiffUtil.diff(initialContent, diffContent);\n const renderedDiff = BlockNoteWordDiffRendererUtil.renderWordDiffs(\n diffResult.blocks,\n handleAcceptChange,\n handleRejectChange,\n acceptedChanges,\n rejectedChanges,\n );\n return removeTrailingEmptyBlocks(renderedDiff);\n } catch (_error) {\n return initialContent && Array.isArray(initialContent) && initialContent.length > 0\n ? removeTrailingEmptyBlocks(initialContent)\n : [];\n }\n }\n\n if (!initialContent) {\n return [];\n }\n\n if (!Array.isArray(initialContent)) {\n return [];\n }\n\n return initialContent.length > 0 ? removeTrailingEmptyBlocks(initialContent) : [];\n }, [\n initialContent,\n diffContent,\n handleAcceptChange,\n handleRejectChange,\n acceptedChanges,\n rejectedChanges,\n removeTrailingEmptyBlocks,\n ]);\n\n const validatedInitialContent = useMemo(() => {\n if (processedContent && Array.isArray(processedContent) && processedContent.length > 0) {\n const validatedContent = processedContent.filter((block) => {\n if (!block || typeof block !== \"object\") return false;\n if (!(block as any).type) return false;\n return true;\n });\n return validatedContent.length > 0 ? (validatedContent as PartialBlock[]) : undefined;\n }\n return undefined;\n }, [processedContent]);\n\n // BlockNote's own UI text (slash menu, toolbar, AI menu) in the active\n // language; English when BlockNote has no dictionary for it.\n const language = locale.split(\"-\")[0];\n const coreDictionary = (coreLocales as Record<string, typeof coreLocales.en>)[language] ?? coreLocales.en;\n const aiDictionary = (aiLocales as Record<string, typeof aiLocales.en>)[language] ?? aiLocales.en;\n\n const editor = useCreateBlockNote(\n useMemo(\n () =>\n buildBlockNoteEditorOptions({\n placeholder: placeholder || t(`common.blocknote.placeholder`),\n schema,\n initialContent: validatedInitialContent,\n uploadFile: uploadImage,\n disableUploads,\n aiExtension,\n coreDictionary,\n aiDictionary,\n collaboration,\n }),\n [\n placeholder,\n t,\n schema,\n validatedInitialContent,\n uploadImage,\n disableUploads,\n aiExtension,\n coreDictionary,\n aiDictionary,\n collaboration,\n ],\n ),\n // useCreateBlockNote memoises on THIS list, not on the options' identity\n // (@blocknote/react: useMemo(() => BlockNoteEditor.create(options), deps),\n // deps defaulting to []). Without it the editor keeps the extensions of its\n // first render: AI config arriving later (user loaded after mount)\n // rendered the AI UI over an editor with no AIExtension, and BlockNote's\n // useExtension threw \"Extension not found\". The other options keep their\n // first-render values, as before. `aiEnabled` is deliberately not here.\n // A new Yjs fragment (another document) needs a new editor bound to it.\n [aiExtension, collaboration?.fragment],\n );\n\n // Every AI surface keys off the editor actually rendered, never off the\n // props: those can disagree with the options that editor was created with.\n // `aiEnabled` then hides that UI without touching the editor.\n const hasAiExtension = !!editor.getExtension(AIExtension);\n const aiActive = hasAiExtension && aiEnabled;\n\n // AI switched off while its menu is open or a run is streaming: hiding the\n // AIMenuController alone would leave the editor read-only (openAIMenuAtBlock\n // sets isEditable = false) and the AI suggestions in the document. Stop the\n // request, then reject the suggestions, or just close an idle prompt menu.\n useEffect(() => {\n if (aiEnabled || !hasAiExtension) return;\n const ai = editor.getExtension(AIExtension);\n if (!ai) return;\n const dismiss = async () => {\n const menu = ai.store.state.aiMenuState;\n if (menu === \"closed\") return;\n if (menu.status === \"thinking\" || menu.status === \"ai-writing\") await ai.abort(\"AI disabled\");\n const after = ai.store.state.aiMenuState;\n if (after === \"closed\") return;\n if (after.status === \"user-input\") ai.closeAIMenu();\n else ai.rejectChanges();\n };\n dismiss().catch((error) => console.error(\"Closing the AI menu failed:\", error));\n }, [aiEnabled, hasAiExtension, editor]);\n\n // Publish the outside-the-editor AI trigger. `editor.getExtension(AIExtension)`\n // is BlockNote 0.54's documented lookup by extension factory (core's\n // `getExtension` resolves a function argument through `extensionFactories`),\n // so the instance is reachable without the `useExtension` hook that only\n // works inside the BlockNote context (NarrAIMenu). The menu MUST be opened\n // first: `invokeAI` routes every status update through `setAIResponseStatus`,\n // which is a no-op while `aiMenuState === \"closed\"` — without the open menu\n // the request runs but the accept / reject UI never appears.\n useEffect(() => {\n if (!aiHandleRef) return;\n if (!aiActive) {\n aiHandleRef.current = null;\n return;\n }\n aiHandleRef.current = {\n invokeAi: (type: BlockNoteAiGenerateAction) => {\n // A caller may hold the handle across the render that turns AI off.\n if (!aiRequestRef.current.aiEnabled) return;\n const ai = editor.getExtension(AIExtension);\n if (!ai) return;\n editor.focus();\n const blocks = editor.document;\n const anchor = blocks?.[blocks.length - 1];\n if (anchor?.id) ai.openAIMenuAtBlock(anchor.id);\n void ai.invokeAI({\n userPrompt: type,\n useSelection: false,\n chatRequestOptions: { body: { type } },\n });\n },\n };\n return () => {\n aiHandleRef.current = null;\n };\n }, [aiHandleRef, aiActive, editor]);\n\n // Tracks the hash of the document the editor itself just emitted via onChange.\n // The sync effect below uses it to skip replaceBlocks when the parent's\n // initialContent is just an echo of our own emission (form-controlled flow).\n const lastEmittedHashRef = useRef<string | null>(null);\n\n // Whether the parent's copy of the text is empty: the content it handed in, then each change\n // reported to it. A change from empty to still empty is not reported: BlockNote emits one when an\n // empty editor mounts (its trailing empty paragraph), and reported it became a save of nothing on\n // every view of a page with an empty field.\n const processedContentRef = useRef<any[]>([]);\n const parentKnowsEmptyRef = useRef<boolean | null>(null);\n\n // The document the editor holds right after loading the parent's text, until the first change\n // that differs from it. Loading text BlockNote stores in a fuller shape (block ids, default props,\n // children: text written by the server, an import, the API) emits a change of the same text.\n // Reported, it became a save on every view of such a page, and offline a queued change.\n const loadedHashRef = useRef<string | null>(null);\n // True while replaceBlocks loads the parent's text: BlockNote fires onChange synchronously\n // inside it, before loadedHashRef can be set.\n const loadingFromParentRef = useRef(false);\n\n const handleChange = useCallback(async () => {\n if (!onChange) return;\n const newBlocks = editor.document;\n const newHash = JSON.stringify(newBlocks);\n if (loadingFromParentRef.current) {\n lastEmittedHashRef.current = newHash;\n return;\n }\n if (loadedHashRef.current !== null) {\n if (newHash === loadedHashRef.current) {\n lastEmittedHashRef.current = newHash;\n return;\n }\n loadedHashRef.current = null;\n }\n lastEmittedHashRef.current = newHash;\n const isEmpty = isDocumentEmpty(newBlocks);\n const wasEmpty = parentKnowsEmptyRef.current ?? isDocumentEmpty(processedContentRef.current);\n if (isEmpty && wasEmpty) return;\n parentKnowsEmptyRef.current = isEmpty;\n\n function hasUnresolvedDiffsRecursive(block: any): boolean {\n if (!block || typeof block !== \"object\") return false;\n let diffId = undefined;\n if (block.props && block.props.diffId) diffId = block.props.diffId;\n if (!diffId && block.attrs && block.attrs.diffId) diffId = block.attrs.diffId;\n if (diffId && !acceptedChanges.has(diffId) && !rejectedChanges.has(diffId)) {\n return true;\n }\n\n if (block.content) {\n const contentArr = Array.isArray(block.content) ? block.content : [block.content];\n for (const inline of contentArr) {\n if (inline && typeof inline === \"object\") {\n if (inline.type === \"diffActions\" && inline.props && inline.props.diffIds) {\n const ids =\n typeof inline.props.diffIds === \"string\" ? inline.props.diffIds.split(\",\") : inline.props.diffIds;\n for (const id of ids) {\n const trimmed = (id || \"\").toString().trim();\n if (trimmed && !acceptedChanges.has(trimmed) && !rejectedChanges.has(trimmed)) {\n return true;\n }\n }\n }\n if (inline.props && inline.props.diffId) {\n const diffIdInline = inline.props.diffId;\n if (diffIdInline && !acceptedChanges.has(diffIdInline) && !rejectedChanges.has(diffIdInline)) {\n return true;\n }\n }\n if (inline.children && Array.isArray(inline.children)) {\n for (const child of inline.children) {\n if (hasUnresolvedDiffsRecursive(child)) return true;\n }\n }\n }\n }\n }\n if (Array.isArray(block.children)) {\n for (const child of block.children) {\n if (hasUnresolvedDiffsRecursive(child)) return true;\n }\n }\n return false;\n }\n\n let hasUnresolvedDiff = false;\n if (Array.isArray(newBlocks)) {\n hasUnresolvedDiff = newBlocks.some((block: any) => hasUnresolvedDiffsRecursive(block));\n }\n\n onChange(newBlocks, isEmpty, hasUnresolvedDiff);\n }, [editor, onChange, id, acceptedChanges, rejectedChanges]);\n\n processedContentRef.current = processedContent as any[];\n // A diff render (the suggested changes, or the text after an accept or a reject) is not the\n // parent's text: the parent learns it, and whether changes are unresolved, from the change\n // BlockNote emits when it loads it.\n const rendersDiffRef = useRef(false);\n rendersDiffRef.current = !!(diffContent && initialContent);\n\n // Utility: deep equality for arrays of blocks\n const areBlocksEqual = (a: any[], b: any[]): boolean => {\n return JSON.stringify(a) === JSON.stringify(b);\n };\n\n // Only initialize from markdownContent once per value, and only if different\n const hasInitializedFromMarkdown = useRef<string | null>(null);\n useEffect(() => {\n const updateContent = async (markdown: string) => {\n const blocks = await editor.tryParseMarkdownToBlocks(markdown);\n if (!areBlocksEqual(blocks, editor.document)) {\n editor.replaceBlocks(editor.document, blocks);\n }\n };\n\n if (markdownContent && hasInitializedFromMarkdown.current !== markdownContent) {\n hasInitializedFromMarkdown.current = markdownContent;\n updateContent(markdownContent).then(() => handleChange());\n }\n }, [markdownContent, editor]);\n\n // Update editor content when diff content changes, but only if different\n // Prevent unnecessary replaceBlocks calls that reset scroll/cursor.\n const previousContentHashRef = useRef<string | null>(null);\n useEffect(() => {\n if (!processedContent || !editor) return;\n // A collaborative editor's content IS the shared Yjs document: it has no initialContent,\n // so processedContent is [] and replaceBlocks would wipe the document it just loaded,\n // and that wipe would be synced to every other writer and stored.\n if (collaboration) return;\n const hash = JSON.stringify(processedContent);\n if (previousContentHashRef.current === hash) return; // no changes\n // New content from the parent: that is now the text it knows.\n parentKnowsEmptyRef.current = isDocumentEmpty(processedContent as any[]);\n // Skip replaceBlocks when the new initialContent is just an echo of what\n // the editor itself emitted. Without this, a form-controlled parent\n // (FormBlockNote) round-trips field.value back as initialContent on every\n // keystroke and triggers replaceBlocks, which resets the cursor and can\n // strip just-inserted inline content like mentions.\n if (lastEmittedHashRef.current === hash) {\n previousContentHashRef.current = hash;\n return;\n }\n const currentHash = JSON.stringify(editor.document);\n if (currentHash === hash) {\n previousContentHashRef.current = hash;\n return; // already in sync\n }\n if (rendersDiffRef.current) {\n loadedHashRef.current = null;\n editor.replaceBlocks(editor.document, processedContent as PartialBlock[]);\n previousContentHashRef.current = hash;\n return;\n }\n loadingFromParentRef.current = true;\n try {\n editor.replaceBlocks(editor.document, processedContent as PartialBlock[]);\n } finally {\n loadingFromParentRef.current = false;\n }\n // The parent's text, as BlockNote now holds it: a change of the same text emitted after the\n // load is not an edit either.\n loadedHashRef.current = JSON.stringify(editor.document);\n previousContentHashRef.current = hash;\n }, [processedContent, editor, collaboration]);\n\n useEffect(() => {\n if (!onWarmMentions || !initialContent || !Array.isArray(initialContent) || initialContent.length === 0) return;\n onWarmMentions(initialContent);\n }, [onWarmMentions, initialContent]);\n\n useEffect(() => {\n docRef.current.getDoc = () => editor?.document ?? [];\n selectionRef.current.getSelectedBlocks = () => {\n const sel = editor?.getSelection?.();\n const blocks = (sel as any)?.blocks;\n return Array.isArray(blocks) ? blocks : [];\n };\n }, [editor]);\n\n // Handle audio received from whisper transcription\n const _handleAudioReceived = useCallback(\n (message: string) => {\n try {\n // Ensure the editor has focus\n const editorElement = editorRef.current?.querySelector('[contenteditable=\"true\"]') as HTMLElement;\n if (editorElement && document.activeElement !== editorElement) {\n editorElement.focus();\n }\n\n // Insert the transcribed text at the current cursor position\n editor.insertInlineContent(message);\n } catch (error) {\n console.error(\"Error inserting transcribed text:\", error);\n // Fallback: try to insert at the end of the document\n try {\n const blocks = editor.document;\n if (blocks.length > 0) {\n const lastBlock = blocks[blocks.length - 1];\n editor.setTextCursorPosition(lastBlock.id, \"end\");\n editor.insertInlineContent(message);\n }\n } catch (fallbackError) {\n console.error(\"Fallback insertion also failed:\", fallbackError);\n }\n }\n },\n [editor],\n );\n\n return (\n <div\n ref={editorRef}\n className={cn(\n bordered ? \"rounded-md border border-input bg-input/20 dark:bg-input/30\" : \"\",\n \"flex flex-col w-full\",\n // Pin BlockNote's font-size so it doesn't jump from 14→16px when the\n // xl-ai AIMenu mounts. The shadcn theme sets `.bn-default-styles {\n // font-size: 16px }` explicitly; outside AI mode the form's text-sm\n // wins via cascade, but ForkYDocExtension re-evaluates the style\n // context on AI activation and the explicit 16px takes over.\n // Phone: an editable field types at 16px, or iPhone Safari zooms the\n // page in on focus. The two ranges never overlap, so neither depends on\n // CSS source order to win.\n isEditable\n ? \"md:[&_.bn-default-styles]:!text-sm max-md:[&_.bn-default-styles]:!text-base\"\n : \"[&_.bn-default-styles]:!text-sm\",\n className,\n )}\n >\n <BlockNoteView\n editor={editor}\n onChange={handleChange}\n editable={isEditable}\n formattingToolbar={false}\n slashMenu={!aiActive}\n // Follow the app theme: hardcoding \"light\" leaves dark (light-theme)\n // text on the dark card, which is nearly unreadable in dark mode.\n theme={resolvedTheme === \"dark\" ? \"dark\" : \"light\"}\n // `className` is applied by BlockNote to both the main `.bn-container`\n // AND `editor.portalElement` (the floating-UI portal root). Gate `p-4`\n // on `.bn-container` so it doesn't add padding to the empty portal\n // element and produce a phantom scrollbar on the wrapper.\n className={cn(\n \"BlockNoteView flex-1\",\n isEditable && \"[&.bn-container]:p-4\",\n // In stretch mode the parent chain caps our height via flex; without\n // these two classes the `.bn-container` keeps `min-height: auto`\n // (its content's intrinsic height) and pushes the bordered wrapper\n // — and the surrounding EditorSheet form — to scroll instead of\n // scrolling internally.\n isEditable && stretch && \"[&.bn-container]:min-h-0 [&.bn-container]:overflow-y-auto\",\n // Phone — these reach the floating menus because BlockNote puts this\n // className on its portal root too. The formatting toolbar (~450px)\n // scrolls sideways instead of losing alignment and link off-screen;\n // the slash menu is capped to the screen and drops its keyboard\n // shortcut badges, which mean nothing on a touch screen.\n \"max-md:[&_.bn-formatting-toolbar]:max-w-[calc(100vw-1rem)] max-md:[&_.bn-formatting-toolbar]:overflow-x-auto max-md:[&_.bn-formatting-toolbar>*]:shrink-0\",\n \"max-md:[&_.bn-suggestion-menu]:max-w-[calc(100vw-1rem)] max-md:[&_.bn-suggestion-menu_[role=option]>[data-position=right]]:hidden\",\n size === \"sm\" && \"small\",\n )}\n >\n <BlockNoteEditorFormattingToolbar showAI={aiActive} />\n {enableMentions && mentionSearchFn && (\n <BlockNoteEditorMentionSuggestionMenu\n editor={editor}\n mentionSearchFn={mentionSearchFn}\n mentionSearchParams={mentionSearchParams}\n suggestionMenuComponent={suggestionMenuComponent}\n />\n )}\n {renderOverlays?.(editor)}\n {enableMentions && mentionResolveFn && (\n <BlockNoteEditorMentionHoverCard containerRef={editorRef} mentionResolveFn={mentionResolveFn} />\n )}\n {aiActive && (\n <SuggestionMenuController\n triggerCharacter=\"/\"\n getItems={async (query: string) =>\n filterSuggestionItems([...getDefaultReactSlashMenuItems(editor), ...getAISlashMenuItems(editor)], query)\n }\n />\n )}\n {aiActive && <AIMenuController aiMenu={() => <NarrAIMenu actions={aiConfig?.actions} />} />}\n </BlockNoteView>\n </div>\n );\n}\n","import { LayoutTemplateIcon, SparklesIcon } from \"lucide-react\";\nimport React from \"react\";\n\n/**\n * Whole-document AI actions an editor can offer in its AI menu when nothing\n * is selected. Each maps to a backend `type` discriminator; NO prompt text\n * lives here. Selection-edit actions (Improve, Fix spelling, …) are separate\n * and always available.\n */\nexport type BlockNoteAiGenerateAction = \"fill-template\" | \"draft-impression\";\n\nexport const DEFAULT_AI_GENERATE_ACTIONS: BlockNoteAiGenerateAction[] = [\"fill-template\"];\n\nexport type AiGenerateMenuItem = {\n key: string;\n title: string;\n aliases: string[];\n /** BlockNote's DefaultReactSuggestionItem types icon as an element, not ReactNode. */\n icon: React.JSX.Element;\n size: \"small\";\n onItemClick: () => void;\n};\n\n/** `titleKey` is a message key; the caller's translator resolves it to the shown title. */\ntype AiGenerateItemDefinition = Omit<AiGenerateMenuItem, \"onItemClick\" | \"title\"> & { titleKey: string };\n\nconst ITEMS: Record<BlockNoteAiGenerateAction, AiGenerateItemDefinition> = {\n \"fill-template\": {\n key: \"generate_from_template\",\n titleKey: \"ui.editor.ai.generate_from_template\",\n aliases: [\"generate\", \"template\", \"fill\"],\n icon: <LayoutTemplateIcon size={18} />,\n size: \"small\",\n },\n \"draft-impression\": {\n key: \"suggest_impression\",\n titleKey: \"ui.editor.ai.suggest_impression\",\n aliases: [\"suggest\", \"impression\"],\n icon: <SparklesIcon size={18} />,\n size: \"small\",\n },\n};\n\nexport function generateActionItems(\n actions: BlockNoteAiGenerateAction[] | undefined,\n invoke: (type: BlockNoteAiGenerateAction) => void,\n translate: (key: string) => string,\n): AiGenerateMenuItem[] {\n return (actions ?? DEFAULT_AI_GENERATE_ACTIONS).map((type) => {\n const { titleKey, ...item } = ITEMS[type];\n return { ...item, title: translate(titleKey), onItemClick: () => invoke(type) };\n });\n}\n","\"use client\";\n\nimport {\n BasicTextStyleButton,\n BlockTypeSelect,\n CreateLinkButton,\n FileCaptionButton,\n FileReplaceButton,\n FormattingToolbar,\n FormattingToolbarController,\n TextAlignButton,\n} from \"@blocknote/react\";\nimport { AIToolbarButton } from \"@blocknote/xl-ai\";\n\nexport function BlockNoteEditorFormattingToolbar({ showAI = false }: { showAI?: boolean }) {\n return (\n <FormattingToolbarController\n formattingToolbar={() => (\n <FormattingToolbar>\n <BlockTypeSelect key={\"blockTypeSelect\"} />\n\n <FileCaptionButton key={\"fileCaptionButton\"} />\n <FileReplaceButton key={\"replaceFileButton\"} />\n\n <BasicTextStyleButton basicTextStyle={\"bold\"} key={\"boldStyleButton\"} />\n <BasicTextStyleButton basicTextStyle={\"italic\"} key={\"italicStyleButton\"} />\n <BasicTextStyleButton basicTextStyle={\"underline\"} key={\"underlineStyleButton\"} />\n <BasicTextStyleButton basicTextStyle={\"strike\"} key={\"strikeStyleButton\"} />\n\n <TextAlignButton textAlignment={\"left\"} key={\"textAlignLeftButton\"} />\n <TextAlignButton textAlignment={\"center\"} key={\"textAlignCenterButton\"} />\n <TextAlignButton textAlignment={\"right\"} key={\"textAlignRightButton\"} />\n\n <CreateLinkButton key={\"createLinkButton\"} />\n\n {showAI ? <AIToolbarButton key={\"aiToolbarButton\"} /> : null}\n </FormattingToolbar>\n )}\n />\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,SAAS,iBAAiB,2BAA2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,UACnB,WAAW,CAAC;AAAA,UAGZ,OAAO,kBAAkB,SAAS,SAAS;AAAA,UAK3C,WAAW;AAAA,YACT;AAAA,YACA,cAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,YAMd,cAAc,WAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,YAMzB;AAAA,YACA;AAAA,YACA,SAAS,QAAQ;AAAA,UACnB;AAAA,UAEA;AAAA,4BAAAD,KAAC,oCAAiC,QAAQ,UAAU;AAAA,YACnD,kBAAkB,mBACjB,gBAAAA;AAAA,cAAC;AAAA;AAAA,gBACC;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA;AAAA;AAAA,YACF;AAAA,YAED,iBAAiB,MAAM;AAAA,YACvB,kBAAkB,oBACjB,gBAAAA,KAAC,mCAAgC,cAAc,WAAW,kBAAoC;AAAA,YAE/F,YACC,gBAAAA;AAAA,cAAC;AAAA;AAAA,gBACC,kBAAiB;AAAA,gBACjB,UAAU,OAAO,UACf,sBAAsB,CAAC,GAAG,8BAA8B,MAAM,GAAG,GAAG,oBAAoB,MAAM,CAAC,GAAG,KAAK;AAAA;AAAA,YAE3G;AAAA,YAED,YAAY,gBAAAA,KAAC,oBAAiB,QAAQ,MAAM,gBAAAA,KAAC,cAAW,SAAS,UAAU,SAAS,GAAI;AAAA;AAAA;AAAA,MAC3F;AAAA;AAAA,EACF;AAEJ;AA5pBwB;","names":["SparklesIcon","jsx","jsx","jsxs","SparklesIcon","removeTrailingEmptyBlocks","type","id"]}
@@ -6,7 +6,11 @@
6
6
 
7
7
 
8
8
 
9
- var _chunk6RWEYSYEjs = require('./chunk-6RWEYSYE.js');
9
+
10
+
11
+
12
+
13
+ var _chunkWXTEAATGjs = require('./chunk-WXTEAATG.js');
10
14
  require('./chunk-SYMI4IDW.js');
11
15
  require('./chunk-3EPNHTMH.js');
12
16
 
@@ -38,7 +42,7 @@ var _chunk7QVYU63Ejs = require('./chunk-7QVYU63E.js');
38
42
 
39
43
  // src/components/editors/BlockNoteEditor.tsx
40
44
  var _core = require('@blocknote/core');
41
- var _locales = require('@blocknote/core/locales'); var coreLocales2 = _interopRequireWildcard(_locales); var coreLocales = _interopRequireWildcard(_locales);
45
+ var _locales = require('@blocknote/core/locales'); var coreLocales = _interopRequireWildcard(_locales);
42
46
 
43
47
 
44
48
 
@@ -130,62 +134,6 @@ function BlockNoteEditorFormattingToolbar({ showAI = false }) {
130
134
  }
131
135
  _chunk7QVYU63Ejs.__name.call(void 0, BlockNoteEditorFormattingToolbar, "BlockNoteEditorFormattingToolbar");
132
136
 
133
- // src/components/editors/blockNoteEditorOptions.ts
134
-
135
- var _yjs = require('@blocknote/core/yjs');
136
- function buildBlockNoteEditorOptions(params) {
137
- const { aiExtension, coreDictionary, aiDictionary, collaboration } = params;
138
- const options = {
139
- placeholders: {
140
- emptyDocument: params.placeholder
141
- },
142
- schema: params.schema,
143
- uploadFile: params.disableUploads ? void 0 : params.uploadFile,
144
- extensions: aiExtension ? [aiExtension] : void 0,
145
- dictionary: aiExtension ? { ...coreDictionary, ai: aiDictionary } : coreDictionary === coreLocales.en ? void 0 : coreDictionary
146
- };
147
- if (collaboration) return _yjs.withCollaboration.call(void 0, { ...options, collaboration });
148
- return { ...options, initialContent: params.initialContent };
149
- }
150
- _chunk7QVYU63Ejs.__name.call(void 0, buildBlockNoteEditorOptions, "buildBlockNoteEditorOptions");
151
- function resolveEditable(params) {
152
- return params.editable !== void 0 ? params.editable : params.onChange !== void 0;
153
- }
154
- _chunk7QVYU63Ejs.__name.call(void 0, resolveEditable, "resolveEditable");
155
- function isBlockEmpty(block) {
156
- if (!block || typeof block !== "object") return true;
157
- if (block.type !== "paragraph") return false;
158
- if (Array.isArray(block.children) && block.children.length > 0 && !isDocumentEmpty(block.children)) {
159
- return false;
160
- }
161
- if (Array.isArray(block.content)) {
162
- for (const inline of block.content) {
163
- if (typeof inline === "string") {
164
- if (inline.trim()) return false;
165
- } else if (inline && typeof inline === "object") {
166
- if (inline.type !== "text") return false;
167
- if (typeof inline.text === "string" && inline.text.trim()) return false;
168
- }
169
- }
170
- } else if (typeof block.content === "string" && block.content.trim()) {
171
- return false;
172
- }
173
- return true;
174
- }
175
- _chunk7QVYU63Ejs.__name.call(void 0, isBlockEmpty, "isBlockEmpty");
176
- function isDocumentEmpty(blocks) {
177
- if (!Array.isArray(blocks) || blocks.length === 0) return true;
178
- return blocks.every(isBlockEmpty);
179
- }
180
- _chunk7QVYU63Ejs.__name.call(void 0, isDocumentEmpty, "isDocumentEmpty");
181
- function removeTrailingEmptyBlocks(blocks) {
182
- if (!blocks || blocks.length === 0) return blocks;
183
- const result = [...blocks];
184
- while (result.length > 1 && isBlockEmpty(result[result.length - 1])) result.pop();
185
- return result;
186
- }
187
- _chunk7QVYU63Ejs.__name.call(void 0, removeTrailingEmptyBlocks, "removeTrailingEmptyBlocks");
188
-
189
137
  // src/components/editors/BlockNoteEditor.tsx
190
138
 
191
139
  var createDiffActionsInlineContentSpec = /* @__PURE__ */ _chunk7QVYU63Ejs.__name.call(void 0, (handleAcceptChange, handleRejectChange, labels) => {
@@ -204,7 +152,7 @@ var createDiffActionsInlineContentSpec = /* @__PURE__ */ _chunk7QVYU63Ejs.__name
204
152
  const diffIds = props.inlineContent.props.diffIds;
205
153
  return /* @__PURE__ */ _jsxruntime.jsxs.call(void 0, "span", { className: "diff-actions-container mx-2 inline-flex items-center gap-1 align-middle", children: [
206
154
  /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
207
- _chunk6RWEYSYEjs.Button,
155
+ _chunkWXTEAATGjs.Button,
208
156
  {
209
157
  title: labels.accept,
210
158
  onClick: (e) => {
@@ -216,7 +164,7 @@ var createDiffActionsInlineContentSpec = /* @__PURE__ */ _chunk7QVYU63Ejs.__name
216
164
  }
217
165
  ),
218
166
  /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
219
- _chunk6RWEYSYEjs.Button,
167
+ _chunkWXTEAATGjs.Button,
220
168
  {
221
169
  title: labels.reject,
222
170
  className: "mx-2 p-0",
@@ -407,11 +355,11 @@ function BlockNoteEditor({
407
355
  disableUploads,
408
356
  editable
409
357
  }) {
410
- const isEditable = resolveEditable({ editable, onChange });
358
+ const isEditable = _chunkWXTEAATGjs.resolveEditable.call(void 0, { editable, onChange });
411
359
  const t = _nextintl.useTranslations.call(void 0, );
412
360
  const locale = _chunkNP3AFULUjs.useI18nLocale.call(void 0, );
413
361
  const { resolvedTheme } = _nextthemes.useTheme.call(void 0, );
414
- const company = _nullishCoalesce(_optionalChain([_chunk6RWEYSYEjs.useCurrentUserContextOptional.call(void 0, ), 'optionalAccess', _6 => _6.company]), () => ( null));
362
+ const company = _nullishCoalesce(_optionalChain([_chunkWXTEAATGjs.useCurrentUserContextOptional.call(void 0, ), 'optionalAccess', _6 => _6.company]), () => ( null));
415
363
  const [acceptedChanges, setAcceptedChanges] = _react3.useState.call(void 0, /* @__PURE__ */ new Set());
416
364
  const [rejectedChanges, setRejectedChanges] = _react3.useState.call(void 0, /* @__PURE__ */ new Set());
417
365
  const editorRef = _react3.useRef.call(void 0, null);
@@ -452,7 +400,7 @@ function BlockNoteEditor({
452
400
  [handleAcceptChange, handleRejectChange, t]
453
401
  );
454
402
  const mentionSpec = _react3.useMemo.call(void 0,
455
- () => _chunk6RWEYSYEjs.createMentionInlineContentSpec.call(void 0, mentionResolveFn, disableMentions, mentionNameResolver),
403
+ () => _chunkWXTEAATGjs.createMentionInlineContentSpec.call(void 0, mentionResolveFn, disableMentions, mentionNameResolver),
456
404
  [disableMentions, mentionResolveFn, mentionNameResolver]
457
405
  );
458
406
  const schema = _react3.useMemo.call(void 0,
@@ -521,7 +469,7 @@ function BlockNoteEditor({
521
469
  const uploadImage = _react3.useCallback.call(void 0,
522
470
  async (file) => {
523
471
  if (!company && !uploadKeyPrefix) {
524
- _chunk6RWEYSYEjs.errorToast.call(void 0, {
472
+ _chunkWXTEAATGjs.errorToast.call(void 0, {
525
473
  title: t(`common.errors.upload`),
526
474
  error: t(`common.errors.upload_description`)
527
475
  });
@@ -551,7 +499,7 @@ function BlockNoteEditor({
551
499
  (blocks) => {
552
500
  if (!blocks || blocks.length === 0) return blocks;
553
501
  if (onChange !== void 0) return blocks;
554
- return removeTrailingEmptyBlocks(blocks);
502
+ return _chunkWXTEAATGjs.removeTrailingEmptyBlocks.call(void 0, blocks);
555
503
  },
556
504
  [onChange]
557
505
  );
@@ -599,11 +547,11 @@ function BlockNoteEditor({
599
547
  return void 0;
600
548
  }, [processedContent]);
601
549
  const language = locale.split("-")[0];
602
- const coreDictionary = _nullishCoalesce(coreLocales2[language], () => ( coreLocales2.en));
550
+ const coreDictionary = _nullishCoalesce(coreLocales[language], () => ( coreLocales.en));
603
551
  const aiDictionary = _nullishCoalesce(aiLocales[language], () => ( aiLocales.en));
604
552
  const editor = _react.useCreateBlockNote.call(void 0,
605
553
  _react3.useMemo.call(void 0,
606
- () => buildBlockNoteEditorOptions({
554
+ () => _chunkWXTEAATGjs.buildBlockNoteEditorOptions.call(void 0, {
607
555
  placeholder: placeholder || t(`common.blocknote.placeholder`),
608
556
  schema,
609
557
  initialContent: validatedInitialContent,
@@ -701,8 +649,8 @@ function BlockNoteEditor({
701
649
  loadedHashRef.current = null;
702
650
  }
703
651
  lastEmittedHashRef.current = newHash;
704
- const isEmpty = isDocumentEmpty(newBlocks);
705
- const wasEmpty = _nullishCoalesce(parentKnowsEmptyRef.current, () => ( isDocumentEmpty(processedContentRef.current)));
652
+ const isEmpty = _chunkWXTEAATGjs.isDocumentEmpty.call(void 0, newBlocks);
653
+ const wasEmpty = _nullishCoalesce(parentKnowsEmptyRef.current, () => ( _chunkWXTEAATGjs.isDocumentEmpty.call(void 0, processedContentRef.current)));
706
654
  if (isEmpty && wasEmpty) return;
707
655
  parentKnowsEmptyRef.current = isEmpty;
708
656
  function hasUnresolvedDiffsRecursive(block) {
@@ -779,7 +727,7 @@ function BlockNoteEditor({
779
727
  if (collaboration) return;
780
728
  const hash = JSON.stringify(processedContent);
781
729
  if (previousContentHashRef.current === hash) return;
782
- parentKnowsEmptyRef.current = isDocumentEmpty(processedContent);
730
+ parentKnowsEmptyRef.current = _chunkWXTEAATGjs.isDocumentEmpty.call(void 0, processedContent);
783
731
  if (lastEmittedHashRef.current === hash) {
784
732
  previousContentHashRef.current = hash;
785
733
  return;
@@ -888,7 +836,7 @@ function BlockNoteEditor({
888
836
  children: [
889
837
  /* @__PURE__ */ _jsxruntime.jsx.call(void 0, BlockNoteEditorFormattingToolbar, { showAI: aiActive }),
890
838
  enableMentions && mentionSearchFn && /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
891
- _chunk6RWEYSYEjs.BlockNoteEditorMentionSuggestionMenu,
839
+ _chunkWXTEAATGjs.BlockNoteEditorMentionSuggestionMenu,
892
840
  {
893
841
  editor,
894
842
  mentionSearchFn,
@@ -897,7 +845,7 @@ function BlockNoteEditor({
897
845
  }
898
846
  ),
899
847
  _optionalChain([renderOverlays, 'optionalCall', _29 => _29(editor)]),
900
- enableMentions && mentionResolveFn && /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _chunk6RWEYSYEjs.BlockNoteEditorMentionHoverCard, { containerRef: editorRef, mentionResolveFn }),
848
+ enableMentions && mentionResolveFn && /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _chunkWXTEAATGjs.BlockNoteEditorMentionHoverCard, { containerRef: editorRef, mentionResolveFn }),
901
849
  aiActive && /* @__PURE__ */ _jsxruntime.jsx.call(void 0,
902
850
  _react.SuggestionMenuController,
903
851
  {
@@ -916,4 +864,4 @@ _chunk7QVYU63Ejs.__name.call(void 0, BlockNoteEditor, "BlockNoteEditor");
916
864
 
917
865
 
918
866
  exports.default = BlockNoteEditor;
919
- //# sourceMappingURL=BlockNoteEditor-SWDRMNLT.js.map
867
+ //# sourceMappingURL=BlockNoteEditor-KGCHQQVY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/work/nextjs-jsonapi/nextjs-jsonapi/dist/BlockNoteEditor-KGCHQQVY.js","../src/components/editors/BlockNoteEditor.tsx","../src/components/editors/BlockNoteEditorAiActions.tsx","../src/components/editors/BlockNoteEditorFormattingToolbar.tsx"],"names":["jsx","jsxs","SparklesIcon","removeTrailingEmptyBlocks","type"],"mappings":"AAAA,+8BAAY;AACZ;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,sDAA4B;AAC5B,+BAA4B;AAC5B,+BAA4B;AAC5B;AACE;AACF,sDAA4B;AAC5B,+BAA4B;AAC5B;AACE;AACA;AACA;AACA;AACF,sDAA4B;AAC5B,+BAA4B;AAC5B,+BAA4B;AAC5B,+BAA4B;AAC5B,+BAA4B;AAC5B,+BAA4B;AAC5B,+BAA4B;AAC5B,+BAA4B;AAC5B;AACE;AACF,sDAA4B;AAC5B;AACE;AACF,sDAA4B;AAC5B;AACE;AACF,sDAA4B;AAC5B;AACA;ACxCA,uCAAgG;AAChG,uGAA6B;AAC7B;AACE;AAEA;AACA;AAEA;AACA;AACA;AACA;AAAA,yCACK;AACP,2CAA8B;AAC9B,uCAAO;AACP;AACE;AACA;AACA;AACA;AACA;AACA;AAAA,wCACK;AACP,wGAA2B;AAC3B,sCAAO;AACP,wBAAqC;AACrC,2CAA0F;AAC1F,qCAAgC;AAChC,yCAAyB;AACzB,+BAAyE;ADwCzE;AACA;AExEA;AA+BU,+CAAA;AApBH,IAAM,4BAAA,EAA2D,CAAC,eAAe,CAAA;AAexF,IAAM,MAAA,EAAqE;AAAA,EACzE,eAAA,EAAiB;AAAA,IACf,GAAA,EAAK,wBAAA;AAAA,IACL,QAAA,EAAU,qCAAA;AAAA,IACV,OAAA,EAAS,CAAC,UAAA,EAAY,UAAA,EAAY,MAAM,CAAA;AAAA,IACxC,IAAA,kBAAM,6BAAA,+BAAC,EAAA,EAAmB,IAAA,EAAM,GAAA,CAAI,CAAA;AAAA,IACpC,IAAA,EAAM;AAAA,EACR,CAAA;AAAA,EACA,kBAAA,EAAoB;AAAA,IAClB,GAAA,EAAK,oBAAA;AAAA,I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EA,UAAA;AAAC,4BAAA;AAEC,YAAA;AAAC,cAAA;AAAA,cAAA;AACC,gBAAA;AACA,gBAAA;AACA,gBAAA;AACA,gBAAA;AAAA,cAAA;AACF,YAAA;AAEsB,4BAAA;AAEtB,YAAA;AAGAD,YAAAA;AAAC,cAAA;AAAA,cAAA;AACkB,gBAAA;AAEf,gBAAA;AAAuG,cAAA;AAE3G,YAAA;AAEY,YAAA;AAA2E,UAAA;AAAA,QAAA;AAC3F,MAAA;AAAA,IAAA;AACF,EAAA;AAEJ;AA5pBwB;ADgdwC;AACA;AACA","file":"/home/runner/work/nextjs-jsonapi/nextjs-jsonapi/dist/BlockNoteEditor-KGCHQQVY.js","sourcesContent":[null,"\"use client\";\n\nimport { BlockNoteSchema, defaultInlineContentSpecs, filterSuggestionItems, PartialBlock } from \"@blocknote/core\";\nimport * as coreLocales from \"@blocknote/core/locales\";\nimport {\n createReactInlineContentSpec,\n DefaultReactSuggestionItem,\n getDefaultReactSlashMenuItems,\n SuggestionMenuController,\n SuggestionMenuProps,\n useBlockNoteEditor,\n useCreateBlockNote,\n useExtension,\n useExtensionState,\n} from \"@blocknote/react\";\nimport { BlockNoteView } from \"@blocknote/shadcn\";\nimport \"@blocknote/shadcn/style.css\";\nimport {\n AIExtension,\n AIMenuController,\n getAISlashMenuItems,\n getDefaultAIMenuItems,\n PromptSuggestionMenu,\n useAIDictionary,\n} from \"@blocknote/xl-ai\";\nimport * as aiLocales from \"@blocknote/xl-ai/locales\";\nimport \"@blocknote/xl-ai/style.css\";\nimport { DefaultChatTransport } from \"ai\";\nimport { CheckIcon, LanguagesIcon, SparklesIcon, TypeIcon, WandSparklesIcon, XIcon } from \"lucide-react\";\nimport { useTranslations } from \"next-intl\";\nimport { useTheme } from \"next-themes\";\nimport React, { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { getPublicApiUrl } from \"../../client/config\";\nimport { getClientToken } from \"../../client/token\";\nimport { useCurrentUserContextOptional } from \"../../contexts\";\nimport { S3Interface } from \"../../features/s3/data\";\nimport { S3Service } from \"../../features/s3/data/s3.service\";\nimport { UserInterface } from \"../../features/user/data\";\nimport { useI18nLocale } from \"../../i18n/config\";\nimport { Button } from \"../../shadcnui\";\nimport { BlockNoteDiffUtil, BlockNoteWordDiffRendererUtil, cn } from \"../../utils\";\nimport { errorToast } from \"../errors\";\nimport { BlockNoteAiGenerateAction, generateActionItems } from \"./BlockNoteEditorAiActions\";\nimport { BlockNoteEditorFormattingToolbar } from \"./BlockNoteEditorFormattingToolbar\";\nimport {\n type BlockNoteCollaboration,\n buildBlockNoteEditorOptions,\n isDocumentEmpty,\n removeTrailingEmptyBlocks as trimTrailingEmptyBlocks,\n resolveEditable,\n} from \"./blockNoteEditorOptions\";\nimport { BlockNoteEditorMentionHoverCard } from \"./BlockNoteEditorMentionHoverCard\";\nimport {\n createMentionInlineContentSpec,\n type MentionNameResolver,\n type MentionResolveFn,\n} from \"./BlockNoteEditorMentionInlineContent\";\nimport { BlockNoteEditorMentionSuggestionMenu } from \"./BlockNoteEditorSuggestionMenuController\";\n\n/**\n * Lets app code trigger a whole-document AI action from OUTSIDE the editor\n * (a visible button next to the field label, for instance) without owning the\n * BlockNote instance. Delivered through a plain prop, not a React `ref`:\n * `BlockNoteEditorContainer` is a `next/dynamic` import wrapped in\n * `React.memo`, and refs do not pass through that reliably.\n */\nexport type BlockNoteAiHandle = { invokeAi: (type: BlockNoteAiGenerateAction) => void };\n\nexport type BlockNoteAiConfig = {\n endpoint: string;\n entityType: string;\n entityId?: string;\n /** Whole-document actions shown when nothing is selected. Default: [\"fill-template\"]. */\n actions?: BlockNoteAiGenerateAction[];\n};\n\nexport type BlockNoteEditorProps = {\n id: string;\n type: string;\n initialContent?: PartialBlock[];\n onChange?: (content: any, isEmpty: boolean, hasUnresolvedDiff: boolean) => void;\n size?: \"sm\" | \"md\";\n className?: string;\n markdownContent?: string;\n diffContent?: PartialBlock[];\n placeholder?: string;\n bordered?: boolean;\n /**\n * Storage folder for pasted images, used instead of the current company's\n * `companies/<companyId>/<type>` folder: the image key becomes\n * `<uploadKeyPrefix>/<id>/<file name>`. For platform content edited by users\n * who belong to no company (the blog). Omitted: the company folder, as before.\n */\n uploadKeyPrefix?: string;\n inlineContentSpecs?: Record<string, any>;\n renderOverlays?: (editor: any) => React.ReactNode;\n enableMentions?: boolean;\n disableMentions?: boolean;\n mentionSearchFn?: (\n query: string,\n params?: Record<string, string>,\n ) => Promise<import(\"./BlockNoteEditorSuggestionMenuController\").MentionItem[]>;\n mentionSearchParams?: Record<string, string>;\n mentionResolveFn?: MentionResolveFn;\n suggestionMenuComponent?: React.FC<SuggestionMenuProps<DefaultReactSuggestionItem>>;\n mentionNameResolver?: MentionNameResolver;\n onWarmMentions?: (blocks: PartialBlock[]) => void;\n aiConfig?: BlockNoteAiConfig;\n // When the editor is inside a bounded flex column (parent gives it a real\n // height via flex-1+min-h-0), set this so `.bn-container` shrinks to that\n // height and scrolls internally. Without it the editor grows to fit its\n // content and pushes the surrounding form to scroll instead.\n stretch?: boolean;\n // Gates AI on top of `aiConfig` (credit availability, etc.). Defaults to\n // true so existing callers that only pass `aiConfig` are unaffected. When\n // false, the AI toolbar button and AI slash items are hidden, the editor\n // falls back to the plain slash menu, an open AI menu or run is closed, and\n // no AI request is sent. The AI extension itself stays: toggling this never\n // rebuilds the editor, so unsaved text survives credits running out.\n aiEnabled?: boolean;\n // Filled with a {@link BlockNoteAiHandle} while the editor is mounted and AI\n // is on, so a control outside the editor can run a whole-document AI action.\n // Cleared on unmount and whenever AI is unavailable.\n aiHandleRef?: React.MutableRefObject<BlockNoteAiHandle | null>;\n /**\n * Live co-editing (Yjs). When set, the Yjs document is the content: used\n * instead of `initialContent`/`onChange`. Changing `collaboration.fragment`\n * rebuilds the editor.\n */\n collaboration?: BlockNoteCollaboration;\n /** true: image uploads are off (no paste/drop upload, no upload tab). */\n disableUploads?: boolean;\n /**\n * Overrides the default `onChange !== undefined` editability, e.g. for a\n * collaborative editor, which has no `onChange`.\n */\n editable?: boolean;\n};\n\nconst createDiffActionsInlineContentSpec = (\n handleAcceptChange: (diffId: string) => void,\n handleRejectChange: (diffId: string) => void,\n labels: { accept: string; reject: string },\n) => {\n return createReactInlineContentSpec(\n {\n type: \"diffActions\",\n propSchema: {\n diffIds: {\n default: \"\",\n },\n },\n content: \"none\",\n },\n {\n render: (props) => {\n const diffIds = props.inlineContent.props.diffIds;\n\n return (\n <span className=\"diff-actions-container mx-2 inline-flex items-center gap-1 align-middle\">\n <Button\n title={labels.accept}\n onClick={(e) => {\n e.preventDefault();\n e.stopPropagation();\n diffIds.split(\",\").forEach((id: string) => handleAcceptChange(id.trim()));\n }}\n >\n <CheckIcon className=\"text-success h-3 w-3\" />\n </Button>\n <Button\n title={labels.reject}\n className=\"mx-2 p-0\"\n onClick={(e) => {\n e.preventDefault();\n e.stopPropagation();\n diffIds.split(\",\").forEach((id: string) => handleRejectChange(id.trim()));\n }}\n >\n <XIcon className=\"text-destructive h-3 w-3\" />\n </Button>\n </span>\n );\n },\n },\n );\n};\n\n/**\n * Custom AI menu wrapper. Surfaces our backend-driven action items\n * (Improve Writing, Fix Spelling) above the free-form prompt input.\n *\n * Why a custom wrapper instead of `<AIMenu items={…}>` with the BlockNote\n * defaults: BlockNote's `PromptSuggestionMenu` hijacks Enter to pick the\n * highlighted item whenever `items.length > 0`. We gate items on\n * - status === \"user-input\"\n * - editor has a selection\n * - prompt input is empty\n * so the moment the user types, items disappear and Enter falls back to\n * free-form submission. Outside `user-input` (review / error states) we\n * keep BlockNote's default review buttons (accept/revert/retry/cancel).\n *\n * Each custom item passes a `type` discriminator on `chatRequestOptions.body`.\n * That field flows through `chat.sendMessage(msg, opts)` to the transport's\n * `prepareSendMessagesRequest({messages, body})` (see types.ts in\n * `@blocknote/xl-ai` — `ChatRequestOptions = Parameters<Chat[\"sendMessage\"]>[1]`).\n * The backend dispatcher reads `body.type` and routes to a per-type handler\n * with its own canonical prompt. NO prompt text lives in this file.\n */\nfunction NarrAIMenu({ actions }: { actions?: BlockNoteAiGenerateAction[] }) {\n const t = useTranslations();\n const editor = useBlockNoteEditor();\n const ai = useExtension(AIExtension);\n const dict = useAIDictionary();\n const status = useExtensionState(AIExtension, {\n selector: (s) => (s.aiMenuState !== \"closed\" ? s.aiMenuState.status : \"closed\"),\n });\n const [prompt, setPrompt] = useState(\"\");\n // Set by items that pre-fill the input (Translate) so handleSubmit knows\n // which `type` to attach when the user submits the captured text. Cleared\n // after submit or on status change.\n const pendingTypeRef = useRef<string | null>(null);\n\n useEffect(() => {\n if (status === \"ai-writing\" || status === \"user-reviewing\" || status === \"error\" || status === \"closed\") {\n setPrompt(\"\");\n pendingTypeRef.current = null;\n }\n }, [status]);\n\n // Selection-edit ops operate per-block. If the user's selection only\n // covers part of a block (cursor mid-paragraph dragged to mid-next), the\n // rewrite would silently replace the WHOLE containing blocks — beyond\n // what the user highlighted. Expand the selection to whole-block bounds\n // BEFORE invokeAI so the user sees exactly what will be rewritten.\n const expandSelectionToBlocks = useCallback(() => {\n const sel = editor.getSelection?.();\n const blocks = (sel as any)?.blocks;\n if (!Array.isArray(blocks) || blocks.length === 0) return;\n const first = blocks[0];\n const last = blocks[blocks.length - 1];\n try {\n (editor as any).setSelection?.(first, last);\n } catch {\n // If BlockNote's setSelection signature changes, fail silently — the\n // backend still operates per-block, so we just lose the visual hint.\n }\n }, [editor]);\n\n const items = useMemo(() => {\n // Outside user-input (reviewing / error), use BlockNote's default\n // review buttons (accept/revert/retry/cancel). Need to wrap onItemClick\n // because the default items expect a setPrompt argument.\n if (status !== \"user-input\") {\n return getDefaultAIMenuItems(editor, status).map((item) => ({\n ...item,\n onItemClick: () => item.onItemClick(setPrompt),\n }));\n }\n const hasSelection = editor.getSelection() !== undefined;\n const hasTyped = prompt.trim().length > 0;\n // Once the user starts typing, hide all items so Enter submits the\n // free-form (or pending-type) prompt instead of being hijacked.\n if (hasTyped) return [];\n\n const invokeGenerate = (type: BlockNoteAiGenerateAction) => {\n void ai.invokeAI({\n userPrompt: type,\n useSelection: false,\n chatRequestOptions: { body: { type } },\n });\n };\n // Whole-document items are shown in BOTH contexts (with and without\n // selection) because they operate on the whole document — they ignore any\n // active selection. Listed first so the first one is the\n // default-highlighted item.\n const generateItems = generateActionItems(actions, invokeGenerate, t);\n\n if (hasSelection) {\n // Selection-edit items + the always-available whole-document items.\n // Each selection item invokes ai.invokeAI with chatRequestOptions\n // carrying the `type` body field. The userPrompt is a short tag — the\n // backend ignores it and uses the canonical prompt for the type instead.\n return [\n ...generateItems,\n {\n key: \"improve_writing\",\n title: t(\"ui.editor.ai.improve_writing\"),\n aliases: [\"improve\", \"rewrite\", \"polish\"],\n icon: <SparklesIcon size={18} />,\n size: \"small\" as const,\n onItemClick: () => {\n expandSelectionToBlocks();\n void ai.invokeAI({\n userPrompt: \"improve-writing\",\n useSelection: true,\n chatRequestOptions: { body: { type: \"improve-writing\" } },\n });\n },\n },\n {\n key: \"fix_spelling\",\n title: t(\"ui.editor.ai.fix_spelling\"),\n aliases: [\"spelling\", \"grammar\", \"typo\"],\n icon: <TypeIcon size={18} />,\n size: \"small\" as const,\n onItemClick: () => {\n expandSelectionToBlocks();\n void ai.invokeAI({\n userPrompt: \"fix-spelling\",\n useSelection: true,\n chatRequestOptions: { body: { type: \"fix-spelling\" } },\n });\n },\n },\n {\n key: \"translate\",\n title: t(\"ui.editor.ai.translate\"),\n aliases: [\"translate\", \"language\"],\n icon: <LanguagesIcon size={18} />,\n size: \"small\" as const,\n // Pre-fills the input with a placeholder. User appends/replaces\n // with the target language and submits via Enter. handleSubmit\n // reads pendingTypeRef and forwards `type: \"translate\"`. We\n // expand the selection now so the user sees the scope before\n // typing the language — handleSubmit doesn't re-expand.\n onItemClick: () => {\n expandSelectionToBlocks();\n pendingTypeRef.current = \"translate\";\n setPrompt(t(\"ui.editor.ai.translate_prefill\"));\n },\n },\n {\n key: \"simplify\",\n title: t(\"ui.editor.ai.simplify\"),\n aliases: [\"simplify\", \"easier\", \"plain\"],\n icon: <WandSparklesIcon size={18} />,\n size: \"small\" as const,\n onItemClick: () => {\n expandSelectionToBlocks();\n void ai.invokeAI({\n userPrompt: \"simplify\",\n useSelection: true,\n chatRequestOptions: { body: { type: \"simplify\" } },\n });\n },\n },\n ];\n }\n\n // No selection (the /ai slash menu path): just the whole-document items.\n // Free-form typing still works — once the user types, items hide and\n // Enter submits with no type (backend defaults to fill-template).\n return generateItems;\n }, [editor, status, prompt, ai, expandSelectionToBlocks, actions, t]);\n\n const handleSubmit = useCallback(\n async (userPrompt: string) => {\n if (!userPrompt.trim()) return;\n const pendingType = pendingTypeRef.current;\n pendingTypeRef.current = null;\n const body = pendingType ? { type: pendingType } : undefined;\n await ai.invokeAI({\n userPrompt,\n useSelection: editor.getSelection() !== undefined,\n ...(body ? { chatRequestOptions: { body } } : {}),\n });\n },\n [ai, editor],\n );\n\n const placeholder =\n status === \"thinking\"\n ? dict.ai_menu.status.thinking\n : status === \"ai-writing\"\n ? dict.ai_menu.status.editing\n : status === \"error\"\n ? dict.ai_menu.status.error\n : dict.ai_menu.input_placeholder;\n\n const disabled = status === \"thinking\" || status === \"ai-writing\";\n\n return (\n <PromptSuggestionMenu\n items={items}\n onManualPromptSubmit={handleSubmit}\n promptText={prompt}\n onPromptTextChange={setPrompt}\n placeholder={placeholder}\n disabled={disabled}\n icon={\n <div className=\"bn-combobox-icon\">\n <SparklesIcon size={16} />\n </div>\n }\n />\n );\n}\n\nexport default function BlockNoteEditor({\n id,\n type,\n initialContent,\n onChange,\n size,\n className,\n markdownContent,\n diffContent,\n placeholder,\n bordered,\n uploadKeyPrefix,\n inlineContentSpecs,\n renderOverlays,\n enableMentions,\n disableMentions,\n mentionSearchFn,\n mentionSearchParams,\n mentionResolveFn,\n suggestionMenuComponent,\n mentionNameResolver,\n onWarmMentions,\n aiConfig,\n stretch,\n aiEnabled = true,\n aiHandleRef,\n collaboration,\n disableUploads,\n editable,\n}: BlockNoteEditorProps): React.JSX.Element {\n const isEditable = resolveEditable({ editable, onChange });\n const t = useTranslations();\n const locale = useI18nLocale();\n const { resolvedTheme } = useTheme();\n // Optional on purpose: a host app may mount its own user context instead of\n // this package's, and the editor already degrades without a company — image\n // upload reports it (`uploadImage`) and the AI transport simply omits the\n // company header. Throwing here would take the whole page down instead.\n const company = useCurrentUserContextOptional<UserInterface>()?.company ?? null;\n\n const [acceptedChanges, setAcceptedChanges] = useState<Set<string>>(new Set());\n const [rejectedChanges, setRejectedChanges] = useState<Set<string>>(new Set());\n\n const editorRef = useRef<HTMLDivElement>(null);\n\n // Ensure side menu buttons don't trigger form submission\n useEffect(() => {\n if (!editorRef.current) return;\n const setButtonTypes = () => {\n editorRef.current?.querySelectorAll(\".bn-side-menu button\").forEach((btn) => {\n if (!btn.getAttribute(\"type\")) {\n btn.setAttribute(\"type\", \"button\");\n }\n });\n };\n const observer = new MutationObserver(setButtonTypes);\n observer.observe(editorRef.current, { childList: true, subtree: true });\n return () => observer.disconnect();\n }, []);\n\n const handleAcceptChange = useCallback((diffId: string) => {\n setAcceptedChanges((prev) => new Set([...prev, diffId]));\n setRejectedChanges((prev) => {\n const newSet = new Set(prev);\n newSet.delete(diffId);\n return newSet;\n });\n }, []);\n\n const handleRejectChange = useCallback((diffId: string) => {\n setRejectedChanges((prev) => new Set([...prev, diffId]));\n setAcceptedChanges((prev) => {\n const newSet = new Set(prev);\n newSet.delete(diffId);\n return newSet;\n });\n }, []);\n\n const DiffActionsInlineContent = useMemo(\n () =>\n createDiffActionsInlineContentSpec(handleAcceptChange, handleRejectChange, {\n accept: t(\"ui.editor.accept_change\"),\n reject: t(\"ui.editor.reject_change\"),\n }),\n [handleAcceptChange, handleRejectChange, t],\n );\n\n const mentionSpec = useMemo(\n () => createMentionInlineContentSpec(mentionResolveFn, disableMentions, mentionNameResolver),\n [disableMentions, mentionResolveFn, mentionNameResolver],\n );\n\n const schema = useMemo(\n () =>\n BlockNoteSchema.create({\n inlineContentSpecs: {\n ...defaultInlineContentSpecs,\n diffActions: DiffActionsInlineContent,\n mention: mentionSpec,\n ...inlineContentSpecs,\n },\n } as any),\n [DiffActionsInlineContent, mentionSpec, inlineContentSpecs],\n );\n\n const docRef = useRef<{ getDoc: () => any[] }>({ getDoc: () => [] });\n // Selection getter used by the AI transport to attach `selectionBlocks` to\n // the outgoing request metadata. Populated in a useEffect once the editor\n // instance exists; reads the current BlockNote selection on every send.\n const selectionRef = useRef<{ getSelectedBlocks: () => any[] }>({ getSelectedBlocks: () => [] });\n\n // Callers pass `aiConfig` as an inline object, the company arrives after the\n // first render and `aiEnabled` flips with credits, so none of them may key\n // the AI extension: every new extension means a new editor, which restarts\n // from `initialContent` and drops unsaved text. The transport and the outside\n // handle read them through this ref at send time.\n const aiRequestRef = useRef({ aiConfig, companyId: company?.id, aiEnabled });\n useEffect(() => {\n aiRequestRef.current = { aiConfig, companyId: company?.id, aiEnabled };\n });\n\n const hasAiConfig = !!aiConfig;\n const aiEndpoint = aiConfig?.endpoint;\n const aiExtension = useMemo(() => {\n if (!hasAiConfig || !aiEndpoint) return undefined;\n const base = getPublicApiUrl();\n const url = new URL(aiEndpoint, base.endsWith(\"/\") ? base : base + \"/\").toString();\n return AIExtension({\n transport: new DefaultChatTransport({\n api: url,\n credentials: \"include\",\n headers: async () => {\n const headers: Record<string, string> = { \"x-language\": locale };\n const token = await getClientToken();\n if (token) headers[\"Authorization\"] = `Bearer ${token}`;\n const companyId = aiRequestRef.current.companyId;\n if (companyId) headers[\"x-companyid\"] = companyId;\n return headers;\n },\n prepareSendMessagesRequest: ({ messages, body }: any) => {\n // Last guard before the network: AI switched off while a request was\n // being started never reaches the endpoint. Throwing here puts the\n // AI menu in its error state instead of sending.\n if (!aiRequestRef.current.aiEnabled) throw new Error(\"AI is disabled\");\n const latestAiConfig = aiRequestRef.current.aiConfig;\n let lastUserIdx = -1;\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i]?.role === \"user\") {\n lastUserIdx = i;\n break;\n }\n }\n const selectedBlocks = selectionRef.current.getSelectedBlocks();\n const augmented = messages.map((m: any, i: number) =>\n i === lastUserIdx\n ? {\n ...m,\n metadata: {\n ...(m.metadata ?? {}),\n entityType: latestAiConfig?.entityType,\n entityId: latestAiConfig?.entityId,\n blocks: docRef.current.getDoc(),\n selectionBlocks: selectedBlocks,\n },\n }\n : m,\n );\n return { body: { ...(body ?? {}), messages: augmented } };\n },\n }),\n });\n }, [hasAiConfig, aiEndpoint, locale]);\n\n const uploadImage = useCallback(\n async (file: File): Promise<string> => {\n if (!company && !uploadKeyPrefix) {\n errorToast({\n title: t(`common.errors.upload`),\n error: t(`common.errors.upload_description`),\n });\n throw new Error(t(`common.errors.upload`));\n }\n\n const fileType = file.type;\n const key = uploadKeyPrefix\n ? `${uploadKeyPrefix}/${id}/${file.name}`\n : `companies/${company!.id}/${type}/${id}/${file.name}`;\n\n const s3: S3Interface = await S3Service.getPreSignedUrl({\n key: key,\n contentType: fileType,\n isPublic: true,\n });\n\n await fetch(s3.url, {\n method: \"PUT\",\n headers: s3.headers,\n body: file,\n });\n\n const signedImage: S3Interface = await S3Service.getSignedUrl({\n key: key,\n isPublic: true,\n });\n\n return signedImage.url;\n },\n [company, id, t, type, uploadKeyPrefix],\n );\n\n // Utility: Remove trailing empty blocks for read-only display\n const removeTrailingEmptyBlocks = useCallback(\n (blocks: PartialBlock[]): PartialBlock[] => {\n if (!blocks || blocks.length === 0) return blocks;\n\n // Only remove trailing empty blocks in read-only mode\n if (onChange !== undefined) return blocks;\n\n return trimTrailingEmptyBlocks(blocks);\n },\n [onChange],\n );\n\n const processedContent = useMemo(() => {\n if (diffContent && initialContent) {\n try {\n const diffResult = BlockNoteDiffUtil.diff(initialContent, diffContent);\n const renderedDiff = BlockNoteWordDiffRendererUtil.renderWordDiffs(\n diffResult.blocks,\n handleAcceptChange,\n handleRejectChange,\n acceptedChanges,\n rejectedChanges,\n );\n return removeTrailingEmptyBlocks(renderedDiff);\n } catch (_error) {\n return initialContent && Array.isArray(initialContent) && initialContent.length > 0\n ? removeTrailingEmptyBlocks(initialContent)\n : [];\n }\n }\n\n if (!initialContent) {\n return [];\n }\n\n if (!Array.isArray(initialContent)) {\n return [];\n }\n\n return initialContent.length > 0 ? removeTrailingEmptyBlocks(initialContent) : [];\n }, [\n initialContent,\n diffContent,\n handleAcceptChange,\n handleRejectChange,\n acceptedChanges,\n rejectedChanges,\n removeTrailingEmptyBlocks,\n ]);\n\n const validatedInitialContent = useMemo(() => {\n if (processedContent && Array.isArray(processedContent) && processedContent.length > 0) {\n const validatedContent = processedContent.filter((block) => {\n if (!block || typeof block !== \"object\") return false;\n if (!(block as any).type) return false;\n return true;\n });\n return validatedContent.length > 0 ? (validatedContent as PartialBlock[]) : undefined;\n }\n return undefined;\n }, [processedContent]);\n\n // BlockNote's own UI text (slash menu, toolbar, AI menu) in the active\n // language; English when BlockNote has no dictionary for it.\n const language = locale.split(\"-\")[0];\n const coreDictionary = (coreLocales as Record<string, typeof coreLocales.en>)[language] ?? coreLocales.en;\n const aiDictionary = (aiLocales as Record<string, typeof aiLocales.en>)[language] ?? aiLocales.en;\n\n const editor = useCreateBlockNote(\n useMemo(\n () =>\n buildBlockNoteEditorOptions({\n placeholder: placeholder || t(`common.blocknote.placeholder`),\n schema,\n initialContent: validatedInitialContent,\n uploadFile: uploadImage,\n disableUploads,\n aiExtension,\n coreDictionary,\n aiDictionary,\n collaboration,\n }),\n [\n placeholder,\n t,\n schema,\n validatedInitialContent,\n uploadImage,\n disableUploads,\n aiExtension,\n coreDictionary,\n aiDictionary,\n collaboration,\n ],\n ),\n // useCreateBlockNote memoises on THIS list, not on the options' identity\n // (@blocknote/react: useMemo(() => BlockNoteEditor.create(options), deps),\n // deps defaulting to []). Without it the editor keeps the extensions of its\n // first render: AI config arriving later (user loaded after mount)\n // rendered the AI UI over an editor with no AIExtension, and BlockNote's\n // useExtension threw \"Extension not found\". The other options keep their\n // first-render values, as before. `aiEnabled` is deliberately not here.\n // A new Yjs fragment (another document) needs a new editor bound to it.\n [aiExtension, collaboration?.fragment],\n );\n\n // Every AI surface keys off the editor actually rendered, never off the\n // props: those can disagree with the options that editor was created with.\n // `aiEnabled` then hides that UI without touching the editor.\n const hasAiExtension = !!editor.getExtension(AIExtension);\n const aiActive = hasAiExtension && aiEnabled;\n\n // AI switched off while its menu is open or a run is streaming: hiding the\n // AIMenuController alone would leave the editor read-only (openAIMenuAtBlock\n // sets isEditable = false) and the AI suggestions in the document. Stop the\n // request, then reject the suggestions, or just close an idle prompt menu.\n useEffect(() => {\n if (aiEnabled || !hasAiExtension) return;\n const ai = editor.getExtension(AIExtension);\n if (!ai) return;\n const dismiss = async () => {\n const menu = ai.store.state.aiMenuState;\n if (menu === \"closed\") return;\n if (menu.status === \"thinking\" || menu.status === \"ai-writing\") await ai.abort(\"AI disabled\");\n const after = ai.store.state.aiMenuState;\n if (after === \"closed\") return;\n if (after.status === \"user-input\") ai.closeAIMenu();\n else ai.rejectChanges();\n };\n dismiss().catch((error) => console.error(\"Closing the AI menu failed:\", error));\n }, [aiEnabled, hasAiExtension, editor]);\n\n // Publish the outside-the-editor AI trigger. `editor.getExtension(AIExtension)`\n // is BlockNote 0.54's documented lookup by extension factory (core's\n // `getExtension` resolves a function argument through `extensionFactories`),\n // so the instance is reachable without the `useExtension` hook that only\n // works inside the BlockNote context (NarrAIMenu). The menu MUST be opened\n // first: `invokeAI` routes every status update through `setAIResponseStatus`,\n // which is a no-op while `aiMenuState === \"closed\"` — without the open menu\n // the request runs but the accept / reject UI never appears.\n useEffect(() => {\n if (!aiHandleRef) return;\n if (!aiActive) {\n aiHandleRef.current = null;\n return;\n }\n aiHandleRef.current = {\n invokeAi: (type: BlockNoteAiGenerateAction) => {\n // A caller may hold the handle across the render that turns AI off.\n if (!aiRequestRef.current.aiEnabled) return;\n const ai = editor.getExtension(AIExtension);\n if (!ai) return;\n editor.focus();\n const blocks = editor.document;\n const anchor = blocks?.[blocks.length - 1];\n if (anchor?.id) ai.openAIMenuAtBlock(anchor.id);\n void ai.invokeAI({\n userPrompt: type,\n useSelection: false,\n chatRequestOptions: { body: { type } },\n });\n },\n };\n return () => {\n aiHandleRef.current = null;\n };\n }, [aiHandleRef, aiActive, editor]);\n\n // Tracks the hash of the document the editor itself just emitted via onChange.\n // The sync effect below uses it to skip replaceBlocks when the parent's\n // initialContent is just an echo of our own emission (form-controlled flow).\n const lastEmittedHashRef = useRef<string | null>(null);\n\n // Whether the parent's copy of the text is empty: the content it handed in, then each change\n // reported to it. A change from empty to still empty is not reported: BlockNote emits one when an\n // empty editor mounts (its trailing empty paragraph), and reported it became a save of nothing on\n // every view of a page with an empty field.\n const processedContentRef = useRef<any[]>([]);\n const parentKnowsEmptyRef = useRef<boolean | null>(null);\n\n // The document the editor holds right after loading the parent's text, until the first change\n // that differs from it. Loading text BlockNote stores in a fuller shape (block ids, default props,\n // children: text written by the server, an import, the API) emits a change of the same text.\n // Reported, it became a save on every view of such a page, and offline a queued change.\n const loadedHashRef = useRef<string | null>(null);\n // True while replaceBlocks loads the parent's text: BlockNote fires onChange synchronously\n // inside it, before loadedHashRef can be set.\n const loadingFromParentRef = useRef(false);\n\n const handleChange = useCallback(async () => {\n if (!onChange) return;\n const newBlocks = editor.document;\n const newHash = JSON.stringify(newBlocks);\n if (loadingFromParentRef.current) {\n lastEmittedHashRef.current = newHash;\n return;\n }\n if (loadedHashRef.current !== null) {\n if (newHash === loadedHashRef.current) {\n lastEmittedHashRef.current = newHash;\n return;\n }\n loadedHashRef.current = null;\n }\n lastEmittedHashRef.current = newHash;\n const isEmpty = isDocumentEmpty(newBlocks);\n const wasEmpty = parentKnowsEmptyRef.current ?? isDocumentEmpty(processedContentRef.current);\n if (isEmpty && wasEmpty) return;\n parentKnowsEmptyRef.current = isEmpty;\n\n function hasUnresolvedDiffsRecursive(block: any): boolean {\n if (!block || typeof block !== \"object\") return false;\n let diffId = undefined;\n if (block.props && block.props.diffId) diffId = block.props.diffId;\n if (!diffId && block.attrs && block.attrs.diffId) diffId = block.attrs.diffId;\n if (diffId && !acceptedChanges.has(diffId) && !rejectedChanges.has(diffId)) {\n return true;\n }\n\n if (block.content) {\n const contentArr = Array.isArray(block.content) ? block.content : [block.content];\n for (const inline of contentArr) {\n if (inline && typeof inline === \"object\") {\n if (inline.type === \"diffActions\" && inline.props && inline.props.diffIds) {\n const ids =\n typeof inline.props.diffIds === \"string\" ? inline.props.diffIds.split(\",\") : inline.props.diffIds;\n for (const id of ids) {\n const trimmed = (id || \"\").toString().trim();\n if (trimmed && !acceptedChanges.has(trimmed) && !rejectedChanges.has(trimmed)) {\n return true;\n }\n }\n }\n if (inline.props && inline.props.diffId) {\n const diffIdInline = inline.props.diffId;\n if (diffIdInline && !acceptedChanges.has(diffIdInline) && !rejectedChanges.has(diffIdInline)) {\n return true;\n }\n }\n if (inline.children && Array.isArray(inline.children)) {\n for (const child of inline.children) {\n if (hasUnresolvedDiffsRecursive(child)) return true;\n }\n }\n }\n }\n }\n if (Array.isArray(block.children)) {\n for (const child of block.children) {\n if (hasUnresolvedDiffsRecursive(child)) return true;\n }\n }\n return false;\n }\n\n let hasUnresolvedDiff = false;\n if (Array.isArray(newBlocks)) {\n hasUnresolvedDiff = newBlocks.some((block: any) => hasUnresolvedDiffsRecursive(block));\n }\n\n onChange(newBlocks, isEmpty, hasUnresolvedDiff);\n }, [editor, onChange, id, acceptedChanges, rejectedChanges]);\n\n processedContentRef.current = processedContent as any[];\n // A diff render (the suggested changes, or the text after an accept or a reject) is not the\n // parent's text: the parent learns it, and whether changes are unresolved, from the change\n // BlockNote emits when it loads it.\n const rendersDiffRef = useRef(false);\n rendersDiffRef.current = !!(diffContent && initialContent);\n\n // Utility: deep equality for arrays of blocks\n const areBlocksEqual = (a: any[], b: any[]): boolean => {\n return JSON.stringify(a) === JSON.stringify(b);\n };\n\n // Only initialize from markdownContent once per value, and only if different\n const hasInitializedFromMarkdown = useRef<string | null>(null);\n useEffect(() => {\n const updateContent = async (markdown: string) => {\n const blocks = await editor.tryParseMarkdownToBlocks(markdown);\n if (!areBlocksEqual(blocks, editor.document)) {\n editor.replaceBlocks(editor.document, blocks);\n }\n };\n\n if (markdownContent && hasInitializedFromMarkdown.current !== markdownContent) {\n hasInitializedFromMarkdown.current = markdownContent;\n updateContent(markdownContent).then(() => handleChange());\n }\n }, [markdownContent, editor]);\n\n // Update editor content when diff content changes, but only if different\n // Prevent unnecessary replaceBlocks calls that reset scroll/cursor.\n const previousContentHashRef = useRef<string | null>(null);\n useEffect(() => {\n if (!processedContent || !editor) return;\n // A collaborative editor's content IS the shared Yjs document: it has no initialContent,\n // so processedContent is [] and replaceBlocks would wipe the document it just loaded,\n // and that wipe would be synced to every other writer and stored.\n if (collaboration) return;\n const hash = JSON.stringify(processedContent);\n if (previousContentHashRef.current === hash) return; // no changes\n // New content from the parent: that is now the text it knows.\n parentKnowsEmptyRef.current = isDocumentEmpty(processedContent as any[]);\n // Skip replaceBlocks when the new initialContent is just an echo of what\n // the editor itself emitted. Without this, a form-controlled parent\n // (FormBlockNote) round-trips field.value back as initialContent on every\n // keystroke and triggers replaceBlocks, which resets the cursor and can\n // strip just-inserted inline content like mentions.\n if (lastEmittedHashRef.current === hash) {\n previousContentHashRef.current = hash;\n return;\n }\n const currentHash = JSON.stringify(editor.document);\n if (currentHash === hash) {\n previousContentHashRef.current = hash;\n return; // already in sync\n }\n if (rendersDiffRef.current) {\n loadedHashRef.current = null;\n editor.replaceBlocks(editor.document, processedContent as PartialBlock[]);\n previousContentHashRef.current = hash;\n return;\n }\n loadingFromParentRef.current = true;\n try {\n editor.replaceBlocks(editor.document, processedContent as PartialBlock[]);\n } finally {\n loadingFromParentRef.current = false;\n }\n // The parent's text, as BlockNote now holds it: a change of the same text emitted after the\n // load is not an edit either.\n loadedHashRef.current = JSON.stringify(editor.document);\n previousContentHashRef.current = hash;\n }, [processedContent, editor, collaboration]);\n\n useEffect(() => {\n if (!onWarmMentions || !initialContent || !Array.isArray(initialContent) || initialContent.length === 0) return;\n onWarmMentions(initialContent);\n }, [onWarmMentions, initialContent]);\n\n useEffect(() => {\n docRef.current.getDoc = () => editor?.document ?? [];\n selectionRef.current.getSelectedBlocks = () => {\n const sel = editor?.getSelection?.();\n const blocks = (sel as any)?.blocks;\n return Array.isArray(blocks) ? blocks : [];\n };\n }, [editor]);\n\n // Handle audio received from whisper transcription\n const _handleAudioReceived = useCallback(\n (message: string) => {\n try {\n // Ensure the editor has focus\n const editorElement = editorRef.current?.querySelector('[contenteditable=\"true\"]') as HTMLElement;\n if (editorElement && document.activeElement !== editorElement) {\n editorElement.focus();\n }\n\n // Insert the transcribed text at the current cursor position\n editor.insertInlineContent(message);\n } catch (error) {\n console.error(\"Error inserting transcribed text:\", error);\n // Fallback: try to insert at the end of the document\n try {\n const blocks = editor.document;\n if (blocks.length > 0) {\n const lastBlock = blocks[blocks.length - 1];\n editor.setTextCursorPosition(lastBlock.id, \"end\");\n editor.insertInlineContent(message);\n }\n } catch (fallbackError) {\n console.error(\"Fallback insertion also failed:\", fallbackError);\n }\n }\n },\n [editor],\n );\n\n return (\n <div\n ref={editorRef}\n className={cn(\n bordered ? \"rounded-md border border-input bg-input/20 dark:bg-input/30\" : \"\",\n \"flex flex-col w-full\",\n // Pin BlockNote's font-size so it doesn't jump from 14→16px when the\n // xl-ai AIMenu mounts. The shadcn theme sets `.bn-default-styles {\n // font-size: 16px }` explicitly; outside AI mode the form's text-sm\n // wins via cascade, but ForkYDocExtension re-evaluates the style\n // context on AI activation and the explicit 16px takes over.\n // Phone: an editable field types at 16px, or iPhone Safari zooms the\n // page in on focus. The two ranges never overlap, so neither depends on\n // CSS source order to win.\n isEditable\n ? \"md:[&_.bn-default-styles]:!text-sm max-md:[&_.bn-default-styles]:!text-base\"\n : \"[&_.bn-default-styles]:!text-sm\",\n className,\n )}\n >\n <BlockNoteView\n editor={editor}\n onChange={handleChange}\n editable={isEditable}\n formattingToolbar={false}\n slashMenu={!aiActive}\n // Follow the app theme: hardcoding \"light\" leaves dark (light-theme)\n // text on the dark card, which is nearly unreadable in dark mode.\n theme={resolvedTheme === \"dark\" ? \"dark\" : \"light\"}\n // `className` is applied by BlockNote to both the main `.bn-container`\n // AND `editor.portalElement` (the floating-UI portal root). Gate `p-4`\n // on `.bn-container` so it doesn't add padding to the empty portal\n // element and produce a phantom scrollbar on the wrapper.\n className={cn(\n \"BlockNoteView flex-1\",\n isEditable && \"[&.bn-container]:p-4\",\n // In stretch mode the parent chain caps our height via flex; without\n // these two classes the `.bn-container` keeps `min-height: auto`\n // (its content's intrinsic height) and pushes the bordered wrapper\n // — and the surrounding EditorSheet form — to scroll instead of\n // scrolling internally.\n isEditable && stretch && \"[&.bn-container]:min-h-0 [&.bn-container]:overflow-y-auto\",\n // Phone — these reach the floating menus because BlockNote puts this\n // className on its portal root too. The formatting toolbar (~450px)\n // scrolls sideways instead of losing alignment and link off-screen;\n // the slash menu is capped to the screen and drops its keyboard\n // shortcut badges, which mean nothing on a touch screen.\n \"max-md:[&_.bn-formatting-toolbar]:max-w-[calc(100vw-1rem)] max-md:[&_.bn-formatting-toolbar]:overflow-x-auto max-md:[&_.bn-formatting-toolbar>*]:shrink-0\",\n \"max-md:[&_.bn-suggestion-menu]:max-w-[calc(100vw-1rem)] max-md:[&_.bn-suggestion-menu_[role=option]>[data-position=right]]:hidden\",\n size === \"sm\" && \"small\",\n )}\n >\n <BlockNoteEditorFormattingToolbar showAI={aiActive} />\n {enableMentions && mentionSearchFn && (\n <BlockNoteEditorMentionSuggestionMenu\n editor={editor}\n mentionSearchFn={mentionSearchFn}\n mentionSearchParams={mentionSearchParams}\n suggestionMenuComponent={suggestionMenuComponent}\n />\n )}\n {renderOverlays?.(editor)}\n {enableMentions && mentionResolveFn && (\n <BlockNoteEditorMentionHoverCard containerRef={editorRef} mentionResolveFn={mentionResolveFn} />\n )}\n {aiActive && (\n <SuggestionMenuController\n triggerCharacter=\"/\"\n getItems={async (query: string) =>\n filterSuggestionItems([...getDefaultReactSlashMenuItems(editor), ...getAISlashMenuItems(editor)], query)\n }\n />\n )}\n {aiActive && <AIMenuController aiMenu={() => <NarrAIMenu actions={aiConfig?.actions} />} />}\n </BlockNoteView>\n </div>\n );\n}\n","import { LayoutTemplateIcon, SparklesIcon } from \"lucide-react\";\nimport React from \"react\";\n\n/**\n * Whole-document AI actions an editor can offer in its AI menu when nothing\n * is selected. Each maps to a backend `type` discriminator; NO prompt text\n * lives here. Selection-edit actions (Improve, Fix spelling, …) are separate\n * and always available.\n */\nexport type BlockNoteAiGenerateAction = \"fill-template\" | \"draft-impression\";\n\nexport const DEFAULT_AI_GENERATE_ACTIONS: BlockNoteAiGenerateAction[] = [\"fill-template\"];\n\nexport type AiGenerateMenuItem = {\n key: string;\n title: string;\n aliases: string[];\n /** BlockNote's DefaultReactSuggestionItem types icon as an element, not ReactNode. */\n icon: React.JSX.Element;\n size: \"small\";\n onItemClick: () => void;\n};\n\n/** `titleKey` is a message key; the caller's translator resolves it to the shown title. */\ntype AiGenerateItemDefinition = Omit<AiGenerateMenuItem, \"onItemClick\" | \"title\"> & { titleKey: string };\n\nconst ITEMS: Record<BlockNoteAiGenerateAction, AiGenerateItemDefinition> = {\n \"fill-template\": {\n key: \"generate_from_template\",\n titleKey: \"ui.editor.ai.generate_from_template\",\n aliases: [\"generate\", \"template\", \"fill\"],\n icon: <LayoutTemplateIcon size={18} />,\n size: \"small\",\n },\n \"draft-impression\": {\n key: \"suggest_impression\",\n titleKey: \"ui.editor.ai.suggest_impression\",\n aliases: [\"suggest\", \"impression\"],\n icon: <SparklesIcon size={18} />,\n size: \"small\",\n },\n};\n\nexport function generateActionItems(\n actions: BlockNoteAiGenerateAction[] | undefined,\n invoke: (type: BlockNoteAiGenerateAction) => void,\n translate: (key: string) => string,\n): AiGenerateMenuItem[] {\n return (actions ?? DEFAULT_AI_GENERATE_ACTIONS).map((type) => {\n const { titleKey, ...item } = ITEMS[type];\n return { ...item, title: translate(titleKey), onItemClick: () => invoke(type) };\n });\n}\n","\"use client\";\n\nimport {\n BasicTextStyleButton,\n BlockTypeSelect,\n CreateLinkButton,\n FileCaptionButton,\n FileReplaceButton,\n FormattingToolbar,\n FormattingToolbarController,\n TextAlignButton,\n} from \"@blocknote/react\";\nimport { AIToolbarButton } from \"@blocknote/xl-ai\";\n\nexport function BlockNoteEditorFormattingToolbar({ showAI = false }: { showAI?: boolean }) {\n return (\n <FormattingToolbarController\n formattingToolbar={() => (\n <FormattingToolbar>\n <BlockTypeSelect key={\"blockTypeSelect\"} />\n\n <FileCaptionButton key={\"fileCaptionButton\"} />\n <FileReplaceButton key={\"replaceFileButton\"} />\n\n <BasicTextStyleButton basicTextStyle={\"bold\"} key={\"boldStyleButton\"} />\n <BasicTextStyleButton basicTextStyle={\"italic\"} key={\"italicStyleButton\"} />\n <BasicTextStyleButton basicTextStyle={\"underline\"} key={\"underlineStyleButton\"} />\n <BasicTextStyleButton basicTextStyle={\"strike\"} key={\"strikeStyleButton\"} />\n\n <TextAlignButton textAlignment={\"left\"} key={\"textAlignLeftButton\"} />\n <TextAlignButton textAlignment={\"center\"} key={\"textAlignCenterButton\"} />\n <TextAlignButton textAlignment={\"right\"} key={\"textAlignRightButton\"} />\n\n <CreateLinkButton key={\"createLinkButton\"} />\n\n {showAI ? <AIToolbarButton key={\"aiToolbarButton\"} /> : null}\n </FormattingToolbar>\n )}\n />\n );\n}\n"]}