@toantranmei/editor 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["Fragment","normalize","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","_hoisted_9","_openBlock","_createElementBlock","_mergeProps","_unref","_Fragment","_renderList","_createElementVNode","_toDisplayString","_normalizeClass","_withModifiers","_createBlock","_resolveDynamicComponent","_createCommentVNode","_sfc_main","MAX","normalize","SlashMenu","node","updateAttributes","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","_openBlock","_createBlock","_unref","_withCtx","_createElementVNode","_normalizeStyle","_toDisplayString","_createElementBlock","_Fragment","_renderList","_normalizeClass","_createCommentVNode","_createVNode","_sfc_main","CalloutView","_hoisted_1","_hoisted_2","_hoisted_3","_openBlock","_createElementBlock","_createCommentVNode","_toDisplayString","_sfc_main","node","updateAttributes","editor","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_openBlock","_createBlock","_unref","_withCtx","_createElementVNode","_createElementBlock","_Fragment","_renderList","_toDisplayString","_createVNode","_resolveDynamicComponent","_createTextVNode","_normalizeClass","MermaidDiagram","_createCommentVNode","_sfc_main","ALIASES","CodeBlockView","selected","node","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_openBlock","_createBlock","_unref","_normalizeClass","_withCtx","_createElementBlock","_withModifiers","_createElementVNode","_toDisplayString","_withDirectives","_vModelText","_createCommentVNode","_sfc_main","EmbedView","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","MIN","_openBlock","_createElementBlock","_createElementVNode","_normalizeStyle","_Fragment","_renderList","_toDisplayString","_sfc_main","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_openBlock","_createBlock","_Teleport","_createElementVNode","_mergeProps","_withModifiers","_normalizeClass","_normalizeStyle","_createVNode","_unref","_toDisplayString","_sfc_main","node","selected","updateAttributes","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","_hoisted_9","_hoisted_10","_hoisted_11","_hoisted_12","_hoisted_13","_hoisted_14","_hoisted_15","_hoisted_16","_hoisted_17","_hoisted_18","_hoisted_19","_hoisted_20","_hoisted_21","_hoisted_22","_hoisted_23","_hoisted_24","_hoisted_25","_hoisted_26","_hoisted_27","_hoisted_28","_hoisted_29","_hoisted_30","_openBlock","_createBlock","_unref","_normalizeClass","_withCtx","_createElementBlock","_withModifiers","_createElementVNode","_Fragment","_renderList","_resolveDynamicComponent","LinkIcon","_createTextVNode","_toDisplayString","_createVNode","ImageIcon","_withDirectives","_vModelText","_createCommentVNode","_normalizeStyle","ImageCropper","ImageLightbox","_sfc_main","Image","ImageView","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_openBlock","_createElementBlock","_mergeProps","_unref","_createElementVNode","_Fragment","_renderList","_normalizeClass","_withModifiers","_toDisplayString","_sfc_main","EmojiMenu","node","selected","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","_hoisted_9","_hoisted_10","_hoisted_11","_hoisted_12","_hoisted_13","_hoisted_14","FileIcon","_openBlock","_createBlock","_unref","_normalizeClass","_withCtx","_createElementBlock","_withModifiers","_createElementVNode","_Fragment","_renderList","_resolveDynamicComponent","LinkIcon","_createTextVNode","_toDisplayString","_withDirectives","_vModelText","_createCommentVNode","_createVNode","_sfc_main","FileView","selected","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","_hoisted_9","_hoisted_10","_hoisted_11","_hoisted_12","_hoisted_13","_hoisted_14","_hoisted_15","_hoisted_16","_hoisted_17","_hoisted_18","_hoisted_19","_hoisted_20","_openBlock","_createBlock","_unref","_normalizeClass","_withCtx","_createElementVNode","_createVNode","_toDisplayString","_createElementBlock","_createTextVNode","_createCommentVNode","_normalizeStyle","_withDirectives","_vModelText","_Teleport","_mergeProps","_withModifiers","_sfc_main","HtmlView","selected","node","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_openBlock","_createBlock","_unref","_normalizeClass","_withCtx","_createElementBlock","_toDisplayString","_createCommentVNode","_withDirectives","_createElementVNode","_vModelText","_sfc_main","MathView","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","_openBlock","_createElementBlock","_mergeProps","_unref","_Fragment","_renderList","_createElementVNode","_toDisplayString","_normalizeClass","_withModifiers","_createBlock","_resolveDynamicComponent","_createCommentVNode","_sfc_main","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","_hoisted_9","_hoisted_10","_hoisted_11","_hoisted_12","_hoisted_13","_hoisted_14","_hoisted_15","_hoisted_16","_hoisted_17","_hoisted_18","_hoisted_19","_hoisted_20","_hoisted_21","_openBlock","_createElementBlock","_createElementVNode","_normalizeClass","_withDirectives","_withKeys","_withModifiers","_vModelText","_createCommentVNode","_toDisplayString","_createVNode","_unref","_Fragment","_renderList","_createBlock","_sfc_main","selected","node","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","_hoisted_9","_hoisted_10","_hoisted_11","_hoisted_12","_hoisted_13","_hoisted_14","_openBlock","_createBlock","_unref","_withCtx","_createElementVNode","_normalizeClass","_createElementBlock","_createCommentVNode","_toDisplayString","_Teleport","_mergeProps","_withModifiers","DatePicker","_Fragment","_withDirectives","_vModelText","_renderList","_resolveDynamicComponent","_createVNode","_sfc_main","MentionView","MentionMenu","selected","_hoisted_1","_hoisted_2","_openBlock","_createBlock","_unref","_normalizeClass","_withCtx","_createElementBlock","_Fragment","_renderList","_toDisplayString","_createCommentVNode","_sfc_main","TocView","TocNode","TableOfContents","$emit","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_openBlock","_createElementBlock","_Fragment","_renderList","_toDisplayString","_createCommentVNode","_createElementVNode","_normalizeClass","_createBlock","_unref","_sfc_main","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","_hoisted_9","_hoisted_10","_hoisted_11","_hoisted_12","_hoisted_13","_hoisted_14","_hoisted_15","_openBlock","_createBlock","_Teleport","_createElementVNode","_mergeProps","_unref","_createVNode","_withDirectives","_vModelText","_createElementBlock","_toDisplayString","_createCommentVNode","_normalizeClass","_Fragment","_renderList","_withModifiers","_resolveDynamicComponent","ColorList","_sfc_main","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","_hoisted_9","_hoisted_10","_hoisted_11","_hoisted_12","_hoisted_13","_openBlock","_createBlock","_unref","_withCtx","_createElementVNode","_mergeProps","_createElementBlock","_Fragment","_renderList","_resolveDynamicComponent","_createTextVNode","_toDisplayString","_createVNode","_createCommentVNode","_normalizeClass","_withModifiers","_withDirectives","_withKeys","_vModelText","ColorList","_sfc_main","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_openBlock","_createBlock","_Teleport","_createElementBlock","_mergeProps","_unref","_createElementVNode","_normalizeClass","_Fragment","_renderList","_toDisplayString","_createCommentVNode","_sfc_main","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_openBlock","_createElementBlock","_Fragment","_createElementVNode","_normalizeStyle","_withModifiers","_createVNode","_unref","_createCommentVNode","_mergeProps","_renderList","_normalizeClass","_createBlock","_resolveDynamicComponent","_toDisplayString","_createTextVNode","_sfc_main","_openBlock","_createElementBlock","_mergeProps","_createVNode","_unref","_withCtx","_createElementVNode","_toDisplayString","_createCommentVNode","FormatMenu","_createBlock","TableControls","MeiOutline","BlockMenu","_Teleport","_Fragment","_renderList","_createTextVNode","_sfc_main","MeiEditor","en","formatDateValue","vi","parseDateInput","reminderTime","HTML_MAX_HEIGHT","LANGUAGE_ALIASES","toEmbedUrl","formatDate","htmlBlockDocument","REMINDERS_DATE","formatTime","REMINDERS_TIME","isoDate","DATE_FORMATS","parseTimeInput","zh","resolveMessages","PALETTE_NAMES","semanticDark","overridesCss","semanticLight","injectStyle","component","installBaseTokens","primitive","baseTokensCss","cssVar","BLOCK_NAMES","TableOfContents$1","StarterKit","Fragment$1","Suggestion","CodeBlockLowlight","Heading","Blockquote","HorizontalRule","Image$1","Mention","MeiConfig","Extension","shallowReactive","\"class\"","defineBlock","build","spec","options","overrides","collectExtensions","seen","blocks","b","ext","CONTAINERS","blockAt","d","$pos","node","after","rangeOfBlock","block","rangeBetween","ba","doc","a","bb","top","$p","pos","ta","tb","isBlockSelection","state","NodeRangeSelection","currentRange","sel","blocksIn","out","range","setBlockSelection","tr","selectBlocks","editor","dissolveEmptyColumn","columnDepth","column","columns","columnsPos","rest","c","replacement","reselect","wasBlocks","next","TextSelection","caret","oldFrom","deleteBlocks","duplicateBlocks","slice","moveBlocks","$from","parent","startIndex","endIndex","insertAt","dir","selectText","from","to","turnBlocksInto","chain","summary","content","paragraph","fragment","colorBlocks","attr","kind","mark","value","color","end","rangeColors","found","any","add","fromBlocks","marks","m","single","s","SIDE_ZONE","LEFT_ZONE","LEFT_INTENT","NEST_INDENT","SCROLL_ZONE","SCROLL_SPEED","NESTABLE","blockDropKey","PluginKey","BlockDrop","storage","indicator","hide","show","scope","indicatorClass","line","rectOf","dom","view","draggingColumns","n","dragStartX","findDropTarget","container","containerPos","start","containers","r","x","y","hit","last","offset","rect","child","isSelf","selection","rightZone","leftIntent","side","vertical","edgeX","colRect","maxColumns","before","isNearEditor","e","moveBlock","target","schema","dragged","existing","moved","NodeSelection","scrollFrame","scrollSpeed","scroller","el","overflowY","stopScroll","updateScroll","bounds","fromTop","fromBottom","step","Plugin","onDragOver","onDrop","onDragEnd","BULK_THRESHOLD","uuid","assignIds","typeSet","types","visit","id","generate","rebuild","children","ids","attrs","BlockId","name","transactions","transform","combineTransactionSteps","oldState","candidates","getChangedRanges","newRange","needsCheck","counts","newState","inCandidates","updates","kept","usedElsewhere","repeated","anchor","Selection","enabledBlocks","isNode","turnIntoBlocks","blockTitle","messages","groupLabel","group","normalize$2","filterBlocks","q","query","score","terms","t","w","TURN_INTO_SHORTCUTS","blockSelectionKey","BlockSelection","suggestionOpen","st","p","withRange","fn","shortcuts","\"Escape\"","key","dragging","DecorationSet","Decoration","event","up","head","$edge","sibling","siblingPos","onMouseUp","safeUrl","src","url","scheme","data","isSameOrigin","base","isWebUrl","MAX_DEPTH","isSpace","isDigit","indentOf","indent","at","headingText","hashes","listItem","i","ordered","digits","task","text","classify","info","space","level","only","item","splitLines","closesFence","open","looksLikeMarkdown","openFence","previousList","raw","OPEN_AFTER","CLOSE_BEFORE","ESCAPABLE","isWs","isWord","EMPHASIS","finder","cached","needle","valid","urlEnd","parseInline","buf","flush","closer","len","inLink","close","paren","inside","title","href","depth","delimiter","type","inner","j","buildList","root","stack","items","list","unquote","all","markdownToBlocks","lines","markdown","kinds","body","quoted","flatten","l","following","k","fitToSchema","map","textOf","parts","MarkdownPaste","input","error","placeholderPluginKey","Placeholder","$anchor","isDefault","TextColor","Mark","mergeAttributes","HTMLAttributes","commands","BgColor","COLORABLE_BLOCKS","BlockColor","useScope","computed","usePointerMoved","_hoisted_1$21","_hoisted_2$21","_hoisted_3$20","_hoisted_4$19","_hoisted_5$15","_hoisted_6$12","_hoisted_7$11","_hoisted_8$10","_hoisted_9$8","SlashMenu_default","defineComponent","__expose","props","__props","selected","ref","listEl","groups","watch","nextTick","select","index","onKeyDown","pointerMoved","openBlock","createElementBlock","mergeProps","unref","Fragment","renderList","entries","createElementVNode","toDisplayString","normalizeClass","$event","withModifiers","createBlock","resolveDynamicComponent","createCommentVNode","KEY","MAX$1","load","recent","save","pushRecentColor","entry","pushRecentBlock","normalize$1","blockItem","ed","listItemRange","colorItems","slashItems","recentItems","rank","readTokenPx","fallback","probe","path","px","suggestionRenderer","renderer","cleanup","position","reference","gap","autoUpdate","flip","shift","hooks","VueRenderer","exitSuggestion","pluginKey","slashPluginKey","SlashCommand","lastMatch","placeholder","Node","inline","UnknownBlock","UnknownInline","createExtensions","config","undoRedo","handleAnchorRect","box","lineHeight","lineHeightOf","center","bar","firstTextRect","padTop","inUi","ui","findTextRect","walker","accept","style","lh","isMac","MAC","PC","kbd","shortcut","isMod","GLOBAL_TOKENS_KEY","GLOBAL_BLOCKS_KEY","blockNodeView","render","VueNodeViewRenderer","stop","original","fast","useEditable","editable","sync","onBeforeUnmount","readonly","useClickOutside","listener","active","handler","onMounted","_hoisted_1$20","_hoisted_2$20","_hoisted_3$19","_hoisted_4$18","_hoisted_5$14","_hoisted_6$11","_hoisted_7$10","_hoisted_8$9","CalloutView_default","nodeViewProps","ICONS","pickerEl","iconEl","iconOffset","alignIcon","first","observer","NodeViewWrapper","_ctx","withCtx","normalizeStyle","_cache","icon","createVNode","NodeViewContent","Callout","katexPromise","loadKatex","mermaidPromise","loadMermaid","_hoisted_1$19","_hoisted_2$19","_hoisted_3$18","counter","nextId","MermaidDiagram_default","svg","timer","latest","mermaid","result","leftover","label","_hoisted_1$18","_hoisted_2$18","_hoisted_3$17","_hoisted_4$17","CodeBlockView_default","hasMermaid","languages","CODE_LANGUAGES","current","copied","showDiagram","isDark","copy","lang","ChevronDown","Check","Copy","createTextVNode","lowlight","createLowlight","LOADERS","pending","loadLanguage","language","mod","refresh","indentCode","$to","empty","direction","lead","CodeBlock","\"Tab\"","requested","check","added","v","prev","Column","Columns","count","colorAttr","ColoredCell","TableCell","ColoredHeader","TableHeader","tableExtensions","TableKit","ToggleDetails","Details","upstreamUpdate","openPending","ok","toggleExtensions","DetailsSummary","DetailsContent","codeBlock","Code","callout","Lightbulb","toggle","ListCollapse","setToggleLevel","TOGGLE_HEADING_ICONS","Heading1","Heading2","Heading3","toggleHeading","table","Table","COLUMN_ICONS","Columns2","Columns3","Columns4","Type","wrapper","HEADING_ICONS","Heading4","heading","o","bulletList","BulletList","ListItem","ListKeymap","List","orderedList","OrderedList","ListOrdered","taskList","TaskList","TaskItem","ListTodo","quote","Quote","divider","Minus","_hoisted_1$17","_hoisted_2$17","_hoisted_3$16","_hoisted_4$16","_hoisted_5$13","_hoisted_6$10","_hoisted_7$9","EmbedView_default","link","resizing","safeSrc","submit","startResize","startY","startH","move","ev","withDirectives","vModelText","Embed","_hoisted_1$16","_hoisted_2$16","_hoisted_3$15","_hoisted_4$15","_hoisted_5$12","MIN$1","ImageCropper_default","__emit","emit","stage","img","HANDLES","clamp","hi","lo","sx","sy","dx","dy","handle","done","full","h","natural","ratio","reset","onKey","pct","_hoisted_1$15","_hoisted_2$15","_hoisted_3$14","_hoisted_4$14","_hoisted_5$11","_hoisted_6$9","MIN","MAX","ImageLightbox_default","zoom","pan","percent","setZoom","zoomIn","zoomOut","onWheel","drag","onPointerDown","onPointerMove","onPointerUp","Teleport","Plus","Download","X","_hoisted_1$14","_hoisted_2$14","_hoisted_3$13","_hoisted_4$13","_hoisted_5$10","_hoisted_6$8","_hoisted_7$8","_hoisted_8$8","_hoisted_9$7","_hoisted_10$7","_hoisted_11$7","_hoisted_12$7","_hoisted_13$7","_hoisted_14$6","_hoisted_15$4","_hoisted_16$3","_hoisted_17$3","_hoisted_18$3","_hoisted_19$3","_hoisted_20$3","_hoisted_21$2","_hoisted_22$1","_hoisted_23$1","_hoisted_24$1","_hoisted_25$1","_hoisted_26$1","_hoisted_27$1","_hoisted_28$1","_hoisted_29$1","_hoisted_30$1","_hoisted_31","_hoisted_32","ImageView_default","tab","uploading","fileInput","figure","readAsDataUrl","reader","resolve","reject","file","handleFile","maxMb","upload","onFileChange","submitLink","startX","startWidth","total","factor","align","delta","ALIGN_ICONS","AlignLeft","AlignCenter","AlignRight","crop","captionShown","isWeb","isRemote","menu","toolbar","captionInput","cropping","viewing","setAlign","toggleCaption","finishCrop","download","blob","objectUrl","copyLink","replace","openOriginal","remove","cropStyle","Captions","Crop","ZoomIn","Ellipsis","RefreshCw","ExternalLink","Trash","Upload","Link","Image","ImageBlock","image","embed","Video","_hoisted_1$13","_hoisted_2$13","_hoisted_3$12","_hoisted_4$12","COLS","EmojiMenu_default","normalize","LOCALES","cache","cachedLocale","loadEmojis","locale","shortcodes","local","localByHex","codes","loc","sc","searchEmojis","limit","starts","contains","emojiPluginKey","EmojiSuggestion","_hoisted_1$12","_hoisted_2$12","_hoisted_3$11","_hoisted_4$11","_hoisted_5$9","_hoisted_6$7","_hoisted_7$7","_hoisted_8$7","_hoisted_9$6","_hoisted_10$6","_hoisted_11$6","_hoisted_12$6","_hoisted_13$6","_hoisted_14$5","FileView_default","File","AudioLines","Film","sizeLabel","bytes","units","FileBlock","_hoisted_1$11","_hoisted_2$11","_hoisted_3$10","_hoisted_4$10","_hoisted_5$8","_hoisted_6$6","_hoisted_7$6","_hoisted_8$6","_hoisted_9$5","_hoisted_10$5","_hoisted_11$5","_hoisted_12$5","_hoisted_13$5","_hoisted_14$4","_hoisted_15$3","_hoisted_16$2","_hoisted_17$2","_hoisted_18$2","_hoisted_19$2","_hoisted_20$2","SANDBOX","HtmlView_default","code","height","srcdoc","mode","interacting","fullscreen","showCode","textarea","showPreview","commit","draft","highlightEl","onInput","onKeydown","syncScroll","grammarReady","escapeHtml","toHtml","highlighted","onFile","onFullscreenKey","CodeXml","Eye","Maximize2","Pointer","HtmlBlock","_hoisted_1$10","_hoisted_2$10","_hoisted_3$9","_hoisted_4$9","_hoisted_5$7","MathView_default","rendered","editing","latex","katex","latexAttr","MathBlock","InputRule","MathInline","match","_hoisted_1$9","_hoisted_2$9","_hoisted_3$8","_hoisted_4$8","_hoisted_5$6","_hoisted_6$5","_hoisted_7$5","_hoisted_8$5","MentionMenu_default","User","FileText","Calendar","order","g","_hoisted_1$8","_hoisted_2$8","_hoisted_3$7","_hoisted_4$7","_hoisted_5$5","_hoisted_6$4","_hoisted_7$4","_hoisted_8$4","_hoisted_9$4","_hoisted_10$4","_hoisted_11$4","_hoisted_12$4","_hoisted_13$4","_hoisted_14$3","_hoisted_15$2","_hoisted_16$1","_hoisted_17$1","_hoisted_18$1","_hoisted_19$1","_hoisted_20$1","_hoisted_21$1","_hoisted_22","_hoisted_23","_hoisted_24","_hoisted_25","_hoisted_26","_hoisted_27","_hoisted_28","_hoisted_29","_hoisted_30","DatePicker_default","update","patch","inputFmt","val","commitDate","parsed","which","monthOf","commitTime","parseIsoDate","today","monthLabel","month","weekdays","fmt","days","inRange","pick","goToday","submenu","reminders","formatLabel","f","toggleEnd","toggleTime","remind","setFormat","setTimeFormat","setRemind","withKeys","ChevronLeft","ChevronRight","CircleQuestionMark","_hoisted_1$7","_hoisted_2$7","_hoisted_3$6","_hoisted_4$6","_hoisted_5$4","_hoisted_6$3","_hoisted_7$3","_hoisted_8$3","_hoisted_9$3","_hoisted_10$3","_hoisted_11$3","_hoisted_12$3","_hoisted_13$3","_hoisted_14$2","MentionView_default","dateValue","chip","panel","onDocPointer","avatar","onClick","searchInput","apply","changeDate","fireAt","clearDate","results","shallowRef","searchToken","token","pickItem","mentionPluginKey","iso","dateItems","day","make","labels","typed","norm","MentionNode","prefix","mentionSuggestion","search","MermaidPreview","SAMPLE_MERMAID","_hoisted_1$6","_hoisted_2$6","TocView_default","collect","minLevel","go","TableOfContents","toc","math","Sigma","Radical","Workflow","emoji","FILE_ICONS","mention","AtSign","html","defaultBlocks","ContentError","message","wrapUnknown","issues","repair","sanitizeContent","wrapped","json","fixed","unwrapUnknown","defineTokens","tokens","COLORS","_hoisted_1$5","_hoisted_2$5","_hoisted_3$5","_hoisted_4$5","colorRows","ColorList_default","rows","isCurrent","row","_hoisted_1$4","_hoisted_2$4","_hoisted_3$4","_hoisted_4$4","_hoisted_5$3","_hoisted_6$2","_hoisted_7$2","_hoisted_8$2","_hoisted_9$2","_hoisted_10$2","_hoisted_11$2","_hoisted_12$2","_hoisted_13$2","_hoisted_14$1","_hoisted_15$1","BlockMenu_default","targets","canTurnInto","hasText","colors","blockId","shortcutFor","turnInto","pickColor","actions","Link2","ArrowUp","ArrowDown","Repeat2","Palette","turnRows","colorRowList","colorMatches","subActive","subCount","scrollActive","openSubmenu","focusFirst","runRow","runSubmenuItem","inSub","hoverRow","keepSubmenu","flipSubmenu","width","Search","ti","_hoisted_1$3","_hoisted_2$3","_hoisted_3$3","_hoisted_4$3","_hoisted_5$2","_hoisted_6$1","_hoisted_7$1","_hoisted_8$1","_hoisted_9$1","_hoisted_10$1","_hoisted_11$1","_hoisted_12$1","_hoisted_13$1","FormatMenu_default","linkUrl","linkInput","actionsFor","shouldShow","CellSelection","actionTitle","runAction","Bold","Italic","Underline","Strikethrough","applyLink","setColor","selectionColors","activeTextColor","BubbleMenu","Baseline","Unlink","_hoisted_1$2","_hoisted_2$2","_hoisted_3$2","_hoisted_4$2","MeiOutline_default","onScreen","updateActive","schedule","onScroll","visible","closeTimer","enter","leave","tableAt","TableMap","cellPos","col","focusCell","selectRow","$cell","selectColumn","insertRow","where","insertColumn","deleteRow","deleteColumn","moveRow","moveTableRow","moveColumn","moveTableColumn","duplicateRow","$row","rowNode","duplicateColumn","cell","clearSelectedCells","colorSelectedCells","hasHeaderRow","header","hasHeaderColumn","toggleHeader","_hoisted_1$1","_hoisted_2$1","_hoisted_3$1","_hoisted_4$1","_hoisted_5$1","_hoisted_6","_hoisted_7","_hoisted_8","_hoisted_9","_hoisted_10","_hoisted_11","_hoisted_12","_hoisted_13","_hoisted_14","_hoisted_15","_hoisted_16","_hoisted_17","_hoisted_18","_hoisted_19","_hoisted_20","_hoisted_21","TableControls_default","colorNames","layer","hover","hideTimer","frame","locate","tableEl","tablePos","tableRect","wrapRect","onMouseMove","tick","onUpdate","colorOpen","menuEl","closeMenu","openMenu","screen","above","run","menuItems","mn","t2","PanelTop","ArrowUpToLine","ArrowDownToLine","Eraser","PanelLeft","ArrowLeftToLine","ArrowRightToLine","ArrowLeft","ArrowRight","onMenuKey","addRow","addColumn","cellColorOpen","onSelection","left","bgColors","GripVertical","GripHorizontal","TableCellsMerge","TableCellsSplit","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","MeiEditor_default","contentFailed","globalBlocks","inject","rootEl","outlineMin","hasTables","instanceId","useId","globalTokens","watchEffect","css","prepare","lastEmitted","collaboration","toRaw","unmounted","createEditor","extra","Editor","collaborationExtensions","nestedOptions","hovered","handlePos","onNodeChange","handlePosition","rects","onDragStart","setHandleLocked","locked","showMenu","hideTooltip","own","openMenuAt","toast","toastTimer","showToast","revealHashBlock","tooltip","tooltipTimer","showTooltip","addBlock","focusEnd","DragHandle","EditorContent","verb","MeiEditorPlugin","app","htmlBlockCsp","locales"],"sources":["../src/config.ts","../src/define-block.ts","../src/block-ops.ts","../src/extensions/block-drop.ts","../src/extensions/block-id.ts","../src/block-items.ts","../src/extensions/block-selection.ts","../src/safe-url.ts","../src/extensions/markdown-paste.ts","../src/extensions/placeholder.ts","../src/extensions/color-marks.ts","../src/composables/useScope.ts","../src/composables/usePointerMoved.ts","../src/components/SlashMenu.vue","../src/components/SlashMenu.vue","../src/recent.ts","../src/slash-items.ts","../src/theme/read.ts","../src/extensions/suggestion-renderer.ts","../src/extensions/slash-command.ts","../src/extensions/unknown.ts","../src/extensions/index.ts","../src/handle-anchor.ts","../src/keys.ts","../src/plugin-key.ts","../src/nodeviews/renderer.ts","../src/composables/useEditable.ts","../src/composables/useClickOutside.ts","../src/nodeviews/CalloutView.vue","../src/nodeviews/CalloutView.vue","../src/extensions/callout.ts","../src/lazy.ts","../src/components/MermaidDiagram.vue","../src/components/MermaidDiagram.vue","../src/nodeviews/CodeBlockView.vue","../src/nodeviews/CodeBlockView.vue","../src/extensions/code-block.ts","../src/extensions/columns.ts","../src/extensions/table.ts","../src/extensions/toggle.ts","../src/blocks/advanced.ts","../src/blocks/basic.ts","../src/nodeviews/EmbedView.vue","../src/nodeviews/EmbedView.vue","../src/extensions/embed.ts","../src/components/ImageCropper.vue","../src/components/ImageCropper.vue","../src/components/ImageLightbox.vue","../src/components/ImageLightbox.vue","../src/nodeviews/ImageView.vue","../src/nodeviews/ImageView.vue","../src/extensions/image-block.ts","../src/blocks/media.ts","../src/components/EmojiMenu.vue","../src/components/EmojiMenu.vue","../src/emoji-data.ts","../src/extensions/emoji.ts","../src/nodeviews/FileView.vue","../src/nodeviews/FileView.vue","../src/extensions/file-block.ts","../src/nodeviews/HtmlView.vue","../src/nodeviews/HtmlView.vue","../src/extensions/html-block.ts","../src/nodeviews/MathView.vue","../src/nodeviews/MathView.vue","../src/extensions/math.ts","../src/components/MentionMenu.vue","../src/components/MentionMenu.vue","../src/components/DatePicker.vue","../src/components/DatePicker.vue","../src/nodeviews/MentionView.vue","../src/nodeviews/MentionView.vue","../src/extensions/mention.ts","../src/extensions/mermaid.ts","../src/nodeviews/TocView.vue","../src/nodeviews/TocView.vue","../src/extensions/toc.ts","../src/blocks/extras.ts","../src/blocks/index.ts","../src/content.ts","../src/theme/index.ts","../src/colors.ts","../src/components/ColorList.vue","../src/components/ColorList.vue","../src/components/BlockMenu.vue","../src/components/BlockMenu.vue","../src/components/FormatMenu.vue","../src/components/FormatMenu.vue","../src/components/MeiOutline.vue","../src/components/MeiOutline.vue","../src/table-ops.ts","../src/components/TableControls.vue","../src/components/TableControls.vue","../src/components/MeiEditor.vue","../src/components/MeiEditor.vue","../src/plugin.ts"],"sourcesContent":["import { Extension } from '@tiptap/core'\nimport { shallowReactive } from 'vue'\nimport type { BlockType } from './block-items'\nimport type { FormatAction } from './define-block'\nimport { type EditorMessages, type LocaleName, vi } from './locale'\n\n/** Uploads an image file and resolves to its public URL. */\nexport type ImageUploader = (file: File) => Promise<string>\n\nexport interface MeiConfigStorage {\n messages: EditorMessages\n locale: LocaleName\n /** Menu entries of the loaded blocks (slash menu, \"Turn into\"). */\n items: BlockType[]\n /** Extra bubble-menu buttons of the loaded blocks (e.g. \"Comment\"). */\n formatActions: FormatAction[]\n /** Custom uploader. Without it, images are inlined as base64 data URLs. */\n uploadImage: ImageUploader | null\n /** Max image size in MB. */\n maxImageSize: number\n /**\n * Attributes for every element that carries theme tokens: the editor root and\n * popovers teleported to <body> (so they get the same mode and overrides).\n */\n scope: { class: string[], 'data-me-id': string }\n}\n\ndeclare module '@tiptap/core' {\n interface Storage {\n meiConfig: MeiConfigStorage\n }\n}\n\n/** Holds editor-wide settings that menus and node views read at runtime. */\nexport const MeiConfig = Extension.create<Partial<MeiConfigStorage>, MeiConfigStorage>({\n name: 'meiConfig',\n\n // Reactive so menus and node views re-render when the locale or options change.\n addStorage() {\n return shallowReactive({\n messages: this.options.messages ?? vi,\n locale: this.options.locale ?? 'vi',\n items: this.options.items ?? [],\n formatActions: this.options.formatActions ?? [],\n uploadImage: this.options.uploadImage ?? null,\n maxImageSize: this.options.maxImageSize ?? 5,\n scope: this.options.scope ?? { 'class': ['me-scope'], 'data-me-id': '' },\n })\n },\n})\n","import type { AnyExtension, Editor } from '@tiptap/core'\nimport type { Component } from 'vue'\nimport type { BlockType } from './block-items'\nimport type { LocaleName, PartialMessages } from './locale'\nimport type { BlockRenderers } from './render/types'\n\n/**\n * A button a block adds to the selection bubble menu (after the built-in marks),\n * e.g. \"Comment\". `readOnly: true` also shows it in read-only editors.\n */\nexport interface FormatAction {\n id: string\n icon: Component\n title: string | ((editor: Editor) => string)\n run: (editor: Editor) => void\n /** Show in read-only editors too (the menu then shows only these actions). */\n readOnly?: boolean\n /** Hide the action for this editor / selection. */\n isVisible?: (editor: Editor) => boolean\n}\n\nexport interface BlockSpec<O extends object = Record<string, never>> {\n /** Unique name, e.g. `'heading'`, `'math'`. */\n name: string\n /** Default options, overridable with `.configure()`. */\n defaults?: O\n /** Tiptap extensions the block needs. Extensions shared by blocks are de-duplicated by name. */\n extensions?: (options: O) => AnyExtension[]\n /** Slash menu / \"Turn into\" entries. */\n items?: (options: O) => BlockType[]\n /** ProseMirror node types this block creates (they get stable ids). */\n nodes?: string[]\n /** UI strings per locale, merged into the editor messages (for custom blocks). */\n messages?: Partial<Record<LocaleName, PartialMessages>>\n /** Bubble-menu buttons for a text selection. */\n formatActions?: (options: O) => FormatAction[]\n /**\n * Server-side HTML for the block's nodes / marks, used by `renderHTML` from\n * `@toantranmei/editor/render`. Must not touch the DOM.\n */\n render?: (options: O) => BlockRenderers\n}\n\n/** A block ready to pass to `<MeiEditor :blocks>`. */\nexport interface BlockDefinition<O extends object = any> {\n name: string\n options: O\n extensions: AnyExtension[]\n items: BlockType[]\n nodes: string[]\n messages?: Partial<Record<LocaleName, PartialMessages>>\n formatActions?: FormatAction[]\n /** Static HTML renderers (see `renderHTML`). */\n render?: BlockRenderers\n /** Returns a copy with different options: `file.configure({ upload })`. */\n configure: (options: Partial<O>) => BlockDefinition<O>\n}\n\n/**\n * Declares a block: its Tiptap extensions, menu entries and strings, in one place.\n *\n * @example\n * export const invoice = defineBlock({\n * name: 'invoice',\n * nodes: ['invoice'],\n * extensions: () => [InvoiceNode],\n * items: () => [{ id: 'invoice', icon: Receipt, group: 'advanced', keywords: ['bill'], insert: c => c.insertInvoice() }],\n * messages: { vi: { blocks: { invoice: { title: 'Hoá đơn', description: 'Chèn hoá đơn' } } } },\n * })\n */\nexport function defineBlock<O extends object = Record<string, never>>(spec: BlockSpec<O>): BlockDefinition<O> {\n const build = (options: O): BlockDefinition<O> => ({\n name: spec.name,\n options,\n extensions: spec.extensions?.(options) ?? [],\n items: spec.items?.(options) ?? [],\n nodes: spec.nodes ?? [],\n messages: spec.messages,\n formatActions: spec.formatActions?.(options),\n render: spec.render?.(options),\n configure: overrides => build({ ...options, ...overrides }),\n })\n return build({ ...(spec.defaults ?? {}) } as O)\n}\n\n/** Flattens block definitions into one extension list (first extension per name wins). */\nexport function collectExtensions(blocks: BlockDefinition[]): AnyExtension[] {\n const seen = new Set<string>()\n return blocks.flatMap(b => b.extensions).filter((ext) => {\n if (seen.has(ext.name)) return false\n seen.add(ext.name)\n return true\n })\n}\n","/**\n * Operations on a range of sibling blocks. Shared by the ⋮⋮ menu, keyboard shortcuts,\n * block selection and drag & drop, so each behavior has exactly one implementation.\n *\n * A \"block\" is a direct child of the doc or of a column.\n */\nimport type { Editor } from '@tiptap/core'\nimport { Fragment, type Node as PMNode, type ResolvedPos } from '@tiptap/pm/model'\nimport { type EditorState, TextSelection, type Transaction } from '@tiptap/pm/state'\nimport { NodeRangeSelection } from '@tiptap/extension-node-range'\nimport type { BlockType } from './block-items'\nimport type { ColorName } from './colors'\n\n/** `[from, to)` covers whole sibling blocks; `depth` is their parent's depth. */\nexport interface BlockRange { from: number, to: number, depth: number }\n\nconst CONTAINERS = ['doc', 'column']\n\n/** The block owning `$pos`: deepest ancestor whose parent is the doc or a column. */\nexport function blockAt($pos: ResolvedPos): { node: PMNode, pos: number, depth: number } | null {\n for (let d = $pos.depth; d >= 1; d--) {\n const node = $pos.node(d)\n if (CONTAINERS.includes($pos.node(d - 1).type.name) && !['column', 'columns'].includes(node.type.name)) {\n return { node, pos: $pos.before(d), depth: d - 1 }\n }\n }\n // Atom blocks (image, divider…) selected as nodes.\n const after = $pos.nodeAfter\n if (after?.isBlock && CONTAINERS.includes($pos.parent.type.name)) return { node: after, pos: $pos.pos, depth: $pos.depth }\n return null\n}\n\nexport const rangeOfBlock = (block: { node: PMNode, pos: number, depth: number }): BlockRange =>\n ({ from: block.pos, to: block.pos + block.node.nodeSize, depth: block.depth })\n\n/** Range spanning the blocks of `a` and `b` (falls back to their shared container level). */\nexport function rangeBetween(doc: PMNode, a: number, b: number): BlockRange | null {\n const ba = blockAt(doc.resolve(a))\n const bb = blockAt(doc.resolve(b))\n if (!ba || !bb) return null\n if (ba.depth === bb.depth && doc.resolve(ba.pos).parent === doc.resolve(bb.pos).parent) {\n return { from: Math.min(ba.pos, bb.pos), to: Math.max(ba.pos + ba.node.nodeSize, bb.pos + bb.node.nodeSize), depth: ba.depth }\n }\n // Different containers (e.g. inside vs. outside columns): select whole top-level blocks.\n const top = (pos: number) => {\n const $p = doc.resolve(pos)\n return { from: $p.before(1), to: $p.after(1) }\n }\n const ta = top(ba.pos + 1)\n const tb = top(bb.pos + 1)\n return { from: Math.min(ta.from, tb.from), to: Math.max(ta.to, tb.to), depth: 0 }\n}\n\nexport const isBlockSelection = (state: EditorState) => state.selection instanceof NodeRangeSelection\n\n/** Blocks the next command acts on: the block selection, or the block(s) holding the cursor. */\nexport function currentRange(state: EditorState): BlockRange | null {\n const sel = state.selection\n if (sel instanceof NodeRangeSelection) return { from: sel.from, to: sel.to, depth: sel.depth ?? 0 }\n return rangeBetween(state.doc, sel.from, sel.to)\n}\n\n/** Nodes in a range, in order. */\nexport function blocksIn(doc: PMNode, range: BlockRange): { node: PMNode, pos: number }[] {\n const out: { node: PMNode, pos: number }[] = []\n for (let pos = range.from; pos < range.to;) {\n const node = doc.nodeAt(pos)\n if (!node) break\n out.push({ node, pos })\n pos += node.nodeSize\n }\n return out\n}\n\nexport function setBlockSelection(tr: Transaction, range: BlockRange) {\n return tr.setSelection(NodeRangeSelection.create(tr.doc, range.from + 1, range.to - 1, range.depth))\n}\n\nexport function selectBlocks(editor: Editor, range: BlockRange) {\n editor.view.dispatch(setBlockSelection(editor.state.tr, range))\n}\n\n/**\n * Called after removing content from inside a column: drops the column if it became\n * empty and unwraps the columns block when a single column is left (Notion behavior).\n */\nexport function dissolveEmptyColumn(tr: Transaction, pos: number) {\n const $pos = tr.doc.resolve(Math.min(pos, tr.doc.content.size))\n let columnDepth = -1\n for (let d = $pos.depth; d >= 1; d--) {\n if ($pos.node(d).type.name === 'column') {\n columnDepth = d\n break\n }\n }\n if (columnDepth < 1) return\n const column = $pos.node(columnDepth)\n const isEmpty = column.childCount === 1 && column.firstChild!.isTextblock && column.firstChild!.content.size === 0\n if (!isEmpty) return\n\n const columns = $pos.node(columnDepth - 1)\n const columnsPos = $pos.before(columnDepth - 1)\n const rest: PMNode[] = []\n columns.forEach(c => c !== column && rest.push(c))\n const replacement = rest.length >= 2\n ? Fragment.from(columns.copy(Fragment.from(rest)))\n : rest.length === 1 ? rest[0]!.content : Fragment.empty\n tr.replaceWith(columnsPos, columnsPos + columns.nodeSize, replacement)\n}\n\n/** Restores a block or text selection over `range` after it moved to `next`. */\nfunction reselect(tr: Transaction, wasBlocks: boolean, oldFrom: number, caret: number, next: BlockRange) {\n if (wasBlocks) return setBlockSelection(tr, next)\n return tr.setSelection(TextSelection.near(tr.doc.resolve(Math.min(next.from + (caret - oldFrom), tr.doc.content.size))))\n}\n\nexport function deleteBlocks(editor: Editor, range: BlockRange) {\n const tr = editor.state.tr.delete(range.from, range.to)\n dissolveEmptyColumn(tr, tr.mapping.map(range.from))\n tr.setSelection(TextSelection.near(tr.doc.resolve(Math.min(tr.mapping.map(range.from), tr.doc.content.size))))\n editor.view.dispatch(tr.scrollIntoView())\n editor.view.focus()\n}\n\nexport function duplicateBlocks(editor: Editor, range: BlockRange) {\n const { state } = editor\n const slice = state.doc.slice(range.from, range.to)\n const tr = state.tr.insert(range.to, slice.content)\n const next = { from: range.to, to: range.to + slice.content.size, depth: range.depth }\n reselect(tr, isBlockSelection(state), range.from, state.selection.from, next)\n editor.view.dispatch(tr.scrollIntoView())\n}\n\n/** Swaps the range with its previous/next sibling. Returns false at the edge. */\nexport function moveBlocks(editor: Editor, range: BlockRange, dir: 'up' | 'down') {\n const { state } = editor\n const $from = state.doc.resolve(range.from)\n const parent = $from.parent\n const startIndex = $from.index()\n const endIndex = state.doc.resolve(range.to).index()\n const slice = state.doc.slice(range.from, range.to)\n const tr = state.tr\n\n let insertAt: number\n if (dir === 'up') {\n if (startIndex === 0) return false\n insertAt = range.from - parent.child(startIndex - 1).nodeSize\n tr.delete(range.from, range.to)\n }\n else {\n if (endIndex >= parent.childCount) return false\n const after = range.to + parent.child(endIndex).nodeSize\n tr.delete(range.from, range.to)\n insertAt = tr.mapping.map(after)\n }\n tr.insert(insertAt, slice.content)\n reselect(tr, isBlockSelection(state), range.from, state.selection.from, { from: insertAt, to: insertAt + slice.content.size, depth: range.depth })\n editor.view.dispatch(tr.scrollIntoView())\n return true\n}\n\n/** Selects the text of every block in the range (for marks / turn into). */\nfunction selectText(tr: Transaction, from: number, to: number) {\n return tr.setSelection(TextSelection.between(tr.doc.resolve(from + 1), tr.doc.resolve(Math.max(from + 1, to - 1))))\n}\n\n/**\n * Converts every block in the range, keeping text. Toggles are unwrapped first, then\n * lists/quotes/callouts are cleared to paragraphs and the new type is applied.\n */\nexport function turnBlocksInto(editor: Editor, range: BlockRange, block: BlockType) {\n if (!block.turnInto) return\n const wasBlocks = isBlockSelection(editor.state)\n let to = range.to\n\n const chain = editor.chain().focus().command(({ tr }) => {\n // Unwrap toggles from last to first so earlier positions stay valid.\n for (const { node, pos } of blocksIn(tr.doc, range).reverse()) {\n if (node.type.name !== 'details') continue\n const [summary, content] = [node.child(0), node.child(1)]\n const paragraph = tr.doc.type.schema.nodes.paragraph!.create(null, summary.content)\n const fragment = Fragment.from(paragraph).append(content.content)\n tr.replaceWith(pos, pos + node.nodeSize, fragment)\n }\n to = tr.mapping.map(range.to)\n selectText(tr, range.from, to)\n return true\n }).clearNodes()\n block.turnInto(chain).run()\n\n if (wasBlocks) {\n const { from: a, to: b } = editor.state.selection\n const next = rangeBetween(editor.state.doc, a, b)\n if (next) selectBlocks(editor, next)\n }\n}\n\n/**\n * Colors whole blocks, like Notion: blocks that support it get a block color (the\n * background fills the block, and empty blocks color what's typed later); others\n * (callouts, code…) get the color on their text. Inline colors of the same kind are\n * cleared so the block color shows.\n */\nexport function colorBlocks(editor: Editor, range: BlockRange, kind: 'text' | 'bg', color: ColorName) {\n const attr = kind === 'text' ? 'blockColor' : 'blockBg'\n const mark = editor.schema.marks[kind === 'text' ? 'textColor' : 'bgColor']\n const value = color === 'default' ? null : color\n const wasBlocks = isBlockSelection(editor.state)\n editor.chain().focus().command(({ tr }) => {\n for (const { node, pos } of blocksIn(tr.doc, range)) {\n const end = pos + node.nodeSize\n if (kind === 'bg' && node.type.name === 'callout') {\n // A callout's background is its own color.\n tr.setNodeAttribute(pos, 'color', value ?? 'gray')\n }\n else if (node.type.spec.attrs?.[attr]) {\n tr.setNodeAttribute(pos, attr, value)\n if (mark) tr.removeMark(pos, end, mark)\n }\n else if (mark) {\n tr.removeMark(pos, end, mark)\n if (value) tr.addMark(pos, end, mark.create({ color: value }))\n }\n }\n return true\n }).run()\n if (wasBlocks) selectBlocks(editor, range)\n}\n\n/** Text/background color shared by all text in the range, if uniform. */\nexport function rangeColors(state: EditorState, range: BlockRange) {\n const found = { text: new Set<string>(), bg: new Set<string>() }\n let any = false\n // Inline mark wins, else the nearest colored block around the text.\n const add = (pos: number, marks: readonly { type: { name: string }, attrs: Record<string, any> }[]) => {\n const $pos = state.doc.resolve(pos)\n const fromBlocks = (attr: string) => {\n for (let d = $pos.depth; d > 0; d--) if ($pos.node(d).attrs[attr]) return $pos.node(d).attrs[attr] as string\n return 'default'\n }\n any = true\n found.text.add(marks.find(m => m.type.name === 'textColor')?.attrs.color ?? fromBlocks('blockColor'))\n found.bg.add(marks.find(m => m.type.name === 'bgColor')?.attrs.color ?? fromBlocks('blockBg'))\n }\n state.doc.nodesBetween(range.from, range.to, (node, pos) => {\n if (node.isText) add(pos, node.marks)\n // An empty colored line still shows (and ticks) its color.\n else if (node.isTextblock && !node.content.size) add(pos + 1, [])\n })\n const single = (s: Set<string>): string | null => (any && s.size === 1 ? [...s][0]! : null)\n return { text: single(found.text), bg: single(found.bg) }\n}\n","import { Extension } from '@tiptap/core'\nimport type { Node as PMNode, Slice } from '@tiptap/pm/model'\nimport { NodeSelection, Plugin, PluginKey, TextSelection } from '@tiptap/pm/state'\nimport type { EditorView } from '@tiptap/pm/view'\nimport { dissolveEmptyColumn } from '../block-ops'\n\nexport interface BlockDropOptions {\n /** Node types whose direct children are \"blocks\" you can drop between. */\n containers: string[]\n /** Class of the drop indicator line. */\n indicatorClass: string\n /** Max columns when dropping beside a block. */\n maxColumns: number\n}\n\nexport interface BlockDropStorage {\n /** True while a block is being dragged from the drag handle. */\n active: boolean\n}\n\ndeclare module '@tiptap/core' {\n interface Storage {\n blockDrop: BlockDropStorage\n }\n}\n\ninterface Line { left: number, top: number, width: number, height?: number, vertical?: boolean }\n\n/** Where a dragged block lands. */\ntype DropTarget =\n /** Between blocks (or appended inside a list/toggle/callout when nested). */\n | { kind: 'insert', pos: number, line: Line }\n /** Beside a block: wraps it into two columns. */\n | { kind: 'wrap', blockPos: number, side: 'left' | 'right', line: Line }\n /** Beside a column: adds a new column. */\n | { kind: 'column', pos: number, line: Line }\n\n// Interaction thresholds (behavior, not visuals).\nconst SIDE_ZONE = 48 // px from a block's right edge that means \"make columns\"\n// Left edge: narrower, and only after a clear sideways move. Dragging straight down from\n// the handle keeps the pointer near blocks' left edges, which must not create columns.\nconst LEFT_ZONE = 24\nconst LEFT_INTENT = 60 // px of horizontal travel from the drag start\nconst NEST_INDENT = 32 // px right of a block's left edge that means \"nest inside\"\nconst SCROLL_ZONE = 64 // px from the viewport edge that starts auto-scroll\nconst SCROLL_SPEED = 18 // max px per frame\n\n/** Blocks that can take children at their end when you drop with an indent. */\nconst NESTABLE = ['bulletList', 'orderedList', 'taskList', 'details', 'callout']\n\nexport const blockDropKey = new PluginKey('blockDrop')\n\n/**\n * Notion-style drop for blocks dragged from the drag handle:\n * - between blocks (top level or in a column), never inside a list item by accident;\n * - beside a block (left/right edge) to create or extend columns;\n * - with an indent below a list/toggle/callout to nest inside it;\n * - auto-scrolls near the viewport edges.\n */\nexport const BlockDrop = Extension.create<BlockDropOptions, BlockDropStorage>({\n name: 'blockDrop',\n\n addOptions() {\n return { containers: ['doc', 'column'], indicatorClass: 'me-drop-indicator', maxColumns: 5 }\n },\n\n addStorage() {\n return { active: false }\n },\n\n addProseMirrorPlugins() {\n const { containers, indicatorClass, maxColumns } = this.options\n const storage = this.storage\n const editor = this.editor\n let indicator: HTMLElement | null = null\n\n const hide = () => {\n indicator?.remove()\n indicator = null\n }\n const show = (line: Line) => {\n if (!indicator) {\n indicator = document.createElement('div')\n // Lives in <body>, so copy the editor's theme scope (mode class + overrides id).\n const scope = editor.storage.meiConfig?.scope\n indicator.className = [...(scope?.class ?? ['me-scope']), indicatorClass].join(' ')\n if (scope?.['data-me-id']) indicator.dataset.meId = scope['data-me-id']\n document.body.appendChild(indicator)\n }\n indicator.classList.toggle('is-vertical', !!line.vertical)\n Object.assign(indicator.style, {\n left: `${line.left}px`,\n top: `${line.top}px`,\n width: line.vertical ? '' : `${line.width}px`,\n height: line.vertical ? `${line.height}px` : '',\n })\n }\n\n const rectOf = (view: EditorView, pos: number) => {\n const dom = view.nodeDOM(pos)\n return dom instanceof HTMLElement ? dom.getBoundingClientRect() : null\n }\n\n /** True if the dragged slice contains columns (no columns inside columns). */\n const draggingColumns = (view: EditorView) => {\n let found = false\n view.dragging?.slice.content.descendants((n) => {\n if (n.type.name === 'columns') found = true\n return !found\n })\n return found\n }\n\n /**\n * Picks the drop target from geometry (posAtCoords fails over node views and gaps):\n * the container under the pointer (a column or the doc), the child block at the\n * pointer's height, then side/indent zones of that block.\n */\n let dragStartX: number | null = null\n const findDropTarget = (view: EditorView, x: number, y: number): DropTarget | null => {\n const { doc, selection } = view.state\n let container: PMNode = doc\n let containerPos = -1\n let start = 0\n\n doc.descendants((node, pos) => {\n if (containers.includes(node.type.name) && node.type.name !== 'doc') {\n const r = rectOf(view, pos)\n if (r && x >= r.left && x <= r.right && y >= r.top && y <= r.bottom) {\n container = node\n containerPos = pos\n start = pos + 1\n }\n return false\n }\n // Only walk into wrappers that hold containers (e.g. `columns`).\n return node.type.name === 'columns'\n })\n\n // Child block at the pointer's height (or the last one).\n type Hit = { node: PMNode, pos: number, rect: DOMRect }\n let hit = null as Hit | null\n let last = null as Hit | null\n container.forEach((child, offset) => {\n if (hit) return\n const pos = start + offset\n const rect = rectOf(view, pos)\n if (!rect) return\n if (y < rect.bottom) hit = { node: child, pos, rect }\n last = { node: child, pos, rect }\n })\n const block = hit ?? last\n if (!block) return null\n const { rect } = block\n const isSelf = block.pos >= selection.from && block.pos < selection.to\n\n // Beside a block → columns.\n const rightZone = Math.min(SIDE_ZONE, rect.width * 0.2)\n const leftIntent = dragStartX !== null && Math.abs(x - dragStartX) >= LEFT_INTENT\n const side = x > rect.right - rightZone ? 'right' : leftIntent && x < rect.left + LEFT_ZONE ? 'left' : null\n if (side && !isSelf && !draggingColumns(view)) {\n const vertical = (edgeX: number, r: DOMRect): Line => ({ left: edgeX, top: r.top, width: 0, height: r.height, vertical: true })\n if (container.type.name === 'column') {\n // Add a column next to the hovered column.\n const columns = doc.resolve(containerPos).parent\n const colRect = rectOf(view, containerPos)\n if (columns.childCount < maxColumns && colRect) {\n return {\n kind: 'column',\n pos: side === 'left' ? containerPos : containerPos + container.nodeSize,\n line: vertical(side === 'left' ? colRect.left : colRect.right, colRect),\n }\n }\n }\n else if (block.node.type.name === 'columns') {\n if (block.node.childCount < maxColumns) {\n return { kind: 'column', pos: side === 'left' ? block.pos + 1 : block.pos + block.node.nodeSize - 1, line: vertical(side === 'left' ? rect.left : rect.right, rect) }\n }\n }\n else {\n return { kind: 'wrap', blockPos: block.pos, side, line: vertical(side === 'left' ? rect.left : rect.right, rect) }\n }\n }\n\n const before = !!hit && y < rect.top + rect.height / 2\n // Indented drop below a list/toggle/callout → nest at its end.\n if (!before && !isSelf && NESTABLE.includes(block.node.type.name) && x > rect.left + NEST_INDENT && !draggingColumns(view)) {\n const end = block.pos + block.node.nodeSize\n // Lists: inside the last item; toggle: inside its content; callout: inside it.\n const pos = block.node.type.name === 'callout' ? end - 1 : end - 2\n return { kind: 'insert', pos, line: { left: rect.left + NEST_INDENT, top: rect.bottom, width: rect.width - NEST_INDENT } }\n }\n\n return {\n kind: 'insert',\n pos: before ? block.pos : block.pos + block.node.nodeSize,\n line: { left: rect.left, top: before ? rect.top : rect.bottom, width: rect.width },\n }\n }\n\n /** Generous hit area around the editor, so drops in the gutter still count. */\n const isNearEditor = (view: EditorView, e: DragEvent) => {\n const r = view.dom.getBoundingClientRect()\n return e.clientY > r.top - 24 && e.clientY < r.bottom + 120 && e.clientX > r.left - 120 && e.clientX < r.right + 60\n }\n\n const moveBlock = (view: EditorView, target: DropTarget) => {\n const slice = view.dragging?.slice\n const { from, to } = view.state.selection\n view.dragging = null\n if (!slice || slice.size === 0) return\n if (target.kind === 'insert' && target.pos >= from && target.pos <= to) return\n\n const { schema } = view.state\n const tr = view.state.tr\n tr.delete(from, to)\n dissolveEmptyColumn(tr, tr.mapping.map(from))\n\n let insertAt: number\n if (target.kind === 'wrap') {\n const pos = tr.mapping.map(target.blockPos)\n const node = tr.doc.nodeAt(pos)\n if (!node) return\n const column = schema.nodes.column!\n const dragged = column.create(null, slice.content)\n const existing = column.create(null, node)\n tr.replaceWith(pos, pos + node.nodeSize, schema.nodes.columns!.create(null, target.side === 'left' ? [dragged, existing] : [existing, dragged]))\n insertAt = target.side === 'left' ? pos + 2 : pos + 2 + existing.nodeSize\n }\n else if (target.kind === 'column' && tr.doc.resolve(tr.mapping.map(target.pos)).parent.type.name === 'columns') {\n insertAt = tr.mapping.map(target.pos)\n tr.insert(insertAt, schema.nodes.column!.create(null, slice.content))\n insertAt += 1\n }\n else {\n // Plain insert (also the fallback if removing the block dissolved the target columns).\n insertAt = tr.mapping.map(target.pos)\n tr.replaceRange(insertAt, insertAt, slice as Slice)\n }\n\n // Select the moved block (atoms) or put the cursor in it, like Notion.\n const moved = tr.doc.resolve(insertAt).nodeAfter\n if (moved?.isAtom && NodeSelection.isSelectable(moved)) tr.setSelection(NodeSelection.create(tr.doc, insertAt))\n else tr.setSelection(TextSelection.near(tr.doc.resolve(Math.min(insertAt + 1, tr.doc.content.size))))\n\n view.dispatch(tr.scrollIntoView())\n view.focus()\n }\n\n // Auto-scroll the nearest scrollable ancestor (or the window) near the viewport edges.\n let scrollFrame = 0\n let scrollSpeed = 0\n const scroller = (view: EditorView): Element | Window => {\n for (let el = view.dom.parentElement; el; el = el.parentElement) {\n const { overflowY } = getComputedStyle(el)\n if (/(auto|scroll)/.test(overflowY) && el.scrollHeight > el.clientHeight) return el\n }\n return window\n }\n const stopScroll = () => {\n cancelAnimationFrame(scrollFrame)\n scrollFrame = 0\n scrollSpeed = 0\n }\n const updateScroll = (view: EditorView, y: number) => {\n const target = scroller(view)\n const bounds = target === window ? { top: 0, bottom: window.innerHeight } : (target as Element).getBoundingClientRect()\n const fromTop = y - bounds.top\n const fromBottom = bounds.bottom - y\n scrollSpeed = fromTop < SCROLL_ZONE\n ? -SCROLL_SPEED * (1 - fromTop / SCROLL_ZONE)\n : fromBottom < SCROLL_ZONE ? SCROLL_SPEED * (1 - fromBottom / SCROLL_ZONE) : 0\n if (!scrollSpeed) return stopScroll()\n if (scrollFrame) return\n const step = () => {\n if (!scrollSpeed) return\n target.scrollBy({ top: scrollSpeed })\n scrollFrame = requestAnimationFrame(step)\n }\n scrollFrame = requestAnimationFrame(step)\n }\n\n return [\n new Plugin({\n key: blockDropKey,\n // Listen on the document in the capture phase: ProseMirror ignores drag events\n // over node views (callout, image, columns...), and drops in the gutter should work too.\n view: (view) => {\n const onDragOver = (e: DragEvent) => {\n if (!storage.active || !view.dragging) return\n dragStartX ??= e.clientX\n updateScroll(view, e.clientY)\n if (!isNearEditor(view, e)) return hide()\n e.preventDefault()\n e.stopPropagation()\n if (e.dataTransfer) e.dataTransfer.dropEffect = 'move'\n const target = findDropTarget(view, e.clientX, e.clientY)\n if (target) show(target.line)\n else hide()\n }\n const onDrop = (e: DragEvent) => {\n if (!storage.active) return\n storage.active = false\n const target = isNearEditor(view, e) ? findDropTarget(view, e.clientX, e.clientY) : null\n dragStartX = null\n hide()\n stopScroll()\n if (!target) return\n e.preventDefault()\n e.stopPropagation()\n moveBlock(view, target)\n }\n const onDragEnd = () => {\n storage.active = false\n dragStartX = null\n hide()\n stopScroll()\n }\n document.addEventListener('dragover', onDragOver, true)\n document.addEventListener('drop', onDrop, true)\n document.addEventListener('dragend', onDragEnd, true)\n return {\n destroy() {\n document.removeEventListener('dragover', onDragOver, true)\n document.removeEventListener('drop', onDrop, true)\n document.removeEventListener('dragend', onDragEnd, true)\n hide()\n stopScroll()\n },\n }\n },\n }),\n ]\n },\n})\n\n","import { combineTransactionSteps, Extension, getChangedRanges, type JSONContent } from '@tiptap/core'\nimport type { Node as PMNode } from '@tiptap/pm/model'\nimport { Plugin, PluginKey, Selection } from '@tiptap/pm/state'\n\nexport interface BlockIdOptions {\n /** Node types that get an id. */\n types: string[]\n /** Attribute name (rendered as `data-<name>`). */\n attributeName: string\n generate: () => string\n}\n\n/** Above this many id changes, rebuild the doc in one step instead of one step per node. */\nconst BULK_THRESHOLD = 300\n\nexport const uuid = () => (globalThis.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`)\n\n/**\n * Gives every block in a JSON document a unique id before it's loaded — one O(n) pass,\n * so opening large documents doesn't need thousands of id-setting steps.\n */\nexport function assignIds(doc: JSONContent | null, types: string[], generate: () => string = uuid, attr = 'id'): JSONContent | null {\n if (!doc) return doc\n const typeSet = new Set(types)\n const seen = new Set<string>()\n const visit = (node: JSONContent): JSONContent => {\n let out = node\n if (node.type && typeSet.has(node.type)) {\n const id = node.attrs?.[attr]\n if (!id || seen.has(id)) out = { ...node, attrs: { ...node.attrs, [attr]: generate() } }\n seen.add(out.attrs![attr])\n }\n return out.content ? { ...out, content: out.content.map(visit) } : out\n }\n return visit(doc)\n}\n\n/** Rebuilds a node tree with new ids at the given positions (single-step bulk update). */\nfunction rebuild(doc: PMNode, ids: Map<number, string>, attr: string): PMNode {\n const visit = (node: PMNode, pos: number): PMNode => {\n if (node.isText) return node\n const children: PMNode[] = []\n node.forEach((child, offset) => children.push(visit(child, pos + 1 + offset)))\n const id = ids.get(pos)\n const attrs = id ? { ...node.attrs, [attr]: id } : node.attrs\n return node.type.create(attrs, children.length ? children : node.content, node.marks)\n }\n // The doc node itself has no position; its children start at 0.\n const children: PMNode[] = []\n doc.forEach((child, offset) => children.push(visit(child, offset)))\n return doc.type.create(doc.attrs, children)\n}\n\n/**\n * Stable block ids, linear-time. Replaces Tiptap's UniqueID, which is O(n²) on large\n * documents (indexOf-based duplicate search over every id, and position-shifting\n * setNodeMarkup steps). Here: only nodes inserted by the transaction are checked,\n * duplicates use a Set, and ids are written with setNodeAttribute (no position shifts).\n */\nexport const BlockId = Extension.create<BlockIdOptions>({\n name: 'blockId',\n\n addOptions: () => ({ types: [], attributeName: 'id', generate: uuid }),\n\n addGlobalAttributes() {\n const name = this.options.attributeName\n return [{\n types: this.options.types,\n attributes: {\n [name]: {\n default: null,\n keepOnSplit: false,\n parseHTML: (el: HTMLElement) => el.getAttribute(`data-${name}`),\n renderHTML: (attrs: Record<string, any>) => (attrs[name] ? { [`data-${name}`]: attrs[name] } : {}),\n },\n },\n }]\n },\n\n addProseMirrorPlugins() {\n const { types, attributeName: attr, generate } = this.options\n const typeSet = new Set(types)\n\n return [new Plugin({\n key: new PluginKey('blockId'),\n appendTransaction(transactions, oldState, newState) {\n if (!transactions.some(tr => tr.docChanged) || transactions.some(tr => tr.getMeta('blockId:skip'))) return null\n\n // Nodes that start inside a changed range were inserted or rebuilt by this change.\n const transform = combineTransactionSteps(oldState.doc, [...transactions])\n const candidates: { pos: number, id: string | null }[] = []\n for (const { newRange } of getChangedRanges(transform)) {\n newState.doc.nodesBetween(newRange.from, newRange.to, (node, pos) => {\n if (pos >= newRange.from && typeSet.has(node.type.name)) candidates.push({ pos, id: node.attrs[attr] ?? null })\n })\n }\n if (!candidates.length) return null\n\n // Ids already used outside the candidates (built only when a candidate has an id).\n const needsCheck = candidates.some(c => c.id)\n const counts = new Map<string, number>()\n if (needsCheck) {\n newState.doc.descendants((node) => {\n const id = node.attrs[attr]\n if (id && typeSet.has(node.type.name)) counts.set(id, (counts.get(id) ?? 0) + 1)\n })\n }\n\n const inCandidates = new Map<string, number>()\n for (const c of candidates) if (c.id) inCandidates.set(c.id, (inCandidates.get(c.id) ?? 0) + 1)\n\n const updates = new Map<number, string>()\n const kept = new Set<string>()\n for (const c of candidates) {\n // An id already used by an untouched node (e.g. the original of a paste or a\n // duplicate) is replaced; among inserted nodes the first occurrence keeps it.\n const usedElsewhere = !!c.id && (counts.get(c.id) ?? 0) > (inCandidates.get(c.id) ?? 0)\n const repeated = !!c.id && kept.has(c.id)\n if (!c.id || usedElsewhere || repeated) updates.set(c.pos, generate())\n else kept.add(c.id)\n }\n if (!updates.size) return null\n\n const tr = newState.tr\n if (updates.size > BULK_THRESHOLD) {\n // Each attribute step re-validates the parent's whole content, so thousands of\n // them on top-level blocks are O(n²). Rebuild once instead.\n const anchor = newState.selection.from\n tr.replaceWith(0, newState.doc.content.size, rebuild(newState.doc, updates, attr).content)\n tr.setSelection(Selection.near(tr.doc.resolve(Math.min(anchor, tr.doc.content.size))))\n }\n else {\n for (const [pos, id] of updates) tr.setNodeAttribute(pos, attr, id)\n }\n return tr.setMeta('addToHistory', false)\n },\n })]\n },\n})\n","import type { ChainedCommands, Editor } from '@tiptap/core'\nimport type { Node as PMNode } from '@tiptap/pm/model'\nimport type { Component } from 'vue'\nimport type { BlockGroup, EditorMessages } from './locale'\n\n/** A menu entry (slash menu, \"Turn into\") contributed by a block definition. */\nexport interface BlockType {\n /** Stable id, also the key in `messages.blocks`. */\n id: string\n icon: Component\n /** Menu section: a built-in group or any custom label key. */\n group: BlockGroup | (string & {})\n /** Extra search terms (any language). Title and id are searched too. */\n keywords: string[]\n /** Markdown shortcut hint shown on the right of the menu row. */\n shortcut?: string\n /** Applies the block to the current (empty) line — used by the slash menu. */\n insert: (chain: ChainedCommands) => ChainedCommands\n /**\n * Converts a block (already cleared to paragraphs) into this type — used by \"Turn into\".\n * Blocks without it are not offered as a turn-into target.\n */\n turnInto?: (chain: ChainedCommands) => ChainedCommands\n /** Whether `node` is this block type, to mark the current type in menus. */\n matches?: (node: PMNode) => boolean\n}\n\n/** Menu items of the blocks loaded in this editor (see the `blocks` prop). */\nexport function enabledBlocks(editor: Editor): BlockType[] {\n return editor.storage.meiConfig?.items ?? []\n}\n\n/** Helper for `matches`: true when the node has this type name. */\nexport const isNode = (name: string) => (node: PMNode) => node.type.name === name\n\nexport function turnIntoBlocks(editor: Editor): BlockType[] {\n return enabledBlocks(editor).filter(b => b.turnInto)\n}\n\nexport const blockTitle = (messages: EditorMessages, block: BlockType) => messages.blocks[block.id]?.title ?? block.id\n\n/** Label of a menu section (custom groups fall back to their key). */\nexport const groupLabel = (messages: EditorMessages, group: string) => (messages.groups as Record<string, string>)[group] ?? group\n\nconst normalize = (s: string) => s.normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/đ/g, 'd').toLowerCase()\n\n/**\n * Filters blocks by query, best matches first:\n * exact term > a word starting with the query > substring anywhere.\n */\nexport function filterBlocks(blocks: BlockType[], query: string, messages: EditorMessages): BlockType[] {\n const q = normalize(query.trim())\n if (!q) return blocks\n\n const score = (b: BlockType) => {\n const terms = [blockTitle(messages, b), b.id, ...b.keywords].map(normalize)\n if (terms.includes(q)) return 3\n if (terms.some(t => t.split(/\\s+/).some(w => w.startsWith(q)))) return 2\n if (terms.some(t => t.includes(q))) return 1\n return 0\n }\n\n return blocks\n .map((b, i) => ({ b, i, s: score(b) }))\n .filter(x => x.s > 0)\n .sort((a, b) => b.s - a.s || a.i - b.i)\n .map(x => x.b)\n}\n","import { Extension } from '@tiptap/core'\nimport { Plugin, PluginKey, TextSelection } from '@tiptap/pm/state'\nimport { Decoration, DecorationSet } from '@tiptap/pm/view'\nimport { NodeRangeSelection } from '@tiptap/extension-node-range'\nimport { enabledBlocks } from '../block-items'\nimport {\n blockAt, type BlockRange, blocksIn, currentRange, deleteBlocks, duplicateBlocks,\n moveBlocks, rangeBetween, selectBlocks, turnBlocksInto,\n} from '../block-ops'\n\nexport interface BlockSelectionStorage {\n /** Set by the editor UI: opens the ⋮⋮ menu for a range (⌘/). */\n openMenu: ((range: BlockRange) => void) | null\n}\n\ndeclare module '@tiptap/core' {\n interface Storage {\n blockSelection: BlockSelectionStorage\n }\n}\n\n/** ⌘⌥0–8 → block type, like Notion. */\nexport const TURN_INTO_SHORTCUTS: Record<string, string> = {\n 0: 'paragraph',\n 1: 'heading1',\n 2: 'heading2',\n 3: 'heading3',\n 4: 'taskList',\n 5: 'bulletList',\n 6: 'orderedList',\n 7: 'toggle',\n 8: 'codeBlock',\n}\n\nexport const blockSelectionKey = new PluginKey('blockSelection')\n\n/**\n * Notion-style block selection and block shortcuts:\n * - Esc selects the current block; Esc again clears.\n * - Shift+click or dragging a text selection across blocks selects whole blocks.\n * - With blocks selected: ↑/↓ move the selection, Shift+↑/↓ extend it, Enter edits,\n * Backspace/Delete removes them, typing is ignored; ⌘C/⌘X copy/cut blocks.\n * - Anywhere: ⌘⇧↑/↓ move, ⌘D duplicate, ⌘⌥0–8 turn into, ⌘/ open the block menu.\n */\nexport const BlockSelection = Extension.create<object, BlockSelectionStorage>({\n name: 'blockSelection',\n priority: 1000,\n\n addStorage() {\n return { openMenu: null }\n },\n\n addKeyboardShortcuts() {\n const editor = this.editor\n const range = () => currentRange(editor.state)\n // Any open suggestion popup (slash, emoji, mention…) gets Esc first.\n const suggestionOpen = () => editor.state.plugins.some((p) => {\n const st = p.getState(editor.state) as { active?: boolean, query?: unknown } | undefined\n return !!st && typeof st === 'object' && st.active === true && 'query' in st\n })\n const withRange = (fn: (r: BlockRange) => unknown) => () => {\n const r = range()\n if (!r) return false\n fn(r)\n return true\n }\n\n const shortcuts: Record<string, () => boolean> = {\n 'Escape': () => {\n if (suggestionOpen()) return false\n const sel = editor.state.selection\n if (sel instanceof NodeRangeSelection) {\n // Second Esc: leave block mode.\n editor.view.dispatch(editor.state.tr.setSelection(TextSelection.near(editor.state.doc.resolve(sel.to - 1), -1)))\n editor.view.dom.blur()\n return true\n }\n const r = range()\n if (!r) return false\n selectBlocks(editor, r)\n return true\n },\n 'Mod-Shift-ArrowUp': () => !!range() && moveBlocks(editor, range()!, 'up'),\n 'Mod-Shift-ArrowDown': () => !!range() && moveBlocks(editor, range()!, 'down'),\n 'Mod-d': withRange(r => duplicateBlocks(editor, r)),\n 'Mod-/': withRange(r => this.storage.openMenu?.(r)),\n }\n for (const [key, id] of Object.entries(TURN_INTO_SHORTCUTS)) {\n shortcuts[`Mod-Alt-${key}`] = withRange((r) => {\n const block = enabledBlocks(editor).find(b => b.id === id)\n if (block) turnBlocksInto(editor, r, block)\n })\n }\n return shortcuts\n },\n\n addProseMirrorPlugins() {\n const editor = this.editor\n let dragging = false\n\n return [\n new Plugin({\n key: blockSelectionKey,\n props: {\n attributes: (state): Record<string, string> =>\n state.selection instanceof NodeRangeSelection ? { class: 'me-has-block-selection' } : {},\n\n decorations(state) {\n const sel = state.selection\n if (!(sel instanceof NodeRangeSelection)) return null\n const range = { from: sel.from, to: sel.to, depth: sel.depth ?? 0 }\n return DecorationSet.create(state.doc, blocksIn(state.doc, range).map(({ node, pos }) =>\n Decoration.node(pos, pos + node.nodeSize, { class: 'me-block-selected' })))\n },\n\n // Keys while blocks are selected.\n handleKeyDown(view, event) {\n const sel = view.state.selection\n if (!(sel instanceof NodeRangeSelection) || event.metaKey || event.ctrlKey || event.altKey) return false\n const range: BlockRange = { from: sel.from, to: sel.to, depth: sel.depth ?? 0 }\n const { doc } = view.state\n\n if (event.key === 'Backspace' || event.key === 'Delete') {\n deleteBlocks(editor, range)\n return true\n }\n if (event.key === 'Enter') {\n view.dispatch(view.state.tr.setSelection(TextSelection.near(doc.resolve(range.to - 1), -1)))\n return true\n }\n if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {\n const up = event.key === 'ArrowUp'\n // Shift moves the \"head\" block and keeps the anchor; plain arrows move a single block.\n const head = blockAt(doc.resolve(event.shiftKey ? sel.head : up ? sel.from + 1 : sel.to - 1))\n if (!head) return true\n const $edge = doc.resolve(up ? head.pos : head.pos + head.node.nodeSize)\n const sibling = up ? $edge.nodeBefore : $edge.nodeAfter\n if (!sibling) return true\n const siblingPos = up ? head.pos - sibling.nodeSize : head.pos + head.node.nodeSize\n if (!event.shiftKey) {\n selectBlocks(editor, { from: siblingPos, to: siblingPos + sibling.nodeSize, depth: range.depth })\n }\n else {\n view.dispatch(view.state.tr.setSelection(NodeRangeSelection.create(doc, sel.anchor, siblingPos + 1, range.depth)))\n }\n return true\n }\n // Printable keys would replace the blocks; Notion ignores them.\n return event.key.length === 1\n },\n\n handleTextInput: view => view.state.selection instanceof NodeRangeSelection,\n\n handleDOMEvents: {\n // Shift+click extends a block selection (or the cursor's block) to the clicked block.\n mousedown(view, event) {\n dragging = !event.shiftKey\n if (!event.shiftKey) return false\n const hit = view.posAtCoords({ left: event.clientX, top: event.clientY })\n if (!hit) return false\n const sel = view.state.selection\n const range = rangeBetween(view.state.doc, sel instanceof NodeRangeSelection ? sel.from + 1 : sel.anchor, hit.pos)\n if (!range || blocksIn(view.state.doc, range).length < 2) return false\n event.preventDefault()\n selectBlocks(editor, range)\n return true\n },\n },\n },\n\n // A text selection dragged across blocks becomes a block selection on mouseup.\n view: () => {\n const onMouseUp = () => {\n if (!dragging) return\n dragging = false\n const { state } = editor\n const sel = state.selection\n if (!(sel instanceof TextSelection) || sel.empty) return\n const a = blockAt(sel.$from)\n const b = blockAt(sel.$to)\n if (!a || !b || a.pos === b.pos) return\n const range = rangeBetween(state.doc, sel.anchor, sel.head)\n if (range) selectBlocks(editor, range)\n }\n document.addEventListener('mouseup', onMouseUp)\n return { destroy: () => document.removeEventListener('mouseup', onMouseUp) }\n },\n }),\n ]\n },\n})\n\n","/**\n * Which `data:` URLs a block may load: `image` (only `data:image/*`), `any`, or `none`.\n */\nexport type DataUrlPolicy = 'image' | 'any' | 'none'\n\n/**\n * URLs from document content (pasted, synced, imported) before they reach `src`, `href` or\n * `window.open`: http(s), `blob:`, URLs without a scheme and the allowed `data:` URLs. Anything\n * else — `javascript:`, `data:text/html`, `vbscript:`, URLs with control characters — gives `null`.\n *\n * URLs without a scheme take the page's: paths (`/api/v1/files/<id>`, `a.png`) are same-origin,\n * while `//cdn.example.com/a.png` (and `\\\\host`, `/\\host`, which browsers read the same way) are\n * http(s) URLs on another host — as safe as any https URL, but not same-origin. Use `isSameOrigin`\n * when that matters.\n */\nexport function safeUrl(src: unknown, data: DataUrlPolicy = 'none'): string | null {\n if (typeof src !== 'string') return null\n const url = src.trim()\n // Browsers drop tabs / newlines inside URLs (\"java\\tscript:\"), so refuse any control character.\n // eslint-disable-next-line no-control-regex\n if (!url || /[\\u0000-\\u001F\\u007F]/.test(url)) return null\n const scheme = /^([a-z][a-z\\d+.-]*):/i.exec(url)?.[1]?.toLowerCase()\n if (!scheme) return url // relative or protocol-relative: same scheme as the page\n if (scheme === 'http' || scheme === 'https' || scheme === 'blob') return url\n if (scheme === 'data') {\n if (data === 'any') return url\n if (data === 'image' && /^data:image\\/[a-z\\d.+-]+[;,]/i.test(url)) return url\n }\n return null\n}\n\n/** True when `url` (resolved against the page) is on the page's origin. */\nexport function isSameOrigin(url: string, base: string = globalThis.location?.href ?? 'http://localhost/'): boolean {\n try {\n return new URL(url, base).origin === new URL(base).origin\n }\n catch {\n return false\n }\n}\n\n/** True when `url` (resolved against the page) is an http(s) URL. */\nexport function isWebUrl(url: string, base: string = globalThis.location?.href ?? 'http://localhost/'): boolean {\n try {\n return /^https?:$/.test(new URL(url, base).protocol)\n }\n catch {\n return false\n }\n}\n","import { Extension, type JSONContent } from '@tiptap/core'\nimport type { Schema } from '@tiptap/pm/model'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\nimport { safeUrl } from '../safe-url'\n\n/**\n * Pasting Markdown as plain text (from a chat, a README, an LLM answer…) gives blocks instead of\n * one paragraph per line (KS-BUG-11): headings, bullet / numbered / task lists (nested by\n * indentation), quotes, fenced code, dividers, and inline bold, italic, strike, code and links\n * (bare http(s) URLs too). Tiptap's paste rules are not run on the result: they would undo\n * escapes (`\\\\*x\\\\*`) and the word rules (`__init__.py`).\n *\n * Converted only when the text clearly is Markdown (`looksLikeMarkdown`), at most\n * `MARKDOWN_PASTE_MAX` characters, never inside a code block, never for \"paste as plain text\"\n * (Shift+Mod+V) and never when the clipboard also has HTML. The parsers are linear in the input\n * (no backtracking regexes, bounded nesting), so a pasted text can't freeze the tab.\n */\n\n/** Longer plain-text pastes are never converted. */\nexport const MARKDOWN_PASTE_MAX = 100 * 1024\n/** Deeper quote / list / emphasis nesting is flattened (or kept as text) at this depth. */\nconst MAX_DEPTH = 8\n\n// ---------------------------------------------------------------------------------------------\n// Lines\n\ninterface ListLine { indent: number, ordered: boolean, start: number, task: boolean | null, text: string }\n\ntype Line =\n | { kind: 'blank' }\n | { kind: 'fence', marker: string, info: string }\n | { kind: 'heading', level: number, text: string }\n | { kind: 'hr' }\n | { kind: 'quote' }\n | { kind: 'list', item: ListLine }\n | { kind: 'text' }\n\nconst isSpace = (c: string | undefined) => c === ' ' || c === '\\t'\nconst isDigit = (c: string | undefined) => c !== undefined && c >= '0' && c <= '9'\n\n/** Indentation width (tab = 4) and the index of the first other character. */\nfunction indentOf(line: string): [indent: number, at: number] {\n let indent = 0\n let at = 0\n while (at < line.length && isSpace(line[at])) indent += line[at++] === '\\t' ? 4 : 1\n return [indent, at]\n}\n\n/** Heading text without the optional closing `#`s (`## Title ##`). */\nfunction headingText(rest: string): string {\n let end = rest.length\n while (end > 0 && isSpace(rest[end - 1])) end--\n let hashes = end\n while (hashes > 0 && rest[hashes - 1] === '#') hashes--\n if (hashes < end && (hashes === 0 || isSpace(rest[hashes - 1]))) {\n end = hashes\n while (end > 0 && isSpace(rest[end - 1])) end--\n }\n return rest.slice(0, end)\n}\n\nfunction listItem(line: string, indent: number, at: number): ListLine | null {\n let i = at\n let ordered = false\n let start = 1\n if (line[i] === '-' || line[i] === '*' || line[i] === '+') {\n i++\n }\n else {\n const digits = i\n while (i - digits < 4 && isDigit(line[i])) i++\n // At most 3 digits: \"2024. A great year\" stays a sentence.\n if (i === digits || i - digits > 3 || (line[i] !== '.' && line[i] !== ')')) return null\n ordered = true\n start = Number(line.slice(digits, i))\n i++\n }\n if (!isSpace(line[i])) return null\n while (isSpace(line[i])) i++\n let task: boolean | null = null\n if (!ordered && line[i] === '[' && line[i + 2] === ']' && isSpace(line[i + 3]) && ' xX'.includes(line[i + 1] ?? '-')) {\n task = line[i + 1] !== ' '\n i += 4\n while (isSpace(line[i])) i++\n }\n const text = line.slice(i)\n return text.trim() ? { indent, ordered, start, task, text } : null\n}\n\nfunction classify(line: string): Line {\n const [indent, at] = indentOf(line)\n if (at === line.length) return { kind: 'blank' }\n const c = line[at]!\n if (indent < 4) {\n if ((c === '`' || c === '~') && line.startsWith(c.repeat(3), at)) {\n let end = at\n while (line[end] === c) end++\n const info = line.slice(end).trim()\n const space = info.search(/[ \\t]/)\n return { kind: 'fence', marker: line.slice(at, end), info: space === -1 ? info : info.slice(0, space) }\n }\n if (c === '#') {\n let end = at\n while (line[end] === '#' && end - at < 7) end++\n const level = end - at\n if (level <= 6 && isSpace(line[end])) {\n const text = headingText(line.slice(end + 1))\n if (text.trim()) return { kind: 'heading', level, text: text.trim() }\n }\n }\n if (c === '-' || c === '*' || c === '_') {\n let n = 0\n let only = true\n for (let i = at; i < line.length && only; i++) {\n if (line[i] === c) n++\n else if (!isSpace(line[i])) only = false\n }\n if (only && n >= 3) return { kind: 'hr' }\n }\n if (c === '>') return { kind: 'quote' }\n }\n const item = listItem(line, indent, at)\n return item ? { kind: 'list', item } : { kind: 'text' }\n}\n\nconst splitLines = (text: string) => text.replace(/\\r\\n?/g, '\\n').split('\\n')\n\nconst closesFence = (line: Line, open: string) => line.kind === 'fence' && !line.info && line.marker[0] === open[0] && line.marker.length >= open.length\n\n/**\n * True when `text` clearly is Markdown: a heading, a closed code fence, a task item, or two list\n * items of the same kind in a row. A lone \"- Alice\" signature or \"1) apples\" is not enough.\n */\nexport function looksLikeMarkdown(text: string): boolean {\n if (text.length > MARKDOWN_PASTE_MAX) return false\n let openFence: string | null = null\n let previousList: boolean | null = null // previous non-blank line was a list item: ordered?\n for (const raw of splitLines(text)) {\n const line = classify(raw)\n if (openFence !== null) {\n if (closesFence(line, openFence)) return true\n continue\n }\n if (line.kind === 'blank') continue\n if (line.kind === 'heading') return true\n if (line.kind === 'fence') {\n openFence = line.marker\n continue\n }\n if (line.kind === 'list') {\n if (line.item.task !== null || previousList === line.item.ordered) return true\n previousList = line.item.ordered\n continue\n }\n previousList = null\n }\n return false\n}\n\n// ---------------------------------------------------------------------------------------------\n// Inline\n\ntype Mark = { type: string, attrs?: Record<string, unknown> }\nconst OPEN_AFTER = '([{\\'\"'\nconst CLOSE_BEFORE = '.,;:!?)]}\\'\"'\nconst ESCAPABLE = '\\\\`*_~[]()#>!-'\nconst isWs = (c: string | undefined) => c === undefined || c === ' ' || c === '\\t' || c === '\\n' || c === ' '\nconst isWord = (c: string | undefined) => c !== undefined && /[\\p{L}\\p{N}_]/u.test(c)\nconst EMPHASIS: [delimiter: string, mark: string][] = [['**', 'bold'], ['__', 'bold'], ['~~', 'strike'], ['*', 'italic'], ['_', 'italic']]\n\n/**\n * Next match of `needle` at or after `from`, optionally passing `valid`. Queries for one key come\n * in increasing `from` order, so the last answer is reused: the whole scan stays linear even\n * with thousands of unmatched `[`, `` ` `` or `*`.\n */\nfunction finder(text: string) {\n const last = new Map<string, number>()\n return (key: string, needle: string, from: number, valid?: (i: number) => boolean): number => {\n const cached = last.get(key)\n if (cached !== undefined && (cached === -1 || cached >= from)) return cached\n let i = text.indexOf(needle, from)\n while (i !== -1 && valid && !valid(i)) i = text.indexOf(needle, i + 1)\n last.set(key, i)\n return i\n }\n}\n\n/** End of a bare URL starting at `start`: up to whitespace, without trailing punctuation. */\nfunction urlEnd(text: string, start: number): number {\n let end = start\n while (end < text.length && !isWs(text[end]) && text[end] !== '<') end++\n while (end > start && CLOSE_BEFORE.includes(text[end - 1]!)) {\n // Keep a closing parenthesis that belongs to the URL (`…/Foo_(bar)`).\n if (text[end - 1] === ')' && text.slice(start, end).split('(').length > text.slice(start, end).split(')').length - 1) break\n end--\n }\n return end\n}\n\n/**\n * Inline Markdown → text nodes with marks (bold, italic, strike, code, link), bare http(s) URLs\n * linked. Linear time; emphasis nested deeper than MAX_DEPTH stays text.\n */\nexport function parseInline(text: string, marks: Mark[] = [], inLink = false, depth = 0): JSONContent[] {\n const out: JSONContent[] = []\n let buf = ''\n const flush = () => {\n if (!buf) return\n const last = out.at(-1)\n if (last?.text !== undefined && JSON.stringify(last.marks ?? []) === JSON.stringify(marks)) last.text += buf\n else out.push(marks.length ? { type: 'text', text: buf, marks } : { type: 'text', text: buf })\n buf = ''\n }\n const next = finder(text)\n // An emphasis closer follows a non-space and ends a word: `__init__.py`, `2*3*4` and\n // `snake_case` stay text.\n const closer = (len: number) => (i: number) => !isWs(text[i - 1]) && text[i - 1] !== text[i]\n && (isWs(text[i + len]) || (CLOSE_BEFORE.includes(text[i + len]!) && !isWord(text[i + len + 1])))\n\n let i = 0\n while (i < text.length) {\n const c = text[i]!\n if (c === '\\\\' && ESCAPABLE.includes(text[i + 1] ?? '\\0')) {\n buf += text[i + 1]\n i += 2\n continue\n }\n if (c === '`') {\n const end = next('`', '`', i + 1)\n if (end > i + 1) {\n flush()\n out.push({ type: 'text', text: text.slice(i + 1, end), marks: [...marks, { type: 'code' }] })\n i = end + 1\n continue\n }\n }\n if (c === '[' && !inLink) {\n const close = next(']', ']', i + 1)\n if (close > i + 1 && text[close + 1] === '(') {\n const paren = next(')', ')', close + 2)\n if (paren !== -1) {\n const inside = text.slice(close + 2, paren).trim()\n const space = inside.search(/\\s/)\n const url = space === -1 ? inside : inside.slice(0, space)\n const title = space === -1 ? '' : inside.slice(space).trim()\n if (url && (!title || (title.length > 1 && title[0] === '\"' && title.at(-1) === '\"' && !title.slice(1, -1).includes('\"')))) {\n flush()\n const href = safeUrl(url)\n out.push(...parseInline(text.slice(i + 1, close), href ? [...marks, { type: 'link', attrs: { href } }] : marks, true, depth + 1))\n i = paren + 1\n continue\n }\n }\n }\n }\n // Bare URLs become links here (paste rules aren't run: they'd undo escapes and word rules).\n if (c === 'h' && !inLink && (i === 0 || !isWord(text[i - 1])) && (text.startsWith('https://', i) || text.startsWith('http://', i))) {\n const end = urlEnd(text, i)\n const url = text.slice(i, end)\n const href = /^https?:\\/\\/[^/?#\\s]/.test(url) ? safeUrl(url) : null\n if (href) {\n flush()\n out.push({ type: 'text', text: url, marks: [...marks, { type: 'link', attrs: { href } }] })\n i = end\n continue\n }\n }\n if (c === '*' || c === '_' || c === '~') {\n const delimiter = depth < MAX_DEPTH ? EMPHASIS.find(([d]) => text.startsWith(d, i)) : undefined\n // Opens at a word start, before a non-space.\n if (delimiter && (i === 0 || isWs(text[i - 1]) || OPEN_AFTER.includes(text[i - 1]!)) && !isWs(text[i + delimiter[0].length])) {\n const [d, type] = delimiter\n const end = next(`em${d}`, d, i + d.length + 1, closer(d.length))\n if (end !== -1) {\n flush()\n // `*_*x*_*`: a mark already applied isn't added twice (ProseMirror refuses that).\n const inner = marks.some(m => m.type === type) ? marks : [...marks, { type }]\n out.push(...parseInline(text.slice(i + d.length, end), inner, inLink, depth + 1))\n i = end + d.length\n continue\n }\n }\n // Not a delimiter here: keep the whole run as text.\n let j = i\n while (text[j] === c) j++\n buf += text.slice(i, j)\n i = j\n continue\n }\n buf += c\n i++\n }\n flush()\n return out\n}\n\n// ---------------------------------------------------------------------------------------------\n// Blocks\n\nconst paragraph = (text: string): JSONContent => {\n const content = parseInline(text)\n return content.length ? { type: 'paragraph', content } : { type: 'paragraph' }\n}\n\n/** Nested lists from consecutive list items, without recursion (nesting capped at MAX_DEPTH). */\nfunction buildList(items: ListLine[]): JSONContent[] {\n const root: JSONContent[] = []\n const stack: { indent: number, container: JSONContent[], list: JSONContent }[] = []\n for (const line of items) {\n while (stack.length && line.indent < stack.at(-1)!.indent) stack.pop()\n const type = line.task !== null ? 'taskList' : line.ordered ? 'orderedList' : 'bulletList'\n let top = stack.at(-1)\n if (top && line.indent > top.indent && stack.length < MAX_DEPTH) {\n const parent = top.list.content!.at(-1)!\n const list: JSONContent = { type, content: [] }\n parent.content!.push(list)\n top = { indent: line.indent, container: parent.content!, list }\n stack.push(top)\n }\n if (!top) {\n const list: JSONContent = { type, content: [] }\n root.push(list)\n top = { indent: line.indent, container: root, list }\n stack.push(top)\n }\n if (top.list.type !== type) {\n top.list = { type, content: [] }\n top.container.push(top.list)\n }\n if (type === 'orderedList' && !top.list.content!.length && line.start !== 1) top.list.attrs = { start: line.start }\n const item: JSONContent = { type: type === 'taskList' ? 'taskItem' : 'listItem', content: [paragraph(line.text)] }\n if (type === 'taskList') item.attrs = { checked: !!line.task }\n top.list.content!.push(item)\n }\n return root\n}\n\n/** Removes one quote marker (`> `), or all of them (`>>> x` → `x`). */\nfunction unquote(line: string, all: boolean): string {\n let at = indentOf(line)[1]\n do {\n at++ // the '>'\n if (line[at] === ' ') at++\n if (!all) break\n while (isSpace(line[at])) at++\n } while (line[at] === '>')\n return line.slice(at)\n}\n\n/** Block Markdown → Tiptap JSON blocks (types are mapped to the schema by `fitToSchema`). */\nexport function markdownToBlocks(markdown: string, depth = 0): JSONContent[] {\n const lines = splitLines(markdown)\n const kinds = lines.map(classify)\n const blocks: JSONContent[] = []\n for (let i = 0; i < lines.length;) {\n const kind = kinds[i]!\n if (kind.kind === 'fence') {\n const body: string[] = []\n i++\n while (i < lines.length && !closesFence(kinds[i]!, kind.marker)) body.push(lines[i++]!)\n i++ // closing fence\n const text = body.join('\\n')\n blocks.push({ type: 'codeBlock', attrs: { language: /^[\\w+#.-]{1,32}$/.test(kind.info) ? kind.info : null }, content: text ? [{ type: 'text', text }] : [] })\n continue\n }\n if (kind.kind === 'heading') {\n const content = parseInline(kind.text)\n blocks.push({ type: 'heading', attrs: { level: Math.min(3, kind.level) }, ...(content.length ? { content } : {}) })\n i++\n continue\n }\n if (kind.kind === 'hr') {\n blocks.push({ type: 'horizontalRule' })\n i++\n continue\n }\n if (kind.kind === 'quote') {\n const quoted: string[] = []\n const flatten = depth + 1 >= MAX_DEPTH\n while (i < lines.length && kinds[i]!.kind === 'quote') quoted.push(unquote(lines[i++]!, flatten))\n const content = flatten ? quoted.filter(l => l.trim()).map(l => paragraph(l.trim())) : markdownToBlocks(quoted.join('\\n'), depth + 1)\n blocks.push({ type: 'blockquote', content: content.length ? content : [{ type: 'paragraph' }] })\n continue\n }\n if (kind.kind === 'list') {\n // A lone numbered line not starting at 1 (\"7) and so on\") stays a paragraph.\n const following = kinds[i + 1]\n const lone = kind.item.ordered && kind.item.start !== 1 && !(following?.kind === 'list' && following.item.ordered)\n if (!lone) {\n const items: ListLine[] = []\n while (i < lines.length) {\n const k = kinds[i]!\n if (k.kind === 'list') items.push(k.item)\n else if (k.kind === 'blank' && items.length && kinds[i + 1]?.kind === 'list') { /* loose list */ }\n else if (k.kind === 'text' && items.length && isSpace(lines[i]![0])) items.at(-1)!.text += ` ${lines[i]!.trim()}`\n else break\n i++\n }\n blocks.push(...buildList(items))\n continue\n }\n }\n // Text: one paragraph per line, like a plain-text paste (line breaks are kept).\n if (kind.kind !== 'blank') blocks.push(paragraph(lines[i]!.trim()))\n i++\n }\n return blocks\n}\n\n/** Replaces node / mark types the editor doesn't have (e.g. no task lists loaded) with plain ones. */\nexport function fitToSchema(node: JSONContent, schema: Schema): JSONContent {\n const map: Record<string, string> = { taskList: 'bulletList', taskItem: 'listItem' }\n let type = node.type!\n if (type !== 'text' && !schema.nodes[type]) type = schema.nodes[map[type] ?? ''] ? map[type]! : 'paragraph'\n const out: JSONContent = { ...node, type }\n if (type !== node.type) delete out.attrs\n if (type === 'paragraph' && node.type !== 'paragraph' && node.content?.some(c => c.type !== 'text')) {\n // A block we can't represent: keep its text.\n out.content = [{ type: 'text', text: textOf(node) }].filter(t => t.text)\n return out\n }\n if (node.marks) out.marks = node.marks.filter(m => schema.marks[m.type])\n if (node.content) out.content = node.content.map(c => fitToSchema(c, schema))\n return out\n}\n\n/** All text in a node, without recursion. */\nfunction textOf(node: JSONContent): string {\n const parts: string[] = []\n const stack: JSONContent[] = [node]\n while (stack.length) {\n const n = stack.pop()!\n if (n.text) parts.push(n.text)\n if (n.content) for (let i = n.content.length - 1; i >= 0; i--) stack.push(n.content[i]!)\n }\n return parts.join(' ')\n}\n\nexport const MarkdownPaste = Extension.create({\n name: 'markdownPaste',\n addProseMirrorPlugins() {\n const editor = this.editor\n return [new Plugin({\n key: new PluginKey('markdownPaste'),\n props: {\n handlePaste: (view, event) => {\n const data = event.clipboardData\n const text = data?.getData('text/plain')\n if (!text || data!.getData('text/html')) return false\n // Shift+Mod+V, \"paste as plain text\". Same test as ProseMirror's own plain paste:\n // Shift+Insert (key code 45) is a normal paste.\n const input = (view as unknown as { input?: { shiftKey?: boolean, lastKeyCode?: number | null } }).input\n if (input?.shiftKey && input.lastKeyCode !== 45) return false\n if (view.state.selection.$from.parent.type.spec.code) return false\n let blocks: JSONContent[]\n try {\n if (!looksLikeMarkdown(text)) return false\n blocks = markdownToBlocks(text).map(b => fitToSchema(b, view.state.schema))\n }\n catch (error) {\n // Whatever goes wrong, the paste still happens, as plain text.\n console.warn('[MeiEditor] Markdown paste failed, pasting as plain text:', error)\n return false\n }\n if (!blocks.length) return false\n return editor.commands.insertContent(blocks)\n },\n },\n })]\n },\n})\n","import { type Editor, Extension } from '@tiptap/core'\nimport type { Node as PMNode } from '@tiptap/pm/model'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\nimport { Decoration, DecorationSet } from '@tiptap/pm/view'\n\nexport interface PlaceholderOptions {\n /** Hint for an empty text block, e.g. \"Type '/' for commands\". */\n placeholder: string | ((props: { editor: Editor, node: PMNode, pos: number }) => string)\n}\n\nexport const placeholderPluginKey = new PluginKey('mePlaceholder')\n\n/**\n * \"Type '/'…\" hint on the empty text block holding the cursor, at any depth (inside\n * lists, callouts, toggles, columns). Renders `class=\"is-empty\"` and `data-placeholder`;\n * `is-editor-empty` is added when the whole document is empty.\n *\n * Replaces Tiptap's Placeholder: with `includeChildren` it keeps an incremental\n * decoration set whose rescan ranges are off by one, so hints stayed on blocks the\n * cursor had left (moving up through empty lines showed one on each). Only the\n * cursor's block can show a hint, so it's computed from the selection on every render:\n * no stored state to go stale, and O(1) whatever the document size.\n */\nexport const Placeholder = Extension.create<PlaceholderOptions>({\n name: 'placeholder',\n\n addOptions: () => ({ placeholder: '' }),\n\n addProseMirrorPlugins() {\n const { editor, options } = this\n return [new Plugin({\n key: placeholderPluginKey,\n props: {\n decorations: ({ doc, selection }) => {\n if (!editor.isEditable) return null\n const { $anchor } = selection\n const node = $anchor.parent\n if ($anchor.depth === 0 || !node.isTextblock || node.content.size > 0) return null\n const pos = $anchor.before()\n const text = typeof options.placeholder === 'function' ? options.placeholder({ editor, node, pos }) : options.placeholder\n return DecorationSet.create(doc, [Decoration.node(pos, pos + node.nodeSize, {\n 'class': editor.isEmpty ? 'is-empty is-editor-empty' : 'is-empty',\n 'data-placeholder': text,\n })])\n },\n },\n })]\n },\n})\n","import { Extension, Mark, mergeAttributes } from '@tiptap/core'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n textColor: {\n /** Sets a palette color by name (`'red'`, `'blue'`…); `null`/`'default'` removes it. */\n setTextColor: (color: string | null) => ReturnType\n }\n bgColor: {\n setBgColor: (color: string | null) => ReturnType\n }\n }\n}\n\nconst isDefault = (color: string | null) => !color || color === 'default'\n\n/** Text color stored by palette name, so themes and dark mode can restyle it. */\nexport const TextColor = Mark.create({\n name: 'textColor',\n addAttributes() {\n return {\n color: {\n default: null,\n parseHTML: el => el.getAttribute('data-text-color'),\n renderHTML: attrs => ({ 'data-text-color': attrs.color }),\n },\n }\n },\n parseHTML() {\n return [{ tag: 'span[data-text-color]' }]\n },\n renderHTML({ HTMLAttributes }) {\n return ['span', mergeAttributes(HTMLAttributes), 0]\n },\n addCommands() {\n return {\n setTextColor: color => ({ commands }) =>\n isDefault(color) ? commands.unsetMark(this.name) : commands.setMark(this.name, { color }),\n }\n },\n})\n\n/** Background (highlight) color stored by palette name. */\nexport const BgColor = Mark.create({\n name: 'bgColor',\n addAttributes() {\n return {\n color: {\n default: null,\n parseHTML: el => el.getAttribute('data-bg-color'),\n renderHTML: attrs => ({ 'data-bg-color': attrs.color }),\n },\n }\n },\n parseHTML() {\n return [{ tag: 'mark[data-bg-color]' }]\n },\n renderHTML({ HTMLAttributes }) {\n return ['mark', mergeAttributes(HTMLAttributes), 0]\n },\n addCommands() {\n return {\n setBgColor: color => ({ commands }) =>\n isDefault(color) ? commands.unsetMark(this.name) : commands.setMark(this.name, { color }),\n }\n },\n})\n\n/** Blocks that take a whole-block color (Notion's block menu / \"/red\" colors). */\nexport const COLORABLE_BLOCKS = ['paragraph', 'heading', 'blockquote', 'bulletList', 'orderedList', 'taskList', 'listItem', 'taskItem', 'details']\n\n/**\n * Whole-block text/background color, stored by palette name as `blockColor` / `blockBg`.\n * Renders the same `data-text-color` / `data-bg-color` attributes as the marks, so one\n * set of palette rules styles both. New blocks split off with Enter start uncolored.\n */\nexport const BlockColor = Extension.create({\n name: 'blockColor',\n addGlobalAttributes() {\n const attr = (data: string) => ({\n default: null,\n keepOnSplit: false,\n parseHTML: (el: HTMLElement) => (el.tagName === 'SPAN' || el.tagName === 'MARK' ? null : el.getAttribute(data)),\n })\n return [{\n types: COLORABLE_BLOCKS,\n attributes: {\n blockColor: { ...attr('data-text-color'), renderHTML: a => (a.blockColor ? { 'data-text-color': a.blockColor } : {}) },\n blockBg: { ...attr('data-bg-color'), renderHTML: a => (a.blockBg ? { 'data-bg-color': a.blockBg } : {}) },\n },\n }]\n },\n})\n","import type { Editor } from '@tiptap/core'\nimport { computed } from 'vue'\n\n/**\n * Theme scope attributes (mode class + overrides id) for elements rendered outside\n * the editor root, e.g. popovers teleported to <body>. Use with `v-bind`.\n */\nexport function useScope(editor: () => Editor | undefined) {\n return computed(() => editor()?.storage.meiConfig?.scope ?? { 'class': ['me-scope'], 'data-me-id': '' })\n}\n","/**\n * For menus that open at the caret (slash, mentions, emoji): hovering a row may select it only\n * after the pointer really moved. When a menu opens — or its rows change while typing — under a\n * resting pointer, the browser fires mouseenter (and Chrome a synthetic mousemove) on the row\n * that slid under it; selecting that row made Enter insert the wrong block (KS-BUG-3).\n *\n * Returns a handler for `mousemove`: true when the pointer is at a new position since the last\n * event this menu saw (the first event only records the position).\n */\nexport function usePointerMoved() {\n let last: { x: number, y: number } | null = null\n return (event: MouseEvent): boolean => {\n const moved = last !== null && (last.x !== event.screenX || last.y !== event.screenY)\n last = { x: event.screenX, y: event.screenY }\n return moved\n }\n}\n","<script setup lang=\"ts\">\nimport type { Editor } from '@tiptap/core'\nimport { computed, nextTick, ref, watch } from 'vue'\nimport { useScope } from '../composables/useScope'\nimport type { SlashItem } from '../slash-items'\nimport { usePointerMoved } from '../composables/usePointerMoved'\n\nconst props = defineProps<{\n editor: Editor\n items: SlashItem[]\n query: string\n command: (item: SlashItem) => void\n}>()\n\nconst selected = ref(0)\nconst listEl = ref<HTMLElement | null>(null)\nconst m = computed(() => props.editor.storage.meiConfig.messages)\nconst scope = useScope(() => props.editor)\n\n// While searching, show one ranked list; otherwise keep the sections (recent, groups, colors).\nconst groups = computed(() => {\n if (props.query.trim()) return [[m.value.slash.results, props.items.map((item, index) => ({ item, index }))] as const]\n const map = new Map<string, { item: SlashItem, index: number }[]>()\n props.items.forEach((item, index) => {\n if (!map.has(item.group)) map.set(item.group, [])\n map.get(item.group)!.push({ item, index })\n })\n return [...map.entries()]\n})\n\nwatch(() => props.items, () => (selected.value = 0))\nwatch(selected, async (i) => {\n await nextTick()\n listEl.value?.querySelector(`[data-index=\"${i}\"]`)?.scrollIntoView({ block: 'nearest' })\n})\n\nfunction select(index: number) {\n const item = props.items[index]\n if (item) props.command(item)\n}\n\nfunction onKeyDown(event: KeyboardEvent) {\n const n = props.items.length\n if (!n) return false\n if (event.key === 'ArrowDown') {\n selected.value = (selected.value + 1) % n\n return true\n }\n if (event.key === 'ArrowUp') {\n selected.value = (selected.value + n - 1) % n\n return true\n }\n if (event.key === 'Enter' || event.key === 'Tab') {\n select(selected.value)\n return true\n }\n return false\n}\n\ndefineExpose({ onKeyDown })\n\n// Hover selects a row only after a real pointer move (KS-BUG-3).\nconst pointerMoved = usePointerMoved()\n</script>\n\n<template>\n <div ref=\"listEl\" v-bind=\"scope\" class=\"me-popover me-menu\">\n <template v-if=\"items.length\">\n <div v-for=\"[group, entries] in groups\" :key=\"group\">\n <div class=\"me-menu-label\">\n {{ group }}\n </div>\n <button\n v-for=\"{ item, index } in entries\"\n :key=\"item.key\"\n type=\"button\"\n :data-index=\"index\"\n class=\"me-menu-item\"\n :class=\"{ 'is-active': index === selected }\"\n @mousemove=\"pointerMoved($event) && (selected = index)\"\n @mousedown.prevent=\"select(index)\"\n >\n <span v-if=\"item.swatch\" class=\"me-menu-icon\" :class=\"item.swatch.kind === 'text' ? 'me-swatch--text' : 'me-swatch--bg'\" :data-color=\"item.swatch.color\">A</span>\n <span v-else class=\"me-menu-icon\"><component :is=\"item.icon\" /></span>\n <span class=\"me-menu-text\">\n <span class=\"me-menu-title\">{{ item.title }}</span>\n <span v-if=\"item.description\" class=\"me-menu-desc\">{{ item.description }}</span>\n </span>\n <span v-if=\"item.shortcut\" class=\"me-menu-shortcut\">{{ item.shortcut }}</span>\n </button>\n </div>\n </template>\n <div v-else class=\"me-menu-empty\">\n {{ m.slash.empty }}\n </div>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport type { Editor } from '@tiptap/core'\nimport { computed, nextTick, ref, watch } from 'vue'\nimport { useScope } from '../composables/useScope'\nimport type { SlashItem } from '../slash-items'\nimport { usePointerMoved } from '../composables/usePointerMoved'\n\nconst props = defineProps<{\n editor: Editor\n items: SlashItem[]\n query: string\n command: (item: SlashItem) => void\n}>()\n\nconst selected = ref(0)\nconst listEl = ref<HTMLElement | null>(null)\nconst m = computed(() => props.editor.storage.meiConfig.messages)\nconst scope = useScope(() => props.editor)\n\n// While searching, show one ranked list; otherwise keep the sections (recent, groups, colors).\nconst groups = computed(() => {\n if (props.query.trim()) return [[m.value.slash.results, props.items.map((item, index) => ({ item, index }))] as const]\n const map = new Map<string, { item: SlashItem, index: number }[]>()\n props.items.forEach((item, index) => {\n if (!map.has(item.group)) map.set(item.group, [])\n map.get(item.group)!.push({ item, index })\n })\n return [...map.entries()]\n})\n\nwatch(() => props.items, () => (selected.value = 0))\nwatch(selected, async (i) => {\n await nextTick()\n listEl.value?.querySelector(`[data-index=\"${i}\"]`)?.scrollIntoView({ block: 'nearest' })\n})\n\nfunction select(index: number) {\n const item = props.items[index]\n if (item) props.command(item)\n}\n\nfunction onKeyDown(event: KeyboardEvent) {\n const n = props.items.length\n if (!n) return false\n if (event.key === 'ArrowDown') {\n selected.value = (selected.value + 1) % n\n return true\n }\n if (event.key === 'ArrowUp') {\n selected.value = (selected.value + n - 1) % n\n return true\n }\n if (event.key === 'Enter' || event.key === 'Tab') {\n select(selected.value)\n return true\n }\n return false\n}\n\ndefineExpose({ onKeyDown })\n\n// Hover selects a row only after a real pointer move (KS-BUG-3).\nconst pointerMoved = usePointerMoved()\n</script>\n\n<template>\n <div ref=\"listEl\" v-bind=\"scope\" class=\"me-popover me-menu\">\n <template v-if=\"items.length\">\n <div v-for=\"[group, entries] in groups\" :key=\"group\">\n <div class=\"me-menu-label\">\n {{ group }}\n </div>\n <button\n v-for=\"{ item, index } in entries\"\n :key=\"item.key\"\n type=\"button\"\n :data-index=\"index\"\n class=\"me-menu-item\"\n :class=\"{ 'is-active': index === selected }\"\n @mousemove=\"pointerMoved($event) && (selected = index)\"\n @mousedown.prevent=\"select(index)\"\n >\n <span v-if=\"item.swatch\" class=\"me-menu-icon\" :class=\"item.swatch.kind === 'text' ? 'me-swatch--text' : 'me-swatch--bg'\" :data-color=\"item.swatch.color\">A</span>\n <span v-else class=\"me-menu-icon\"><component :is=\"item.icon\" /></span>\n <span class=\"me-menu-text\">\n <span class=\"me-menu-title\">{{ item.title }}</span>\n <span v-if=\"item.description\" class=\"me-menu-desc\">{{ item.description }}</span>\n </span>\n <span v-if=\"item.shortcut\" class=\"me-menu-shortcut\">{{ item.shortcut }}</span>\n </button>\n </div>\n </template>\n <div v-else class=\"me-menu-empty\">\n {{ m.slash.empty }}\n </div>\n </div>\n</template>\n","import { ref } from 'vue'\nimport type { ColorName } from './colors'\n\n/** Recently used colors and blocks, shared by all editors and kept in localStorage. */\nexport interface RecentColor { kind: 'text' | 'bg', color: ColorName }\n\nconst KEY = 'mei-editor:recent'\nconst MAX = 5\n\nfunction load(): { colors: RecentColor[], blocks: string[] } {\n try {\n const raw = JSON.parse(localStorage.getItem(KEY) ?? '{}')\n return { colors: Array.isArray(raw.colors) ? raw.colors : [], blocks: Array.isArray(raw.blocks) ? raw.blocks : [] }\n }\n catch {\n return { colors: [], blocks: [] }\n }\n}\n\nexport const recent = ref(typeof window === 'undefined' ? { colors: [], blocks: [] } : load())\n\nfunction save() {\n try {\n localStorage.setItem(KEY, JSON.stringify(recent.value))\n }\n catch {}\n}\n\nexport function pushRecentColor(entry: RecentColor) {\n const rest = recent.value.colors.filter(c => !(c.kind === entry.kind && c.color === entry.color))\n recent.value = { ...recent.value, colors: [entry, ...rest].slice(0, MAX) }\n save()\n}\n\nexport function pushRecentBlock(id: string) {\n recent.value = { ...recent.value, blocks: [id, ...recent.value.blocks.filter(b => b !== id)].slice(0, MAX) }\n save()\n}\n","import type { Editor } from '@tiptap/core'\nimport type { ResolvedPos } from '@tiptap/pm/model'\nimport type { Component } from 'vue'\nimport { type BlockType, blockTitle, enabledBlocks, groupLabel } from './block-items'\nimport { type BlockRange, colorBlocks, currentRange } from './block-ops'\nimport { PALETTE_NAMES } from './theme/tokens'\nimport { pushRecentBlock, pushRecentColor, recent } from './recent'\n\n/** One row of the slash menu: a block type or a color command. */\nexport interface SlashItem {\n key: string\n /** Section label shown above the row. */\n group: string\n title: string\n description?: string\n icon?: Component\n swatch?: { kind: 'text' | 'bg', color: string }\n shortcut?: string\n terms: string[]\n /** Runs after the `/query` text has been removed. */\n apply: (editor: Editor) => void\n}\n\nconst normalize = (s: string) => s.normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/đ/g, 'd').toLowerCase()\n\nfunction blockItem(editor: Editor, block: BlockType, group: string, key = block.id): SlashItem {\n const m = editor.storage.meiConfig.messages\n return {\n key,\n group,\n title: blockTitle(m, block),\n description: m.blocks[block.id]?.description,\n icon: block.icon,\n shortcut: block.shortcut,\n terms: [blockTitle(m, block), block.id, ...block.keywords],\n apply: (ed) => {\n pushRecentBlock(block.id)\n block.insert(ed.chain().focus()).run()\n },\n }\n}\n\nfunction listItemRange($pos: ResolvedPos): BlockRange | null {\n for (let d = $pos.depth; d > 0; d--) {\n const name = $pos.node(d).type.name\n if (name === 'listItem' || name === 'taskItem') return { from: $pos.before(d), to: $pos.after(d), depth: d - 1 }\n }\n return null\n}\n\nfunction colorItems(editor: Editor): SlashItem[] {\n const m = editor.storage.meiConfig.messages\n return (['text', 'bg'] as const).flatMap(kind => PALETTE_NAMES.map((color): SlashItem => {\n const name = m.colors[color] ?? color\n const title = kind === 'text' ? m.slash.textColor(name) : m.slash.bgColor(name)\n return {\n key: `color-${kind}-${color}`,\n group: m.slash.colors,\n title,\n swatch: { kind, color },\n terms: [title, name, color, kind === 'text' ? 'color mau chu 文字颜色' : 'background highlight nen 背景颜色'],\n apply: (ed) => {\n pushRecentColor({ kind, color })\n const caret = ed.state.selection.from\n // Inside a list, \"/red\" colors just that item (each item is its own block in Notion).\n const range = listItemRange(ed.state.selection.$from) ?? currentRange(ed.state)\n if (!range) return\n colorBlocks(ed, range, kind, color)\n ed.commands.setTextSelection(caret)\n },\n }\n }))\n}\n\n/**\n * Items for the slash menu. Without a query: recently used blocks, all blocks by group,\n * then colors. With a query: everything ranked (exact term > word prefix > substring).\n */\nexport function slashItems(editor: Editor, query: string): SlashItem[] {\n const m = editor.storage.meiConfig.messages\n const blocks = enabledBlocks(editor)\n const all = [...blocks.map(b => blockItem(editor, b, groupLabel(m, b.group))), ...colorItems(editor)]\n\n const q = normalize(query.trim())\n if (!q) {\n const recentItems = recent.value.blocks\n .map(id => blocks.find(b => b.id === id))\n .filter((b): b is BlockType => !!b)\n .map(b => blockItem(editor, b, m.slash.recent, `recent-${b.id}`))\n // The menu shows items grouped, and ↑/↓ follow this array — so keep each group\n // contiguous (blocks from later definitions, e.g. `file`, join their group).\n const rank = new Map<string, number>()\n for (const item of [...recentItems, ...all]) if (!rank.has(item.group)) rank.set(item.group, rank.size)\n return [...recentItems, ...all]\n .map((item, i) => ({ item, i }))\n .sort((a, b) => rank.get(a.item.group)! - rank.get(b.item.group)! || a.i - b.i)\n .map(x => x.item)\n }\n\n const score = (item: SlashItem) => {\n const terms = item.terms.map(normalize)\n // Title or id typed exactly beats a block that merely lists it as a keyword (\"/page\" → Page, not Mention).\n if (terms[0] === q || terms[1] === q) return 4\n if (terms.includes(q)) return 3\n if (terms.some(t => t.startsWith(q) || t.split(/\\s+/).some(w => w.startsWith(q)))) return 2\n if (terms.some(t => t.includes(q))) return 1\n return 0\n }\n return all\n .map((item, i) => ({ item, i, s: score(item) }))\n .filter(x => x.s > 0)\n .sort((a, b) => b.s - a.s || a.i - b.i)\n .map(x => x.item)\n}\n","import { cssVar } from './define'\n\n/**\n * Reads a token's resolved pixel value from an element, for JS-driven layout\n * (e.g. popover offsets). Returns `fallback` when unavailable.\n */\nexport function readTokenPx(el: Element | null | undefined, path: string, fallback = 0): number {\n if (!el || typeof getComputedStyle === 'undefined') return fallback\n const probe = document.createElement('div')\n probe.style.cssText = `position:absolute;visibility:hidden;width:var(${cssVar(path)})`\n el.appendChild(probe)\n const px = probe.getBoundingClientRect().width\n probe.remove()\n return px || fallback\n}\n","import type { PluginKey } from '@tiptap/pm/state'\nimport { exitSuggestion, type SuggestionKeyDownProps, type SuggestionOptions, type SuggestionProps } from '@tiptap/suggestion'\nimport { VueRenderer } from '@tiptap/vue-3'\nimport { autoUpdate, computePosition, flip, offset, shift } from '@floating-ui/dom'\nimport type { Component } from 'vue'\nimport { readTokenPx } from '../theme/read'\n\n/**\n * Renders a suggestion popup (slash menu, emoji, mentions) with a Vue component that\n * exposes `onKeyDown(event): boolean`, positioned under the caret with floating-ui.\n */\nexport function suggestionRenderer<I>(\n component: Component,\n pluginKey: PluginKey,\n hooks: { onUpdate?: (props: SuggestionProps<I>) => boolean | void, onStart?: () => void } = {},\n): SuggestionOptions<I>['render'] {\n return () => {\n let renderer: VueRenderer | null = null\n let cleanup: (() => void) | null = null\n\n const position = (props: SuggestionProps<I>) => {\n const el = renderer?.element as HTMLElement | undefined\n if (!el || !props.clientRect) return\n const reference = { getBoundingClientRect: () => props.clientRect?.() ?? new DOMRect() }\n const gap = readTokenPx(props.editor.view.dom, 'popover.offset')\n cleanup?.()\n cleanup = autoUpdate(reference, el, () => {\n computePosition(reference, el, {\n placement: 'bottom-start',\n strategy: 'fixed',\n middleware: [offset(gap), flip({ padding: gap }), shift({ padding: gap })],\n }).then(({ x, y }) => Object.assign(el.style, { left: `${x}px`, top: `${y}px` }))\n })\n }\n\n return {\n onStart: (props) => {\n hooks.onStart?.()\n renderer = new VueRenderer(component, { props, editor: props.editor })\n const el = renderer.element as HTMLElement\n Object.assign(el.style, { position: 'fixed', zIndex: '50', left: '0', top: '0' })\n document.body.appendChild(el)\n position(props)\n },\n onUpdate: (props) => {\n // A hook returning false closes the popup (deferred: no dispatch during view updates).\n if (hooks.onUpdate?.(props) === false) {\n setTimeout(() => exitSuggestion(props.editor.view, pluginKey))\n return\n }\n renderer?.updateProps(props)\n position(props)\n },\n onKeyDown: (props: SuggestionKeyDownProps) => {\n if (props.event.key === 'Escape') {\n exitSuggestion(props.view, pluginKey)\n return true\n }\n return renderer?.ref?.onKeyDown?.(props.event) ?? false\n },\n onExit: () => {\n cleanup?.()\n cleanup = null\n renderer?.element?.remove()\n renderer?.destroy()\n renderer = null\n },\n }\n }\n}\n","import { Extension } from '@tiptap/core'\nimport { PluginKey } from '@tiptap/pm/state'\nimport Suggestion from '@tiptap/suggestion'\nimport SlashMenu from '../components/SlashMenu.vue'\nimport { type SlashItem, slashItems } from '../slash-items'\nimport { suggestionRenderer } from './suggestion-renderer'\n\nexport const slashPluginKey = new PluginKey('slashCommand')\n\nexport const SlashCommand = Extension.create({\n name: 'slashCommand',\n // Above list/task keymaps, so Enter picks a menu item instead of splitting the item.\n priority: 200,\n\n addProseMirrorPlugins() {\n let lastMatch = 0\n return [\n Suggestion<SlashItem>({\n editor: this.editor,\n pluginKey: slashPluginKey,\n char: '/',\n // Multi-word names (\"tiêu đề 2\", \"nền vàng\") need spaces; see onUpdate for closing.\n allowSpaces: true,\n // Not inside code blocks, nor table cells (cells are text-only).\n allow: ({ state, range }) => {\n const $pos = state.doc.resolve(range.from)\n if ($pos.parent.type.spec.code) return false\n for (let d = $pos.depth; d > 0; d--) {\n if (['tableCell', 'tableHeader'].includes($pos.node(d).type.name)) return false\n }\n return true\n },\n items: ({ query, editor }) => slashItems(editor, query),\n command: ({ editor, range, props: item }) => {\n editor.chain().focus().deleteRange(range).run()\n item.apply(editor)\n },\n render: suggestionRenderer<SlashItem>(SlashMenu, slashPluginKey, {\n onStart: () => (lastMatch = 0),\n // Smart close (like Notion): stop once the user is clearly just typing text —\n // no results and a space, or 3+ chars past the last match. props.items is\n // briefly empty while items load, so count matches directly.\n onUpdate: (props) => {\n if (slashItems(props.editor, props.query).length) lastMatch = props.query.length\n else if (props.query.endsWith(' ') || props.query.length - lastMatch >= 3) return false\n },\n }),\n }),\n ]\n },\n})\n","import { Node } from '@tiptap/core'\nimport { NodeSelection, Plugin, PluginKey, TextSelection } from '@tiptap/pm/state'\n\n/**\n * Placeholders for content whose block type isn't loaded in this editor (e.g. a doc\n * written where `math` was enabled). The original JSON is kept in `data` and restored\n * on output, so nothing is lost; the block can be moved or deleted but not edited.\n */\nfunction placeholder(name: string, inline: boolean) {\n return Node.create({\n name,\n group: inline ? 'inline' : 'block',\n inline,\n atom: true,\n selectable: true,\n draggable: !inline,\n\n addAttributes() {\n return {\n data: {\n default: null,\n parseHTML: el => JSON.parse(el.getAttribute('data-json') || 'null'),\n renderHTML: attrs => ({ 'data-json': JSON.stringify(attrs.data) }),\n },\n /** True when the block type is known but its content was invalid. */\n invalid: { default: false, rendered: false },\n }\n },\n\n parseHTML() {\n return [{ tag: `${inline ? 'span' : 'div'}[data-type=\"${name}\"]` }]\n },\n\n renderHTML({ HTMLAttributes }) {\n return [inline ? 'span' : 'div', { ...HTMLAttributes, 'data-type': name }]\n },\n\n addProseMirrorPlugins() {\n // Typing while the placeholder is selected would replace it (and lose its data);\n // put the text in a new paragraph after it instead. Deleting still works on purpose.\n return [new Plugin({\n key: new PluginKey(`${name}Guard`),\n props: {\n handleTextInput: (view, _from, _to, text) => {\n const sel = view.state.selection\n if (!(sel instanceof NodeSelection) || sel.node.type.name !== name) return false\n const tr = view.state.tr\n if (inline) {\n tr.setSelection(TextSelection.create(tr.doc, sel.to)).insertText(text)\n }\n else {\n const paragraph = view.state.schema.nodes.paragraph!.create(null, view.state.schema.text(text))\n tr.insert(sel.to, paragraph).setSelection(TextSelection.create(tr.doc, sel.to + 1 + text.length))\n }\n view.dispatch(tr.scrollIntoView())\n return true\n },\n },\n })]\n },\n\n addNodeView() {\n return ({ node, editor }) => {\n const dom = document.createElement(inline ? 'span' : 'div')\n dom.className = inline ? 'me-unknown me-unknown--inline' : `me-unknown${node.attrs.invalid ? ' is-invalid' : ''}`\n dom.contentEditable = 'false'\n const m = editor.storage.meiConfig?.messages\n const label = node.attrs.invalid ? (m?.invalidBlock ?? 'Invalid block') : (m?.unknownBlock ?? 'Unsupported block')\n dom.textContent = `${label}: ${node.attrs.data?.type ?? '?'}`\n return { dom }\n }\n },\n })\n}\n\nexport const UnknownBlock = placeholder('unknownBlock', false)\nexport const UnknownInline = placeholder('unknownInline', true)\n","import type { AnyExtension } from '@tiptap/core'\nimport StarterKit from '@tiptap/starter-kit'\nimport { MeiConfig, type MeiConfigStorage } from '../config'\nimport { collectExtensions, type BlockDefinition } from '../define-block'\nimport { BlockDrop } from './block-drop'\nimport { BlockId } from './block-id'\nimport { BlockSelection } from './block-selection'\nimport { MarkdownPaste } from './markdown-paste'\nimport { Placeholder } from './placeholder'\nimport { BgColor, BlockColor, TextColor } from './color-marks'\nimport { SlashCommand } from './slash-command'\nimport { UnknownBlock, UnknownInline } from './unknown'\n\nexport interface MeiExtensionsOptions extends Partial<MeiConfigStorage> {\n /** Block definitions to load (their extensions and menu items). */\n blocks: BlockDefinition[]\n /**\n * Built-in undo / redo (StarterKit's `undoRedo`). Default true. Set false with\n * `collaborationExtensions()` (`@toantranmei/editor/collaboration`), which brings Yjs undo.\n */\n undoRedo?: boolean\n}\n\n/**\n * Editor core (always loaded) + the extensions of the given blocks.\n * Core: paragraphs, text marks, links, history, colors, slash menu, drag & drop,\n * block selection, block ids and the unknown-block fallback.\n */\nexport function createExtensions({ blocks, undoRedo = true, ...config }: MeiExtensionsOptions): AnyExtension[] {\n return [\n MeiConfig.configure({ ...config, items: blocks.flatMap(b => b.items), formatActions: blocks.flatMap(b => b.formatActions ?? []) }),\n StarterKit.configure({\n // Block types come from block definitions.\n heading: false,\n bulletList: false,\n orderedList: false,\n listItem: false,\n listKeymap: false,\n blockquote: false,\n codeBlock: false,\n horizontalRule: false,\n ...(undoRedo ? {} : { undoRedo: false as const }),\n dropcursor: { color: '#93c5fd', width: 3 },\n link: { openOnClick: false, autolink: true, defaultProtocol: 'https' },\n }),\n Placeholder.configure({\n placeholder: ({ editor, node }) => {\n const m = editor.storage.meiConfig.messages\n if (node.type.name === 'heading') return m.headingPlaceholder(node.attrs.level)\n if (node.type.name === 'detailsSummary') return m.togglePlaceholder\n return m.placeholder\n },\n }),\n TextColor,\n BgColor,\n BlockColor,\n SlashCommand,\n MarkdownPaste,\n BlockDrop,\n BlockSelection,\n UnknownBlock,\n UnknownInline,\n ...collectExtensions(blocks),\n // Stable ids for block-level nodes (used by \"Copy link to block\").\n BlockId.configure({ types: ['paragraph', ...new Set(blocks.flatMap(b => b.nodes))] }),\n ]\n}\n","/**\n * The line the block handle (+ ⋮⋮) is vertically centered on, like Notion:\n * - text blocks: their first line of text (headings, callouts, lists, tables…)\n * - blocks with a header bar (code, HTML): the bar\n * - dividers: the line itself\n * - media and other blocks without text (image, embed, file…): a text line at their top edge\n *\n * Centering on a line, instead of aligning tops, keeps the handle level with the text\n * whatever padding, margin or font size a block has.\n */\nexport function handleAnchorRect(dom: HTMLElement): DOMRect {\n const box = dom.getBoundingClientRect()\n const lineHeight = lineHeightOf(dom)\n const line = (center: number) => new DOMRect(box.left, center - lineHeight / 2, box.width, lineHeight)\n\n if (dom.tagName === 'HR') return line(box.top + box.height / 2)\n\n const bar = dom.querySelector<HTMLElement>('.me-block-bar')\n if (bar) {\n const r = bar.getBoundingClientRect()\n return line(r.top + r.height / 2)\n }\n\n const text = firstTextRect(dom)\n if (text) return line(text.top + text.height / 2)\n\n // An empty text block: the middle of its first (empty) line.\n const block = dom.matches('p, h1, h2, h3, h4, summary') ? dom : dom.querySelector<HTMLElement>('p, h1, h2, h3, h4, summary')\n if (block) {\n const r = block.getBoundingClientRect()\n const padTop = Number.parseFloat(getComputedStyle(block).paddingTop) || 0\n return line(r.top + padTop + lineHeightOf(block) / 2)\n }\n\n return line(box.top + lineHeight / 2)\n}\n\n/**\n * Rect of the first visible character. Prefers editable text over UI inside the block\n * (a callout's emoji button, an image toolbar); blocks that only have UI text (TOC,\n * upload placeholders) fall back to that.\n */\nfunction firstTextRect(root: HTMLElement): DOMRect | null {\n const inUi = (node: Node) => {\n const ui = node.parentElement?.closest('[contenteditable=\"false\"]')\n return !!ui && ui !== root && root.contains(ui)\n }\n return findTextRect(root, node => !inUi(node)) ?? findTextRect(root, () => true)\n}\n\nfunction findTextRect(root: HTMLElement, accept: (node: Node) => boolean): DOMRect | null {\n const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {\n acceptNode: node => (node.textContent?.trim() && accept(node) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP),\n })\n for (let node = walker.nextNode(); node; node = walker.nextNode()) {\n const offset = node.textContent!.search(/\\S/)\n const range = document.createRange()\n range.setStart(node, offset)\n range.setEnd(node, offset + 1)\n const rect = range.getClientRects()[0]\n if (rect && rect.height > 0) return rect\n }\n return null\n}\n\nfunction lineHeightOf(el: HTMLElement): number {\n const style = getComputedStyle(el)\n const lh = Number.parseFloat(style.lineHeight)\n return Number.isNaN(lh) ? Number.parseFloat(style.fontSize) * 1.5 : lh\n}\n","/** Formats a Tiptap-style shortcut ('Mod-Shift-ArrowUp') for display: ⌘⇧↑ on Mac, Ctrl+Shift+↑ elsewhere. */\nconst isMac = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform)\n\nconst MAC: Record<string, string> = { Mod: '⌘', Shift: '⇧', Alt: '⌥', ArrowUp: '↑', ArrowDown: '↓', Backspace: '⌫', Delete: 'Del', Escape: 'Esc' }\nconst PC: Record<string, string> = { Mod: 'Ctrl', Shift: 'Shift', Alt: 'Alt', ArrowUp: '↑', ArrowDown: '↓', Backspace: 'Backspace', Delete: 'Del', Escape: 'Esc' }\n\nexport function kbd(shortcut: string): string {\n const parts = shortcut.split('-').map(p => (isMac ? MAC : PC)[p] ?? p.toUpperCase())\n return isMac ? parts.join('') : parts.join('+')\n}\n\n/** True for ⌘ on Mac / Ctrl elsewhere. */\nexport const isMod = (e: KeyboardEvent | MouseEvent) => (isMac ? e.metaKey : e.ctrlKey)\n","import type { InjectionKey, Ref } from 'vue'\nimport type { BlockDefinition } from './define-block'\nimport type { ThemeTokens } from './theme/tokens'\n\n/** App-wide token overrides provided by the Vue plugin (`app.use(MeiEditorPlugin, { tokens })`). */\nexport const GLOBAL_TOKENS_KEY: InjectionKey<Ref<ThemeTokens | undefined>> = Symbol('mei-editor-tokens')\n\n/** App-wide blocks provided by the Vue plugin / Nuxt module. */\nexport const GLOBAL_BLOCKS_KEY: InjectionKey<BlockDefinition[]> = Symbol('mei-editor-blocks')\n","import { TextSelection } from '@tiptap/pm/state'\nimport { VueNodeViewRenderer } from '@tiptap/vue-3'\nimport type { Component } from 'vue'\n\ninterface PatchedView {\n stopEvent?: (event: Event) => boolean\n handleSelectionUpdate?: () => void\n renderer?: { props?: { selected?: boolean } }\n}\n\n/**\n * VueNodeViewRenderer with two fixes for block node views (image, embed, callout, code…):\n *\n * 1. Lets `mousemove` through from the node view's own UI. Tiptap stops those events\n * by default, which keeps the drag handle from appearing while hovering them.\n * 2. Skips the per-keystroke selection check while typing. Every node view listens to\n * selection changes and calls getPos(), which scans sibling blocks — with thousands\n * of node views that made each keystroke O(views × blocks). A plain caret can't\n * select a node view, so it only needs checking when one is currently selected.\n */\nexport function blockNodeView(component: Component) {\n const render = VueNodeViewRenderer(component)\n return ((props: Parameters<typeof render>[0]) => {\n const view = render(props) as ReturnType<typeof render> & PatchedView\n\n const stop = view.stopEvent?.bind(view)\n if (stop) view.stopEvent = (event: Event) => (event.type === 'mousemove' ? false : stop(event))\n\n const original = view.handleSelectionUpdate\n if (original) {\n const { editor } = props\n const fast = () => {\n const sel = editor.state.selection\n if (sel.empty && sel instanceof TextSelection && !view.renderer?.props?.selected) return\n original()\n }\n editor.off('selectionUpdate', original)\n editor.on('selectionUpdate', fast)\n // destroy() unsubscribes `this.handleSelectionUpdate`, so point it at the new handler.\n view.handleSelectionUpdate = fast\n }\n return view\n }) as typeof render\n}\n","import type { Editor } from '@tiptap/core'\nimport { onBeforeUnmount, readonly, ref } from 'vue'\n\n/**\n * `editor.isEditable` as a Vue ref. The editor's flag isn't reactive, so node views\n * would keep showing edit controls after switching to read-only (setEditable emits\n * an update, which is what we listen to).\n */\nexport function useEditable(editor: Editor) {\n const editable = ref(editor.isEditable)\n const sync = () => {\n if (editable.value !== editor.isEditable) editable.value = editor.isEditable\n }\n editor.on('update', sync)\n onBeforeUnmount(() => editor.off('update', sync))\n return readonly(editable)\n}\n","import { onBeforeUnmount, onMounted, type Ref } from 'vue'\n\n/** An element, or a component whose root element counts (e.g. a NodeViewWrapper ref). */\ntype Target = HTMLElement | { $el?: unknown } | null | undefined\n\n/** Calls `handler` on a pointerdown outside `target` while `active` is true. */\nexport function useClickOutside(target: Ref<Target>, active: { readonly value: boolean }, handler: () => void) {\n const listener = (e: PointerEvent) => {\n if (!active.value) return\n const value = target.value\n const el = value instanceof Element ? value : value?.$el\n if (el instanceof Element && !el.contains(e.target as Node)) handler()\n }\n onMounted(() => document.addEventListener('pointerdown', listener, true))\n onBeforeUnmount(() => document.removeEventListener('pointerdown', listener, true))\n}\n","<script setup lang=\"ts\">\nimport { NodeViewContent, NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'\nimport { useEditable } from '../composables/useEditable'\nimport { handleAnchorRect } from '../handle-anchor'\nimport { PALETTE_NAMES } from '../theme/tokens'\nimport { useClickOutside } from '../composables/useClickOutside'\n\nconst props = defineProps(nodeViewProps)\nconst editable = useEditable(props.editor)\n\nconst ICONS = ['💡', '⚠️', '❗', '✅', 'ℹ️', '📌', '🔥', '📝', '🚀', '❓', '⭐', '🎯']\nconst open = ref(false)\nconst pickerEl = ref<HTMLElement | null>(null)\nuseClickOutside(pickerEl, open, () => (open.value = false))\n\nconst m = computed(() => props.editor.storage.meiConfig.messages)\n\n// Keep the icon centered on the first line of the content, whatever block it is\n// (text, heading, list, code…), measured the same way as the block handle.\nconst root = ref<{ $el: HTMLElement } | null>(null)\nconst iconEl = ref<HTMLElement | null>(null)\nconst iconOffset = ref(0)\nfunction alignIcon() {\n const content = root.value?.$el.querySelector<HTMLElement>('.me-callout-content')\n const first = content?.firstElementChild\n if (!content || !(first instanceof HTMLElement) || !iconEl.value) return\n const line = handleAnchorRect(first)\n const center = line.top + line.height / 2 - content.getBoundingClientRect().top\n iconOffset.value = Math.round(center - iconEl.value.offsetHeight / 2)\n}\nlet observer: ResizeObserver | null = null\nonMounted(() => {\n alignIcon()\n if (typeof ResizeObserver !== 'undefined') {\n observer = new ResizeObserver(() => alignIcon())\n const content = root.value?.$el.querySelector('.me-callout-content')\n if (content) observer.observe(content)\n }\n})\nwatch(() => props.node, () => nextTick(alignIcon))\nonBeforeUnmount(() => observer?.disconnect())\n</script>\n\n<template>\n <NodeViewWrapper ref=\"root\" class=\"me-callout\" :data-color=\"node.attrs.color\">\n <div ref=\"pickerEl\" class=\"me-callout-icon-wrap\" contenteditable=\"false\" :style=\"{ marginTop: `${iconOffset}px` }\">\n <button ref=\"iconEl\" type=\"button\" class=\"me-callout-icon\" :title=\"m.callout.change\" :disabled=\"!editable\" @click=\"open = !open\">\n {{ node.attrs.icon }}\n </button>\n <div v-if=\"open\" class=\"me-popover me-callout-picker\">\n <div class=\"me-menu-label\">\n {{ m.callout.icon }}\n </div>\n <div class=\"me-emoji-grid\">\n <button v-for=\"icon in ICONS\" :key=\"icon\" type=\"button\" class=\"me-emoji\" @click=\"updateAttributes({ icon }); open = false\">\n {{ icon }}\n </button>\n </div>\n <div class=\"me-menu-label\">\n {{ m.callout.background }}\n </div>\n <div class=\"me-swatch-grid\">\n <button\n v-for=\"c in PALETTE_NAMES\"\n :key=\"c\"\n type=\"button\"\n class=\"me-swatch-btn\"\n :class=\"{ 'is-active': node.attrs.color === c }\"\n :data-color=\"c\"\n :title=\"m.colors[c]\"\n @click=\"updateAttributes({ color: c })\"\n />\n </div>\n </div>\n </div>\n <NodeViewContent class=\"me-callout-content\" />\n </NodeViewWrapper>\n</template>\n","<script setup lang=\"ts\">\nimport { NodeViewContent, NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'\nimport { useEditable } from '../composables/useEditable'\nimport { handleAnchorRect } from '../handle-anchor'\nimport { PALETTE_NAMES } from '../theme/tokens'\nimport { useClickOutside } from '../composables/useClickOutside'\n\nconst props = defineProps(nodeViewProps)\nconst editable = useEditable(props.editor)\n\nconst ICONS = ['💡', '⚠️', '❗', '✅', 'ℹ️', '📌', '🔥', '📝', '🚀', '❓', '⭐', '🎯']\nconst open = ref(false)\nconst pickerEl = ref<HTMLElement | null>(null)\nuseClickOutside(pickerEl, open, () => (open.value = false))\n\nconst m = computed(() => props.editor.storage.meiConfig.messages)\n\n// Keep the icon centered on the first line of the content, whatever block it is\n// (text, heading, list, code…), measured the same way as the block handle.\nconst root = ref<{ $el: HTMLElement } | null>(null)\nconst iconEl = ref<HTMLElement | null>(null)\nconst iconOffset = ref(0)\nfunction alignIcon() {\n const content = root.value?.$el.querySelector<HTMLElement>('.me-callout-content')\n const first = content?.firstElementChild\n if (!content || !(first instanceof HTMLElement) || !iconEl.value) return\n const line = handleAnchorRect(first)\n const center = line.top + line.height / 2 - content.getBoundingClientRect().top\n iconOffset.value = Math.round(center - iconEl.value.offsetHeight / 2)\n}\nlet observer: ResizeObserver | null = null\nonMounted(() => {\n alignIcon()\n if (typeof ResizeObserver !== 'undefined') {\n observer = new ResizeObserver(() => alignIcon())\n const content = root.value?.$el.querySelector('.me-callout-content')\n if (content) observer.observe(content)\n }\n})\nwatch(() => props.node, () => nextTick(alignIcon))\nonBeforeUnmount(() => observer?.disconnect())\n</script>\n\n<template>\n <NodeViewWrapper ref=\"root\" class=\"me-callout\" :data-color=\"node.attrs.color\">\n <div ref=\"pickerEl\" class=\"me-callout-icon-wrap\" contenteditable=\"false\" :style=\"{ marginTop: `${iconOffset}px` }\">\n <button ref=\"iconEl\" type=\"button\" class=\"me-callout-icon\" :title=\"m.callout.change\" :disabled=\"!editable\" @click=\"open = !open\">\n {{ node.attrs.icon }}\n </button>\n <div v-if=\"open\" class=\"me-popover me-callout-picker\">\n <div class=\"me-menu-label\">\n {{ m.callout.icon }}\n </div>\n <div class=\"me-emoji-grid\">\n <button v-for=\"icon in ICONS\" :key=\"icon\" type=\"button\" class=\"me-emoji\" @click=\"updateAttributes({ icon }); open = false\">\n {{ icon }}\n </button>\n </div>\n <div class=\"me-menu-label\">\n {{ m.callout.background }}\n </div>\n <div class=\"me-swatch-grid\">\n <button\n v-for=\"c in PALETTE_NAMES\"\n :key=\"c\"\n type=\"button\"\n class=\"me-swatch-btn\"\n :class=\"{ 'is-active': node.attrs.color === c }\"\n :data-color=\"c\"\n :title=\"m.colors[c]\"\n @click=\"updateAttributes({ color: c })\"\n />\n </div>\n </div>\n </div>\n <NodeViewContent class=\"me-callout-content\" />\n </NodeViewWrapper>\n</template>\n","import { Node, mergeAttributes } from '@tiptap/core'\nimport { blockNodeView } from '../nodeviews/renderer'\nimport CalloutView from '../nodeviews/CalloutView.vue'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n callout: {\n setCallout: (attrs?: { icon?: string, color?: string }) => ReturnType\n }\n }\n}\n\nexport const Callout = Node.create({\n name: 'callout',\n group: 'block',\n content: 'block+',\n defining: true,\n draggable: true,\n\n addAttributes() {\n return {\n icon: {\n default: '💡',\n parseHTML: el => el.getAttribute('data-icon') || '💡',\n renderHTML: attrs => ({ 'data-icon': attrs.icon }),\n },\n color: {\n default: 'gray',\n parseHTML: el => el.getAttribute('data-color') || 'gray',\n renderHTML: attrs => ({ 'data-color': attrs.color }),\n },\n }\n },\n\n parseHTML() {\n return [{ tag: 'div[data-type=\"callout\"]' }]\n },\n\n renderHTML({ HTMLAttributes }) {\n return ['div', mergeAttributes(HTMLAttributes, { 'data-type': 'callout' }), 0]\n },\n\n addCommands() {\n return {\n setCallout: attrs => ({ commands }) => commands.wrapIn(this.name, attrs),\n }\n },\n\n addNodeView() {\n return blockNodeView(CalloutView)\n },\n})\n","/**\n * Heavy libraries load on first use, so apps only pay for what documents contain.\n * KaTeX and Mermaid are optional peer dependencies: install them to use `math` / `mermaid`.\n */\nlet katexPromise: Promise<typeof import('katex')['default']> | null = null\n/**\n * KaTeX's stylesheet is NOT imported here: Vite's dev optimizer can't stub a CSS subpath\n * of a missing optional peer, which would break apps that don't use math. The Nuxt module\n * adds it when `math` is enabled; Vue apps import 'katex/dist/katex.min.css' themselves.\n */\nexport function loadKatex() {\n katexPromise ??= import('katex').then(m => m.default)\n return katexPromise\n}\n\nlet mermaidPromise: Promise<typeof import('mermaid')['default']> | null = null\nexport function loadMermaid() {\n mermaidPromise ??= import('mermaid').then(m => m.default)\n return mermaidPromise\n}\n","<script lang=\"ts\">\n/**\n * A page-unique id for every render. Node views are separate Vue render roots, so useId()\n * gave every diagram the same id (`me-mermaid-v-0`): when several diagrams rendered together\n * (opening a page), a failing one removed `#id` — another diagram's SVG — and the next renders\n * failed too (KS-BUG-8).\n */\nlet counter = 0\nconst nextId = () => `me-mermaid-${++counter}`\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, onBeforeUnmount, ref, watch } from 'vue'\nimport type { EditorMessages } from '../locale'\nimport { loadMermaid } from '../lazy'\n\nconst props = defineProps<{ code: string, messages: EditorMessages, dark: boolean }>()\n\nconst svg = ref('')\nconst error = ref('')\nlet timer: ReturnType<typeof setTimeout> | undefined\nlet latest = ''\n\nasync function render() {\n if (!props.code.trim()) {\n svg.value = ''\n return\n }\n const id = nextId()\n latest = id\n try {\n const mermaid = await loadMermaid()\n // securityLevel 'strict' sanitizes labels and disables click handlers in diagrams.\n mermaid.initialize({ startOnLoad: false, securityLevel: 'strict', theme: props.dark ? 'dark' : 'default' })\n const result = await mermaid.render(id, props.code)\n if (latest !== id) return // a newer render took over\n svg.value = result.svg\n error.value = ''\n }\n catch (e) {\n if (latest !== id) return\n // The last good diagram stays while the code has a syntax error (e.g. mid-typing).\n error.value = e instanceof Error && /Failed to fetch|import/i.test(e.message) ? props.messages.mermaid.missing : props.messages.mermaid.invalid\n }\n finally {\n // Mermaid renders in temporary elements in <body> and leaves them there on a syntax error.\n for (const leftover of [id, `d${id}`, `i${id}`]) {\n const el = document.getElementById(leftover)\n if (el && !el.closest('.me-mermaid')) el.remove()\n }\n }\n}\n\n// Debounced while typing.\nwatch(() => [props.code, props.dark], () => {\n clearTimeout(timer)\n timer = setTimeout(render, 300)\n}, { immediate: true })\nonBeforeUnmount(() => clearTimeout(timer))\n\nconst label = computed(() => props.messages.mermaid.preview)\n</script>\n\n<template>\n <div class=\"me-mermaid\" contenteditable=\"false\" :aria-label=\"label\">\n <div v-if=\"svg\" class=\"me-mermaid-svg\" v-html=\"svg\" />\n <p v-if=\"error\" class=\"me-error\">\n {{ error }}\n </p>\n </div>\n</template>\n","<script lang=\"ts\">\n/**\n * A page-unique id for every render. Node views are separate Vue render roots, so useId()\n * gave every diagram the same id (`me-mermaid-v-0`): when several diagrams rendered together\n * (opening a page), a failing one removed `#id` — another diagram's SVG — and the next renders\n * failed too (KS-BUG-8).\n */\nlet counter = 0\nconst nextId = () => `me-mermaid-${++counter}`\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, onBeforeUnmount, ref, watch } from 'vue'\nimport type { EditorMessages } from '../locale'\nimport { loadMermaid } from '../lazy'\n\nconst props = defineProps<{ code: string, messages: EditorMessages, dark: boolean }>()\n\nconst svg = ref('')\nconst error = ref('')\nlet timer: ReturnType<typeof setTimeout> | undefined\nlet latest = ''\n\nasync function render() {\n if (!props.code.trim()) {\n svg.value = ''\n return\n }\n const id = nextId()\n latest = id\n try {\n const mermaid = await loadMermaid()\n // securityLevel 'strict' sanitizes labels and disables click handlers in diagrams.\n mermaid.initialize({ startOnLoad: false, securityLevel: 'strict', theme: props.dark ? 'dark' : 'default' })\n const result = await mermaid.render(id, props.code)\n if (latest !== id) return // a newer render took over\n svg.value = result.svg\n error.value = ''\n }\n catch (e) {\n if (latest !== id) return\n // The last good diagram stays while the code has a syntax error (e.g. mid-typing).\n error.value = e instanceof Error && /Failed to fetch|import/i.test(e.message) ? props.messages.mermaid.missing : props.messages.mermaid.invalid\n }\n finally {\n // Mermaid renders in temporary elements in <body> and leaves them there on a syntax error.\n for (const leftover of [id, `d${id}`, `i${id}`]) {\n const el = document.getElementById(leftover)\n if (el && !el.closest('.me-mermaid')) el.remove()\n }\n }\n}\n\n// Debounced while typing.\nwatch(() => [props.code, props.dark], () => {\n clearTimeout(timer)\n timer = setTimeout(render, 300)\n}, { immediate: true })\nonBeforeUnmount(() => clearTimeout(timer))\n\nconst label = computed(() => props.messages.mermaid.preview)\n</script>\n\n<template>\n <div class=\"me-mermaid\" contenteditable=\"false\" :aria-label=\"label\">\n <div v-if=\"svg\" class=\"me-mermaid-svg\" v-html=\"svg\" />\n <p v-if=\"error\" class=\"me-error\">\n {{ error }}\n </p>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport { NodeViewContent, NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport { Check, ChevronDown, Copy } from '@lucide/vue'\nimport { computed, ref } from 'vue'\nimport { useEditable } from '../composables/useEditable'\nimport { CODE_LANGUAGES } from '../extensions/code-block'\nimport MermaidDiagram from '../components/MermaidDiagram.vue'\n\nconst props = defineProps(nodeViewProps)\nconst editable = useEditable(props.editor)\n\nconst m = computed(() => props.editor.storage.meiConfig.messages.code)\nconst hasMermaid = computed(() => !!props.editor.extensionManager.extensions.find(e => e.name === 'mermaidPreview'))\nconst languages = computed(() => {\n const list = hasMermaid.value ? [...CODE_LANGUAGES, 'mermaid'] : CODE_LANGUAGES\n // Keep an unknown current language (e.g. an alias like \"js\") selectable.\n const current = props.node.attrs.language\n return current && !list.includes(current) ? [...list, current] : list\n})\nconst copied = ref(false)\n\nconst showDiagram = computed(() => props.node.attrs.language === 'mermaid' && hasMermaid.value)\n// Dark when the editor is forced dark, or follows a dark page.\nconst isDark = computed(() => {\n const scope = props.editor.storage.meiConfig.scope.class\n return scope.includes('me-dark') || (!scope.includes('me-light') && document.documentElement.classList.contains('dark'))\n})\n\nasync function copy() {\n await navigator.clipboard.writeText(props.node.textContent)\n copied.value = true\n setTimeout(() => (copied.value = false), 1500)\n}\n</script>\n\n<template>\n <NodeViewWrapper class=\"me-code-block\">\n <div class=\"me-block-bar me-code-toolbar\" contenteditable=\"false\">\n <label class=\"me-code-lang\">\n <select\n :value=\"node.attrs.language || 'plaintext'\"\n :disabled=\"!editable\"\n @change=\"updateAttributes({ language: ($event.target as HTMLSelectElement).value })\"\n >\n <option v-for=\"lang in languages\" :key=\"lang\" :value=\"lang\">{{ lang }}</option>\n </select>\n <ChevronDown />\n </label>\n <button type=\"button\" class=\"me-tool-btn me-code-copy\" @click=\"copy\">\n <component :is=\"copied ? Check : Copy\" /> {{ copied ? m.copied : m.copy }}\n </button>\n </div>\n <pre><NodeViewContent as=\"code\" :class=\"`hljs language-${node.attrs.language || 'plaintext'}`\" /></pre>\n <MermaidDiagram v-if=\"showDiagram\" :code=\"node.textContent\" :messages=\"editor.storage.meiConfig.messages\" :dark=\"isDark\" />\n </NodeViewWrapper>\n</template>\n","<script setup lang=\"ts\">\nimport { NodeViewContent, NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport { Check, ChevronDown, Copy } from '@lucide/vue'\nimport { computed, ref } from 'vue'\nimport { useEditable } from '../composables/useEditable'\nimport { CODE_LANGUAGES } from '../extensions/code-block'\nimport MermaidDiagram from '../components/MermaidDiagram.vue'\n\nconst props = defineProps(nodeViewProps)\nconst editable = useEditable(props.editor)\n\nconst m = computed(() => props.editor.storage.meiConfig.messages.code)\nconst hasMermaid = computed(() => !!props.editor.extensionManager.extensions.find(e => e.name === 'mermaidPreview'))\nconst languages = computed(() => {\n const list = hasMermaid.value ? [...CODE_LANGUAGES, 'mermaid'] : CODE_LANGUAGES\n // Keep an unknown current language (e.g. an alias like \"js\") selectable.\n const current = props.node.attrs.language\n return current && !list.includes(current) ? [...list, current] : list\n})\nconst copied = ref(false)\n\nconst showDiagram = computed(() => props.node.attrs.language === 'mermaid' && hasMermaid.value)\n// Dark when the editor is forced dark, or follows a dark page.\nconst isDark = computed(() => {\n const scope = props.editor.storage.meiConfig.scope.class\n return scope.includes('me-dark') || (!scope.includes('me-light') && document.documentElement.classList.contains('dark'))\n})\n\nasync function copy() {\n await navigator.clipboard.writeText(props.node.textContent)\n copied.value = true\n setTimeout(() => (copied.value = false), 1500)\n}\n</script>\n\n<template>\n <NodeViewWrapper class=\"me-code-block\">\n <div class=\"me-block-bar me-code-toolbar\" contenteditable=\"false\">\n <label class=\"me-code-lang\">\n <select\n :value=\"node.attrs.language || 'plaintext'\"\n :disabled=\"!editable\"\n @change=\"updateAttributes({ language: ($event.target as HTMLSelectElement).value })\"\n >\n <option v-for=\"lang in languages\" :key=\"lang\" :value=\"lang\">{{ lang }}</option>\n </select>\n <ChevronDown />\n </label>\n <button type=\"button\" class=\"me-tool-btn me-code-copy\" @click=\"copy\">\n <component :is=\"copied ? Check : Copy\" /> {{ copied ? m.copied : m.copy }}\n </button>\n </div>\n <pre><NodeViewContent as=\"code\" :class=\"`hljs language-${node.attrs.language || 'plaintext'}`\" /></pre>\n <MermaidDiagram v-if=\"showDiagram\" :code=\"node.textContent\" :messages=\"editor.storage.meiConfig.messages\" :dark=\"isDark\" />\n </NodeViewWrapper>\n</template>\n","import CodeBlockLowlight from '@tiptap/extension-code-block-lowlight'\nimport type { Editor } from '@tiptap/core'\nimport type { NodeType } from '@tiptap/pm/model'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\nimport type { EditorView } from '@tiptap/pm/view'\nimport { createLowlight } from 'lowlight'\nimport { blockNodeView } from '../nodeviews/renderer'\nimport CodeBlockView from '../nodeviews/CodeBlockView.vue'\nimport { LANGUAGE_ALIASES as ALIASES } from './code-languages'\n\n/** Starts empty: each language's grammar is loaded the first time a code block uses it. */\nexport const lowlight = createLowlight()\n\ntype Grammar = Parameters<typeof lowlight.register>[1]\nconst LOADERS: Record<string, () => Promise<{ default: Grammar }>> = {\n arduino: () => import('highlight.js/lib/languages/arduino'),\n bash: () => import('highlight.js/lib/languages/bash'),\n c: () => import('highlight.js/lib/languages/c'),\n cpp: () => import('highlight.js/lib/languages/cpp'),\n csharp: () => import('highlight.js/lib/languages/csharp'),\n css: () => import('highlight.js/lib/languages/css'),\n diff: () => import('highlight.js/lib/languages/diff'),\n go: () => import('highlight.js/lib/languages/go'),\n graphql: () => import('highlight.js/lib/languages/graphql'),\n ini: () => import('highlight.js/lib/languages/ini'),\n java: () => import('highlight.js/lib/languages/java'),\n javascript: () => import('highlight.js/lib/languages/javascript'),\n json: () => import('highlight.js/lib/languages/json'),\n kotlin: () => import('highlight.js/lib/languages/kotlin'),\n less: () => import('highlight.js/lib/languages/less'),\n lua: () => import('highlight.js/lib/languages/lua'),\n makefile: () => import('highlight.js/lib/languages/makefile'),\n markdown: () => import('highlight.js/lib/languages/markdown'),\n objectivec: () => import('highlight.js/lib/languages/objectivec'),\n perl: () => import('highlight.js/lib/languages/perl'),\n php: () => import('highlight.js/lib/languages/php'),\n python: () => import('highlight.js/lib/languages/python'),\n r: () => import('highlight.js/lib/languages/r'),\n ruby: () => import('highlight.js/lib/languages/ruby'),\n rust: () => import('highlight.js/lib/languages/rust'),\n scss: () => import('highlight.js/lib/languages/scss'),\n shell: () => import('highlight.js/lib/languages/shell'),\n sql: () => import('highlight.js/lib/languages/sql'),\n swift: () => import('highlight.js/lib/languages/swift'),\n typescript: () => import('highlight.js/lib/languages/typescript'),\n xml: () => import('highlight.js/lib/languages/xml'),\n yaml: () => import('highlight.js/lib/languages/yaml'),\n}\n\n/** Languages offered in the code block's language picker. */\nexport const CODE_LANGUAGES = ['plaintext', ...Object.keys(LOADERS)]\n\n\nconst pending = new Map<string, Promise<boolean>>()\n\n/** Loads and registers a grammar. Resolves true when newly registered. */\nexport function loadLanguage(language: string): Promise<boolean> {\n const name = ALIASES[language] ?? language\n if (lowlight.registered(name) || !LOADERS[name]) return Promise.resolve(false)\n if (!pending.has(name)) {\n pending.set(name, LOADERS[name]!().then((mod) => {\n lowlight.register(name, mod.default)\n if (name !== language) lowlight.registerAlias(name, language)\n return true\n }).catch(() => false))\n }\n return pending.get(name)!\n}\n\n/** Re-highlights code blocks in `language` once its grammar arrives. */\nfunction refresh(view: EditorView, language: string) {\n if (view.isDestroyed) return\n const tr = view.state.tr\n view.state.doc.descendants((node, pos) => {\n if (node.type.name === 'codeBlock' && node.attrs.language === language) tr.setNodeMarkup(pos, undefined, node.attrs)\n })\n if (tr.docChanged) view.dispatch(tr.setMeta('addToHistory', false))\n}\n\n/** What Tab inserts in a code block. */\nexport const CODE_INDENT = ' '\n\n/**\n * Tab / Shift-Tab in a code block: indent / outdent. A collapsed selection gets an indent at\n * the cursor; a selection indents (outdents) every line it touches. Always handled inside a\n * code block, so focus never leaves the editor (KS-BUG-5).\n */\nexport function indentCode(editor: Editor, type: NodeType, direction: 1 | -1): boolean {\n const { state } = editor\n const { $from, $to, empty } = state.selection\n if ($from.parent.type !== type) return false\n if (!$to.sameParent($from)) return true\n if (!editor.isEditable) return true\n const tr = state.tr\n if (empty && direction === 1) {\n editor.view.dispatch(tr.insertText(CODE_INDENT).scrollIntoView())\n return true\n }\n const start = $from.start()\n const text = $from.parent.textContent\n // Start offsets of the lines touched by the selection.\n const from = $from.parentOffset\n const to = $to.parentOffset\n // (lastIndexOf with -1 would look at index 0.) A selection ending right at a line start\n // doesn't touch that line.\n const lines: number[] = [from === 0 ? 0 : text.lastIndexOf('\\n', from - 1) + 1]\n for (let i = text.indexOf('\\n', from); i !== -1 && i + 1 < to; i = text.indexOf('\\n', i + 1)) lines.push(i + 1)\n // Right to left, so earlier positions stay valid.\n for (const line of lines.reverse()) {\n if (direction === 1) {\n tr.insertText(CODE_INDENT, start + line)\n continue\n }\n const lead = /^(\\t| {1,2})/.exec(text.slice(line))?.[0]\n if (lead) tr.delete(start + line, start + line + lead.length)\n }\n if (tr.docChanged) editor.view.dispatch(tr.scrollIntoView())\n return true\n}\n\nexport const CodeBlock = CodeBlockLowlight.extend({\n addAttributes() {\n const parent: Record<string, object> = this.parent?.() ?? {}\n // No language stays null: a default here would be filled in for every code block read from\n // a Yjs document (it doesn't store null attributes), turning a pure view into an edit (KS-BUG-4).\n // Highlighting still falls back to `defaultLanguage`.\n return { ...parent, language: { ...parent.language, default: null } }\n },\n addKeyboardShortcuts() {\n return {\n ...this.parent?.(),\n 'Tab': () => indentCode(this.editor, this.type, 1),\n 'Shift-Tab': () => indentCode(this.editor, this.type, -1),\n }\n },\n addProseMirrorPlugins() {\n // One load + one re-highlight per language (not per code block: that was O(n²)).\n const requested = new Set<string>()\n const check = (view: EditorView) => {\n view.state.doc.descendants((node) => {\n const language = node.attrs.language as string | null\n if (node.type.name === 'codeBlock' && language && !requested.has(language)) {\n requested.add(language)\n loadLanguage(language).then(added => added && refresh(view, language))\n }\n return !node.isTextblock\n })\n }\n return [\n ...(this.parent?.() ?? []),\n new Plugin({\n key: new PluginKey('codeBlockLanguages'),\n view: (view) => {\n check(view)\n return { update: (v, prev) => !v.state.doc.eq(prev.doc) && check(v) }\n },\n }),\n ]\n },\n addNodeView() {\n return blockNodeView(CodeBlockView)\n },\n}).configure({ lowlight, defaultLanguage: 'plaintext' })\n","import { Node, mergeAttributes } from '@tiptap/core'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n columns: {\n setColumns: (count: number) => ReturnType\n }\n }\n}\n\nexport const Column = Node.create({\n name: 'column',\n content: 'block+',\n isolating: true,\n\n parseHTML() {\n return [{ tag: 'div[data-type=\"column\"]' }]\n },\n\n renderHTML({ HTMLAttributes }) {\n return ['div', mergeAttributes(HTMLAttributes, { 'data-type': 'column', class: 'me-column' }), 0]\n },\n})\n\nexport const Columns = Node.create({\n name: 'columns',\n group: 'block',\n content: 'column{2,5}',\n isolating: true,\n defining: true,\n\n parseHTML() {\n return [{ tag: 'div[data-type=\"columns\"]' }]\n },\n\n renderHTML({ HTMLAttributes, node }) {\n return ['div', mergeAttributes(HTMLAttributes, {\n 'data-type': 'columns',\n class: 'me-columns',\n style: `--cols:${node.childCount}`,\n }), 0]\n },\n\n addCommands() {\n return {\n setColumns: count => ({ commands }) => commands.insertContent({\n type: this.name,\n content: Array.from({ length: count }, () => ({\n type: 'column',\n content: [{ type: 'paragraph' }],\n })),\n }),\n }\n },\n})\n","import { TableCell, TableHeader, TableKit } from '@tiptap/extension-table'\n\n/** Background color by palette name (`data-color`), so themes and dark mode apply. */\nconst colorAttr = {\n color: {\n default: null,\n parseHTML: (el: HTMLElement) => el.getAttribute('data-color'),\n renderHTML: (attrs: Record<string, any>) => (attrs.color ? { 'data-color': attrs.color } : {}),\n },\n}\n\n// Cells hold paragraphs only (like Notion's simple tables): no images, lists or columns\n// nested in cells, which made tables hard to use.\nconst ColoredCell = TableCell.extend({\n content: 'paragraph+',\n addAttributes() {\n return { ...this.parent?.(), ...colorAttr }\n },\n})\nconst ColoredHeader = TableHeader.extend({\n content: 'paragraph+',\n addAttributes() {\n return { ...this.parent?.(), ...colorAttr }\n },\n})\n\nexport const tableExtensions = [\n TableKit.configure({ table: { resizable: true }, tableCell: false, tableHeader: false }),\n ColoredCell,\n ColoredHeader,\n]\n","import { Details, DetailsContent, DetailsSummary } from '@tiptap/extension-details'\n\n/**\n * Toggle (collapsible) block. `level` turns the summary into a heading, which is how\n * Notion's toggle headings work: the heading's content folds under it.\n */\nexport const ToggleDetails = Details.extend({\n addAttributes() {\n return {\n ...this.parent?.(),\n level: {\n default: null,\n parseHTML: el => Number(el.getAttribute('data-level')) || null,\n renderHTML: attrs => (attrs.level ? { 'data-level': attrs.level } : {}),\n },\n }\n },\n\n // Tiptap's node view doesn't re-render attributes on update; keep level and block\n // colors in sync so changing them shows without a reload.\n //\n // Upstream also opens a toggle created open with a deferred *flip*\n // (`setTimeout(() => toggleDetailsContent())`). If update() runs before that timer\n // (any transaction touching the toggle right after it renders, e.g. typing inside a\n // nested toggle), update() opens it and the timer closes it again: an open toggle shows\n // closed although the document says `open: true`. So until that timer has fired we only\n // remember the latest node, then settle the DOM on its `open` attribute (set, not flip).\n // Remove once upstream sets the value instead of toggling (it still flips in\n // @tiptap/extension-details 3.32.0 through 3.32.2). Covered by test/toggle.test.ts.\n addNodeView() {\n const parent = this.parent?.()\n if (!parent) return null\n return (props) => {\n const view = parent(props)\n type PMNode = typeof props.node\n const upstreamUpdate = view.update?.bind(view) as ((node: PMNode, ...rest: any[]) => boolean) | undefined\n let latest = props.node\n let openPending = Boolean(props.node.attrs.open) && !!upstreamUpdate\n if (openPending) {\n // Queued after upstream's timer (same delay, FIFO), so it runs right after the flip.\n setTimeout(() => {\n openPending = false\n upstreamUpdate?.(latest)\n })\n }\n const dom = view.dom as HTMLElement\n const sync = (attrs: Record<string, any>) => {\n for (const [data, value] of [['data-level', attrs.level], ['data-text-color', attrs.blockColor], ['data-bg-color', attrs.blockBg]]) {\n if (value) dom.setAttribute(data, String(value))\n else dom.removeAttribute(data)\n }\n }\n return Object.assign(view, {\n update: (node: PMNode, ...rest: any[]) => {\n const ok = upstreamUpdate && !openPending ? upstreamUpdate(node, ...rest) : node.type === props.node.type\n if (ok && openPending) latest = node\n if (ok) sync(node.attrs)\n return ok\n },\n })\n }\n },\n}).configure({ persist: true, HTMLAttributes: { class: 'me-toggle' } })\n\nexport const toggleExtensions = [ToggleDetails, DetailsSummary, DetailsContent]\n","import { Code, Columns2, Columns3, Columns4, Heading1, Heading2, Heading3, Lightbulb, ListCollapse, Table } from '@lucide/vue'\nimport type { ChainedCommands } from '@tiptap/core'\nimport { type BlockType, isNode } from '../block-items'\nimport { defineBlock } from '../define-block'\nimport { Callout } from '../extensions/callout'\nimport { CodeBlock } from '../extensions/code-block'\nimport { Column, Columns } from '../extensions/columns'\nimport { tableExtensions } from '../extensions/table'\nimport { toggleExtensions } from '../extensions/toggle'\n\nexport const codeBlock = defineBlock({\n name: 'codeBlock',\n nodes: ['codeBlock'],\n extensions: () => [CodeBlock],\n items: () => [{\n id: 'codeBlock',\n icon: Code,\n group: 'basic',\n keywords: ['code', 'snippet', 'pre', '代码', '代码块'],\n shortcut: '```',\n insert: c => c.setCodeBlock(),\n turnInto: c => c.setCodeBlock(),\n matches: n => n.type.name === 'codeBlock' && n.attrs.language !== 'mermaid',\n }],\n})\n\nexport const callout = defineBlock({\n name: 'callout',\n nodes: ['callout'],\n extensions: () => [Callout],\n items: () => [{\n id: 'callout',\n icon: Lightbulb,\n group: 'advanced',\n keywords: ['callout', 'note', 'info', 'warning', 'ghi chu', '标注', '提示'],\n insert: c => c.setCallout(),\n turnInto: c => c.setCallout(),\n matches: isNode('callout'),\n }],\n})\n\nexport const toggle = defineBlock({\n name: 'toggle',\n nodes: ['details'],\n extensions: () => toggleExtensions,\n items: () => [{\n id: 'toggle',\n icon: ListCollapse,\n group: 'advanced',\n keywords: ['toggle', 'details', 'collapse', 'thu gon', '折叠', '折叠列表'],\n insert: c => c.setDetails(),\n turnInto: c => c.setDetails(),\n matches: n => n.type.name === 'details' && !n.attrs.level,\n }],\n})\n\n/** Sets `level` on the toggle that holds the selection (after setDetails). */\nconst setToggleLevel = (level: number) => (c: ChainedCommands) => c.command(({ tr }) => {\n const { $from } = tr.selection\n for (let d = $from.depth; d > 0; d--) {\n if ($from.node(d).type.name === 'details') {\n tr.setNodeMarkup($from.before(d), undefined, { ...$from.node(d).attrs, level })\n return true\n }\n }\n return false\n})\n\nconst TOGGLE_HEADING_ICONS = { 1: Heading1, 2: Heading2, 3: Heading3 } as const\n\n/** Notion's toggle headings: a heading whose content folds under it. */\nexport const toggleHeading = defineBlock({\n name: 'toggleHeading',\n nodes: ['details'],\n extensions: () => toggleExtensions,\n items: () => ([1, 2, 3] as const).map((level): BlockType => ({\n id: `toggleHeading${level}`,\n icon: TOGGLE_HEADING_ICONS[level],\n group: 'advanced',\n keywords: ['toggle heading', `toggle h${level}`, 'tieu de thu gon', 'collapse', '折叠标题'],\n insert: c => setToggleLevel(level)(c.setDetails()),\n turnInto: c => setToggleLevel(level)(c.setDetails()),\n matches: n => n.type.name === 'details' && n.attrs.level === level,\n })),\n})\n\nexport const table = defineBlock({\n name: 'table',\n nodes: ['table'],\n extensions: () => tableExtensions,\n items: () => [{\n id: 'table',\n icon: Table,\n group: 'advanced',\n keywords: ['table', 'grid', 'bang', '表格'],\n insert: c => c.insertTable({ rows: 3, cols: 3, withHeaderRow: true }),\n matches: isNode('table'),\n }],\n})\n\nconst COLUMN_ICONS = { 2: Columns2, 3: Columns3, 4: Columns4 } as const\n\nexport const columns = defineBlock({\n name: 'columns',\n nodes: ['columns'],\n extensions: () => [Columns, Column],\n items: () => ([2, 3, 4] as const).map((n): BlockType => ({\n id: `columns${n}`,\n icon: COLUMN_ICONS[n],\n group: 'layout',\n keywords: ['columns', 'column', 'cot', 'layout', `${n}`, '分栏', '栏', '布局'],\n insert: c => c.setColumns(n),\n matches: node => node.type.name === 'columns' && node.childCount === n,\n })),\n})\n","import { Heading1, Heading2, Heading3, Heading4, List, ListOrdered, ListTodo, Minus, Quote, Type } from '@lucide/vue'\nimport Heading from '@tiptap/extension-heading'\nimport Blockquote from '@tiptap/extension-blockquote'\nimport HorizontalRule from '@tiptap/extension-horizontal-rule'\nimport { BulletList, ListItem, ListKeymap, OrderedList, TaskItem, TaskList } from '@tiptap/extension-list'\nimport { type BlockType, isNode } from '../block-items'\nimport { defineBlock } from '../define-block'\n\n/** Plain text. Always loaded: the paragraph is part of the editor core. */\nexport const text = defineBlock({\n name: 'text',\n items: () => [{\n id: 'paragraph',\n icon: Type,\n group: 'basic',\n keywords: ['text', 'paragraph', 'p', 'van ban', '文本', '段落'],\n // Already text: Tiptap's setParagraph would then lift the line out of its wrapper.\n // That's right for lists and quotes (\"/text\" drops the bullet, like Notion) but not\n // for callouts, columns, toggles or table cells, where the line should stay put.\n insert: c => c.command(({ state, commands }) => {\n const { $from } = state.selection\n if ($from.parent.type.name !== 'paragraph') return commands.setParagraph()\n const wrapper = $from.depth > 1 ? $from.node($from.depth - 1).type.name : 'doc'\n return ['listItem', 'taskItem', 'blockquote'].includes(wrapper) ? commands.setParagraph() : true\n }),\n turnInto: c => c.setParagraph(),\n matches: isNode('paragraph'),\n }],\n})\n\nconst HEADING_ICONS = { 1: Heading1, 2: Heading2, 3: Heading3, 4: Heading4 } as const\n\nexport const heading = defineBlock<{ levels: (1 | 2 | 3 | 4)[] }>({\n name: 'heading',\n defaults: { levels: [1, 2, 3, 4] },\n nodes: ['heading'],\n extensions: o => [Heading.configure({ levels: o.levels })],\n items: o => o.levels.map((level): BlockType => ({\n id: `heading${level}`,\n icon: HEADING_ICONS[level],\n group: 'basic',\n keywords: [`h${level}`, 'heading', 'tieu de', 'title', '标题'],\n shortcut: '#'.repeat(level),\n insert: c => c.setHeading({ level }),\n turnInto: c => c.setHeading({ level }),\n matches: n => n.type.name === 'heading' && n.attrs.level === level,\n })),\n})\n\nexport const bulletList = defineBlock({\n name: 'bulletList',\n nodes: ['bulletList'],\n extensions: () => [BulletList, ListItem, ListKeymap],\n items: () => [{\n id: 'bulletList',\n icon: List,\n group: 'basic',\n keywords: ['bullet', 'list', 'ul', 'danh sach', '无序列表', '列表'],\n shortcut: '-',\n insert: c => c.toggleBulletList(),\n turnInto: c => c.toggleBulletList(),\n matches: isNode('bulletList'),\n }],\n})\n\nexport const orderedList = defineBlock({\n name: 'orderedList',\n nodes: ['orderedList'],\n extensions: () => [OrderedList, ListItem, ListKeymap],\n items: () => [{\n id: 'orderedList',\n icon: ListOrdered,\n group: 'basic',\n keywords: ['number', 'ordered', 'list', 'ol', 'danh sach so', '有序列表', '编号列表'],\n shortcut: '1.',\n insert: c => c.toggleOrderedList(),\n turnInto: c => c.toggleOrderedList(),\n matches: isNode('orderedList'),\n }],\n})\n\nexport const taskList = defineBlock({\n name: 'taskList',\n nodes: ['taskList'],\n extensions: () => [TaskList, TaskItem.configure({ nested: true })],\n items: () => [{\n id: 'taskList',\n icon: ListTodo,\n group: 'basic',\n keywords: ['todo', 'task', 'checkbox', 'check', 'viec can lam', '待办', '待办清单', '任务'],\n shortcut: '[]',\n insert: c => c.toggleTaskList(),\n turnInto: c => c.toggleTaskList(),\n matches: isNode('taskList'),\n }],\n})\n\nexport const quote = defineBlock({\n name: 'quote',\n nodes: ['blockquote'],\n extensions: () => [Blockquote],\n items: () => [{\n id: 'blockquote',\n icon: Quote,\n group: 'basic',\n keywords: ['quote', 'blockquote', 'trich dan', '引用'],\n shortcut: '>',\n insert: c => c.setBlockquote(),\n turnInto: c => c.setBlockquote(),\n matches: isNode('blockquote'),\n }],\n})\n\nexport const divider = defineBlock({\n name: 'divider',\n nodes: ['horizontalRule'],\n extensions: () => [HorizontalRule],\n items: () => [{\n id: 'divider',\n icon: Minus,\n group: 'basic',\n keywords: ['divider', 'hr', 'line', 'separator', 'duong ke', '分割线', '分隔线'],\n shortcut: '---',\n insert: c => c.setHorizontalRule(),\n matches: isNode('horizontalRule'),\n }],\n})\n","<script setup lang=\"ts\">\nimport { NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport { computed, ref } from 'vue'\nimport { useEditable } from '../composables/useEditable'\nimport { toEmbedUrl } from '../extensions/embed'\n\nconst props = defineProps(nodeViewProps)\nconst editable = useEditable(props.editor)\n\nconst m = computed(() => props.editor.storage.meiConfig.messages.embed)\nconst link = ref('')\nconst error = ref('')\nconst resizing = ref(false)\nconst safeSrc = computed(() => (props.node.attrs.src ? toEmbedUrl(props.node.attrs.src) : null))\n\nfunction submit() {\n const src = toEmbedUrl(link.value)\n if (!src) {\n error.value = m.value.invalid\n return\n }\n props.updateAttributes({ src })\n}\n\nfunction startResize(e: PointerEvent) {\n e.preventDefault()\n resizing.value = true\n const startY = e.clientY\n const startH = props.node.attrs.height as number\n const move = (ev: PointerEvent) => {\n props.updateAttributes({ height: Math.round(Math.min(1200, Math.max(160, startH + ev.clientY - startY))) })\n }\n const up = () => {\n resizing.value = false\n window.removeEventListener('pointermove', move)\n window.removeEventListener('pointerup', up)\n }\n window.addEventListener('pointermove', move)\n window.addEventListener('pointerup', up)\n}\n</script>\n\n<template>\n <NodeViewWrapper class=\"me-media\" :class=\"{ 'is-readonly-empty': !editable && !safeSrc }\">\n <form v-if=\"!safeSrc\" class=\"me-media-empty\" contenteditable=\"false\" @submit.prevent=\"submit\">\n <div class=\"me-hint\">\n {{ m.hint }}\n </div>\n <div class=\"me-inline-form\">\n <input v-model=\"link\" class=\"me-input\" :placeholder=\"m.placeholder\" @keydown.stop>\n <button type=\"submit\" class=\"me-btn me-btn--primary\">\n {{ m.submit }}\n </button>\n </div>\n <p v-if=\"error\" class=\"me-error\">\n {{ error }}\n </p>\n </form>\n <div v-else class=\"me-embed\" :class=\"{ 'is-selected': selected }\" contenteditable=\"false\">\n <iframe\n :src=\"safeSrc\"\n :height=\"node.attrs.height\"\n class=\"me-embed-frame\"\n allowfullscreen\n sandbox=\"allow-scripts allow-same-origin allow-popups allow-presentation\"\n />\n <!-- Iframes swallow pointer events; cover them while resizing. -->\n <div v-if=\"resizing\" class=\"me-embed-overlay\" />\n <span v-if=\"editable\" class=\"me-embed-resize\" @pointerdown=\"startResize\" />\n </div>\n </NodeViewWrapper>\n</template>\n","<script setup lang=\"ts\">\nimport { NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport { computed, ref } from 'vue'\nimport { useEditable } from '../composables/useEditable'\nimport { toEmbedUrl } from '../extensions/embed'\n\nconst props = defineProps(nodeViewProps)\nconst editable = useEditable(props.editor)\n\nconst m = computed(() => props.editor.storage.meiConfig.messages.embed)\nconst link = ref('')\nconst error = ref('')\nconst resizing = ref(false)\nconst safeSrc = computed(() => (props.node.attrs.src ? toEmbedUrl(props.node.attrs.src) : null))\n\nfunction submit() {\n const src = toEmbedUrl(link.value)\n if (!src) {\n error.value = m.value.invalid\n return\n }\n props.updateAttributes({ src })\n}\n\nfunction startResize(e: PointerEvent) {\n e.preventDefault()\n resizing.value = true\n const startY = e.clientY\n const startH = props.node.attrs.height as number\n const move = (ev: PointerEvent) => {\n props.updateAttributes({ height: Math.round(Math.min(1200, Math.max(160, startH + ev.clientY - startY))) })\n }\n const up = () => {\n resizing.value = false\n window.removeEventListener('pointermove', move)\n window.removeEventListener('pointerup', up)\n }\n window.addEventListener('pointermove', move)\n window.addEventListener('pointerup', up)\n}\n</script>\n\n<template>\n <NodeViewWrapper class=\"me-media\" :class=\"{ 'is-readonly-empty': !editable && !safeSrc }\">\n <form v-if=\"!safeSrc\" class=\"me-media-empty\" contenteditable=\"false\" @submit.prevent=\"submit\">\n <div class=\"me-hint\">\n {{ m.hint }}\n </div>\n <div class=\"me-inline-form\">\n <input v-model=\"link\" class=\"me-input\" :placeholder=\"m.placeholder\" @keydown.stop>\n <button type=\"submit\" class=\"me-btn me-btn--primary\">\n {{ m.submit }}\n </button>\n </div>\n <p v-if=\"error\" class=\"me-error\">\n {{ error }}\n </p>\n </form>\n <div v-else class=\"me-embed\" :class=\"{ 'is-selected': selected }\" contenteditable=\"false\">\n <iframe\n :src=\"safeSrc\"\n :height=\"node.attrs.height\"\n class=\"me-embed-frame\"\n allowfullscreen\n sandbox=\"allow-scripts allow-same-origin allow-popups allow-presentation\"\n />\n <!-- Iframes swallow pointer events; cover them while resizing. -->\n <div v-if=\"resizing\" class=\"me-embed-overlay\" />\n <span v-if=\"editable\" class=\"me-embed-resize\" @pointerdown=\"startResize\" />\n </div>\n </NodeViewWrapper>\n</template>\n","import { Node, mergeAttributes } from '@tiptap/core'\nimport { blockNodeView } from '../nodeviews/renderer'\nimport EmbedView from '../nodeviews/EmbedView.vue'\nimport { toEmbedUrl } from './embed-url'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n embed: {\n setEmbed: (attrs?: { src?: string | null }) => ReturnType\n }\n }\n}\n\nexport { toEmbedUrl }\n\nexport const Embed = Node.create({\n name: 'embed',\n group: 'block',\n atom: true,\n draggable: true,\n\n addAttributes() {\n return {\n src: { default: null },\n height: { default: 400 },\n }\n },\n\n parseHTML() {\n return [{\n tag: 'div[data-type=\"embed\"]',\n getAttrs: el => ({\n src: toEmbedUrl(el.querySelector('iframe')?.getAttribute('src') ?? ''),\n height: Number(el.querySelector('iframe')?.getAttribute('height')) || 400,\n }),\n }]\n },\n\n renderHTML({ HTMLAttributes, node }) {\n return ['div', { 'data-type': 'embed' }, ['iframe', mergeAttributes(HTMLAttributes, {\n src: node.attrs.src,\n height: node.attrs.height,\n allowfullscreen: 'true',\n sandbox: 'allow-scripts allow-same-origin allow-popups allow-presentation',\n })]]\n },\n\n addCommands() {\n return {\n setEmbed: attrs => ({ commands }) => commands.insertContent({ type: this.name, attrs }),\n }\n },\n\n addNodeView() {\n return blockNodeView(EmbedView)\n },\n})\n","<script setup lang=\"ts\">\n/**\n * Non-destructive crop: shows the whole image with a draggable crop box (move it or\n * drag its corners/edges). The result is stored as fractions of the original image,\n * so the crop can be changed or reset later.\n */\nimport { onBeforeUnmount, onMounted, ref } from 'vue'\nimport type { EditorMessages } from '../locale'\n\nexport interface ImageCrop {\n /** Left / top / width / height as fractions (0–1) of the original image. */\n x: number\n y: number\n w: number\n h: number\n /** Width / height of the cropped area in pixels, for the block's aspect ratio. */\n ratio: number\n}\n\nconst props = defineProps<{ src: string, alt?: string, crop: ImageCrop | null, messages: EditorMessages['image'] }>()\nconst emit = defineEmits<{ done: [crop: ImageCrop | null], cancel: [] }>()\n\nconst MIN = 0.05\nconst box = ref({ x: props.crop?.x ?? 0, y: props.crop?.y ?? 0, w: props.crop?.w ?? 1, h: props.crop?.h ?? 1 })\nconst stage = ref<HTMLElement | null>(null)\nconst img = ref<HTMLImageElement | null>(null)\n\ntype Handle = 'move' | 'n' | 's' | 'e' | 'w' | 'ne' | 'nw' | 'se' | 'sw'\nconst HANDLES: Handle[] = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w']\nconst clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v))\n\nfunction start(e: PointerEvent, handle: Handle) {\n const rect = stage.value?.getBoundingClientRect()\n if (!rect) return\n e.preventDefault()\n e.stopPropagation()\n const from = { ...box.value }\n const sx = e.clientX\n const sy = e.clientY\n const move = (ev: PointerEvent) => {\n const dx = (ev.clientX - sx) / rect.width\n const dy = (ev.clientY - sy) / rect.height\n let { x, y, w, h } = from\n if (handle === 'move') {\n x = clamp(from.x + dx, 0, 1 - from.w)\n y = clamp(from.y + dy, 0, 1 - from.h)\n }\n else {\n if (handle.includes('w')) {\n x = clamp(from.x + dx, 0, from.x + from.w - MIN)\n w = from.x + from.w - x\n }\n if (handle.includes('e')) w = clamp(from.w + dx, MIN, 1 - from.x)\n if (handle.includes('n')) {\n y = clamp(from.y + dy, 0, from.y + from.h - MIN)\n h = from.y + from.h - y\n }\n if (handle.includes('s')) h = clamp(from.h + dy, MIN, 1 - from.y)\n }\n box.value = { x, y, w, h }\n }\n const up = () => {\n window.removeEventListener('pointermove', move)\n window.removeEventListener('pointerup', up)\n }\n window.addEventListener('pointermove', move)\n window.addEventListener('pointerup', up)\n}\n\nfunction done() {\n const { x, y, w, h } = box.value\n const full = w > 0.995 && h > 0.995\n const natural = img.value\n const ratio = natural?.naturalWidth && natural.naturalHeight ? (w * natural.naturalWidth) / (h * natural.naturalHeight) : w / h\n emit('done', full ? null : { x, y, w, h, ratio })\n}\nconst reset = () => (box.value = { x: 0, y: 0, w: 1, h: 1 })\n\nfunction onKey(e: KeyboardEvent) {\n if (e.key === 'Escape') emit('cancel')\n else if (e.key === 'Enter') done()\n else return\n e.preventDefault()\n e.stopPropagation()\n}\nonMounted(() => window.addEventListener('keydown', onKey, true))\nonBeforeUnmount(() => window.removeEventListener('keydown', onKey, true))\n\nconst pct = (v: number) => `${v * 100}%`\n</script>\n\n<template>\n <div class=\"me-cropper\">\n <div ref=\"stage\" class=\"me-cropper-stage\">\n <img ref=\"img\" class=\"me-figure-img\" :src=\"src\" :alt=\"alt || ''\" draggable=\"false\">\n <!-- Dimming is clipped to the image; the box and its handles are not, so edge handles stay grabbable. -->\n <div class=\"me-cropper-shade\">\n <div class=\"me-cropper-hole\" :style=\"{ left: pct(box.x), top: pct(box.y), width: pct(box.w), height: pct(box.h) }\" />\n </div>\n <div\n class=\"me-cropper-box\"\n :style=\"{ left: pct(box.x), top: pct(box.y), width: pct(box.w), height: pct(box.h) }\"\n @pointerdown=\"start($event, 'move')\"\n >\n <span v-for=\"h in HANDLES\" :key=\"h\" class=\"me-cropper-handle\" :data-handle=\"h\" @pointerdown=\"start($event, h)\" />\n </div>\n </div>\n <div class=\"me-cropper-actions\">\n <button type=\"button\" class=\"me-btn\" @click=\"reset\">\n {{ messages.cropReset }}\n </button>\n <span class=\"me-cropper-spacer\" />\n <button type=\"button\" class=\"me-btn\" @click=\"emit('cancel')\">\n {{ messages.cropCancel }}\n </button>\n <button type=\"button\" class=\"me-btn me-btn--primary\" @click=\"done\">\n {{ messages.cropDone }}\n </button>\n </div>\n </div>\n</template>\n","<script setup lang=\"ts\">\n/**\n * Non-destructive crop: shows the whole image with a draggable crop box (move it or\n * drag its corners/edges). The result is stored as fractions of the original image,\n * so the crop can be changed or reset later.\n */\nimport { onBeforeUnmount, onMounted, ref } from 'vue'\nimport type { EditorMessages } from '../locale'\n\nexport interface ImageCrop {\n /** Left / top / width / height as fractions (0–1) of the original image. */\n x: number\n y: number\n w: number\n h: number\n /** Width / height of the cropped area in pixels, for the block's aspect ratio. */\n ratio: number\n}\n\nconst props = defineProps<{ src: string, alt?: string, crop: ImageCrop | null, messages: EditorMessages['image'] }>()\nconst emit = defineEmits<{ done: [crop: ImageCrop | null], cancel: [] }>()\n\nconst MIN = 0.05\nconst box = ref({ x: props.crop?.x ?? 0, y: props.crop?.y ?? 0, w: props.crop?.w ?? 1, h: props.crop?.h ?? 1 })\nconst stage = ref<HTMLElement | null>(null)\nconst img = ref<HTMLImageElement | null>(null)\n\ntype Handle = 'move' | 'n' | 's' | 'e' | 'w' | 'ne' | 'nw' | 'se' | 'sw'\nconst HANDLES: Handle[] = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w']\nconst clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v))\n\nfunction start(e: PointerEvent, handle: Handle) {\n const rect = stage.value?.getBoundingClientRect()\n if (!rect) return\n e.preventDefault()\n e.stopPropagation()\n const from = { ...box.value }\n const sx = e.clientX\n const sy = e.clientY\n const move = (ev: PointerEvent) => {\n const dx = (ev.clientX - sx) / rect.width\n const dy = (ev.clientY - sy) / rect.height\n let { x, y, w, h } = from\n if (handle === 'move') {\n x = clamp(from.x + dx, 0, 1 - from.w)\n y = clamp(from.y + dy, 0, 1 - from.h)\n }\n else {\n if (handle.includes('w')) {\n x = clamp(from.x + dx, 0, from.x + from.w - MIN)\n w = from.x + from.w - x\n }\n if (handle.includes('e')) w = clamp(from.w + dx, MIN, 1 - from.x)\n if (handle.includes('n')) {\n y = clamp(from.y + dy, 0, from.y + from.h - MIN)\n h = from.y + from.h - y\n }\n if (handle.includes('s')) h = clamp(from.h + dy, MIN, 1 - from.y)\n }\n box.value = { x, y, w, h }\n }\n const up = () => {\n window.removeEventListener('pointermove', move)\n window.removeEventListener('pointerup', up)\n }\n window.addEventListener('pointermove', move)\n window.addEventListener('pointerup', up)\n}\n\nfunction done() {\n const { x, y, w, h } = box.value\n const full = w > 0.995 && h > 0.995\n const natural = img.value\n const ratio = natural?.naturalWidth && natural.naturalHeight ? (w * natural.naturalWidth) / (h * natural.naturalHeight) : w / h\n emit('done', full ? null : { x, y, w, h, ratio })\n}\nconst reset = () => (box.value = { x: 0, y: 0, w: 1, h: 1 })\n\nfunction onKey(e: KeyboardEvent) {\n if (e.key === 'Escape') emit('cancel')\n else if (e.key === 'Enter') done()\n else return\n e.preventDefault()\n e.stopPropagation()\n}\nonMounted(() => window.addEventListener('keydown', onKey, true))\nonBeforeUnmount(() => window.removeEventListener('keydown', onKey, true))\n\nconst pct = (v: number) => `${v * 100}%`\n</script>\n\n<template>\n <div class=\"me-cropper\">\n <div ref=\"stage\" class=\"me-cropper-stage\">\n <img ref=\"img\" class=\"me-figure-img\" :src=\"src\" :alt=\"alt || ''\" draggable=\"false\">\n <!-- Dimming is clipped to the image; the box and its handles are not, so edge handles stay grabbable. -->\n <div class=\"me-cropper-shade\">\n <div class=\"me-cropper-hole\" :style=\"{ left: pct(box.x), top: pct(box.y), width: pct(box.w), height: pct(box.h) }\" />\n </div>\n <div\n class=\"me-cropper-box\"\n :style=\"{ left: pct(box.x), top: pct(box.y), width: pct(box.w), height: pct(box.h) }\"\n @pointerdown=\"start($event, 'move')\"\n >\n <span v-for=\"h in HANDLES\" :key=\"h\" class=\"me-cropper-handle\" :data-handle=\"h\" @pointerdown=\"start($event, h)\" />\n </div>\n </div>\n <div class=\"me-cropper-actions\">\n <button type=\"button\" class=\"me-btn\" @click=\"reset\">\n {{ messages.cropReset }}\n </button>\n <span class=\"me-cropper-spacer\" />\n <button type=\"button\" class=\"me-btn\" @click=\"emit('cancel')\">\n {{ messages.cropCancel }}\n </button>\n <button type=\"button\" class=\"me-btn me-btn--primary\" @click=\"done\">\n {{ messages.cropDone }}\n </button>\n </div>\n </div>\n</template>\n","<script setup lang=\"ts\">\n/**\n * Full-screen image viewer (Notion's zoom): fit to screen, zoom with the buttons,\n * wheel, +/- or double-click, drag to pan when zoomed, Esc to close.\n */\nimport { Download, Minus, Plus, X } from '@lucide/vue'\nimport { computed, onBeforeUnmount, onMounted, ref } from 'vue'\nimport type { EditorMessages } from '../locale'\n\ndefineProps<{ src: string, alt?: string, messages: EditorMessages['image'], scope: Record<string, unknown> }>()\nconst emit = defineEmits<{ close: [], download: [] }>()\n\nconst MIN = 0.25\nconst MAX = 8\nconst zoom = ref(1)\nconst pan = ref({ x: 0, y: 0 })\nconst percent = computed(() => `${Math.round(zoom.value * 100)}%`)\n\nfunction setZoom(next: number) {\n zoom.value = Math.min(MAX, Math.max(MIN, Math.round(next * 100) / 100))\n if (zoom.value <= 1) pan.value = { x: 0, y: 0 }\n}\nconst zoomIn = () => setZoom(zoom.value * 1.25)\nconst zoomOut = () => setZoom(zoom.value / 1.25)\nconst reset = () => setZoom(1)\n\nfunction onWheel(e: WheelEvent) {\n e.preventDefault()\n setZoom(zoom.value * (e.deltaY < 0 ? 1.1 : 1 / 1.1))\n}\n\nlet drag: { x: number, y: number, px: number, py: number } | null = null\nconst dragging = ref(false)\nfunction onPointerDown(e: PointerEvent) {\n if (zoom.value <= 1) return\n e.preventDefault()\n drag = { x: e.clientX, y: e.clientY, px: pan.value.x, py: pan.value.y }\n dragging.value = true\n ;(e.target as HTMLElement).setPointerCapture(e.pointerId)\n}\nfunction onPointerMove(e: PointerEvent) {\n if (!drag) return\n pan.value = { x: drag.px + e.clientX - drag.x, y: drag.py + e.clientY - drag.y }\n}\nfunction onPointerUp() {\n drag = null\n dragging.value = false\n}\n\nfunction onKey(e: KeyboardEvent) {\n if (e.key === 'Escape') emit('close')\n else if (e.key === '+' || e.key === '=') zoomIn()\n else if (e.key === '-') zoomOut()\n else if (e.key === '0') reset()\n else return\n e.preventDefault()\n e.stopPropagation()\n}\nonMounted(() => window.addEventListener('keydown', onKey, true))\nonBeforeUnmount(() => window.removeEventListener('keydown', onKey, true))\n</script>\n\n<template>\n <Teleport to=\"body\">\n <div v-bind=\"scope\" class=\"me-lightbox\" role=\"dialog\" aria-modal=\"true\" @mousedown.self=\"emit('close')\" @wheel=\"onWheel\">\n <img\n class=\"me-lightbox-img\"\n :class=\"{ 'is-zoomed': zoom > 1, 'is-dragging': dragging }\"\n :src=\"src\"\n :alt=\"alt || ''\"\n draggable=\"false\"\n :style=\"{ transform: `translate(${pan.x}px, ${pan.y}px) scale(${zoom})` }\"\n @dblclick=\"zoom > 1 ? reset() : setZoom(2)\"\n @pointerdown=\"onPointerDown\"\n @pointermove=\"onPointerMove\"\n @pointerup=\"onPointerUp\"\n @pointercancel=\"onPointerUp\"\n >\n <div class=\"me-popover me-toolbar me-lightbox-toolbar\" @mousedown.stop>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"messages.zoomOut\" :disabled=\"zoom <= MIN\" @click=\"zoomOut\">\n <Minus />\n </button>\n <button type=\"button\" class=\"me-tool-btn me-lightbox-percent\" :title=\"messages.zoomReset\" @click=\"reset\">\n {{ percent }}\n </button>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"messages.zoomIn\" :disabled=\"zoom >= MAX\" @click=\"zoomIn\">\n <Plus />\n </button>\n <span class=\"me-toolbar-divider\" />\n <button type=\"button\" class=\"me-tool-btn\" :title=\"messages.download\" @click=\"emit('download')\">\n <Download />\n </button>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"messages.close\" @click=\"emit('close')\">\n <X />\n </button>\n </div>\n </div>\n </Teleport>\n</template>\n","<script setup lang=\"ts\">\n/**\n * Full-screen image viewer (Notion's zoom): fit to screen, zoom with the buttons,\n * wheel, +/- or double-click, drag to pan when zoomed, Esc to close.\n */\nimport { Download, Minus, Plus, X } from '@lucide/vue'\nimport { computed, onBeforeUnmount, onMounted, ref } from 'vue'\nimport type { EditorMessages } from '../locale'\n\ndefineProps<{ src: string, alt?: string, messages: EditorMessages['image'], scope: Record<string, unknown> }>()\nconst emit = defineEmits<{ close: [], download: [] }>()\n\nconst MIN = 0.25\nconst MAX = 8\nconst zoom = ref(1)\nconst pan = ref({ x: 0, y: 0 })\nconst percent = computed(() => `${Math.round(zoom.value * 100)}%`)\n\nfunction setZoom(next: number) {\n zoom.value = Math.min(MAX, Math.max(MIN, Math.round(next * 100) / 100))\n if (zoom.value <= 1) pan.value = { x: 0, y: 0 }\n}\nconst zoomIn = () => setZoom(zoom.value * 1.25)\nconst zoomOut = () => setZoom(zoom.value / 1.25)\nconst reset = () => setZoom(1)\n\nfunction onWheel(e: WheelEvent) {\n e.preventDefault()\n setZoom(zoom.value * (e.deltaY < 0 ? 1.1 : 1 / 1.1))\n}\n\nlet drag: { x: number, y: number, px: number, py: number } | null = null\nconst dragging = ref(false)\nfunction onPointerDown(e: PointerEvent) {\n if (zoom.value <= 1) return\n e.preventDefault()\n drag = { x: e.clientX, y: e.clientY, px: pan.value.x, py: pan.value.y }\n dragging.value = true\n ;(e.target as HTMLElement).setPointerCapture(e.pointerId)\n}\nfunction onPointerMove(e: PointerEvent) {\n if (!drag) return\n pan.value = { x: drag.px + e.clientX - drag.x, y: drag.py + e.clientY - drag.y }\n}\nfunction onPointerUp() {\n drag = null\n dragging.value = false\n}\n\nfunction onKey(e: KeyboardEvent) {\n if (e.key === 'Escape') emit('close')\n else if (e.key === '+' || e.key === '=') zoomIn()\n else if (e.key === '-') zoomOut()\n else if (e.key === '0') reset()\n else return\n e.preventDefault()\n e.stopPropagation()\n}\nonMounted(() => window.addEventListener('keydown', onKey, true))\nonBeforeUnmount(() => window.removeEventListener('keydown', onKey, true))\n</script>\n\n<template>\n <Teleport to=\"body\">\n <div v-bind=\"scope\" class=\"me-lightbox\" role=\"dialog\" aria-modal=\"true\" @mousedown.self=\"emit('close')\" @wheel=\"onWheel\">\n <img\n class=\"me-lightbox-img\"\n :class=\"{ 'is-zoomed': zoom > 1, 'is-dragging': dragging }\"\n :src=\"src\"\n :alt=\"alt || ''\"\n draggable=\"false\"\n :style=\"{ transform: `translate(${pan.x}px, ${pan.y}px) scale(${zoom})` }\"\n @dblclick=\"zoom > 1 ? reset() : setZoom(2)\"\n @pointerdown=\"onPointerDown\"\n @pointermove=\"onPointerMove\"\n @pointerup=\"onPointerUp\"\n @pointercancel=\"onPointerUp\"\n >\n <div class=\"me-popover me-toolbar me-lightbox-toolbar\" @mousedown.stop>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"messages.zoomOut\" :disabled=\"zoom <= MIN\" @click=\"zoomOut\">\n <Minus />\n </button>\n <button type=\"button\" class=\"me-tool-btn me-lightbox-percent\" :title=\"messages.zoomReset\" @click=\"reset\">\n {{ percent }}\n </button>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"messages.zoomIn\" :disabled=\"zoom >= MAX\" @click=\"zoomIn\">\n <Plus />\n </button>\n <span class=\"me-toolbar-divider\" />\n <button type=\"button\" class=\"me-tool-btn\" :title=\"messages.download\" @click=\"emit('download')\">\n <Download />\n </button>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"messages.close\" @click=\"emit('close')\">\n <X />\n </button>\n </div>\n </div>\n </Teleport>\n</template>\n","<script setup lang=\"ts\">\nimport { NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport {\n AlignCenter, AlignLeft, AlignRight, Captions, Check, Copy, Crop, Download, Ellipsis, ExternalLink,\n Image as ImageIcon, Link as LinkIcon, RefreshCw, Trash, Upload, ZoomIn,\n} from '@lucide/vue'\nimport { computed, nextTick, ref } from 'vue'\nimport ImageCropper, { type ImageCrop } from '../components/ImageCropper.vue'\nimport ImageLightbox from '../components/ImageLightbox.vue'\nimport { useClickOutside } from '../composables/useClickOutside'\nimport { useEditable } from '../composables/useEditable'\nimport { useScope } from '../composables/useScope'\nimport { isSameOrigin, isWebUrl, safeUrl } from '../safe-url'\n\nconst props = defineProps(nodeViewProps)\nconst editable = useEditable(props.editor)\n\nconst config = computed(() => props.editor.storage.meiConfig)\nconst m = computed(() => config.value.messages.image)\nconst tab = ref<'upload' | 'link'>('upload')\nconst link = ref('')\nconst error = ref('')\nconst uploading = ref(false)\nconst fileInput = ref<HTMLInputElement | null>(null)\nconst figure = ref<HTMLElement | null>(null)\nconst scope = useScope(() => props.editor)\n\nconst readAsDataUrl = (file: File) => new Promise<string>((resolve, reject) => {\n const reader = new FileReader()\n reader.onload = () => resolve(reader.result as string)\n reader.onerror = () => reject(reader.error)\n reader.readAsDataURL(file)\n})\n\nasync function handleFile(file: File) {\n error.value = ''\n const maxMb = config.value.maxImageSize\n if (!file.type.startsWith('image/')) return (error.value = m.value.notImage)\n if (file.size > maxMb * 1024 * 1024) return (error.value = m.value.tooLarge(maxMb))\n\n uploading.value = true\n try {\n const upload = config.value.uploadImage\n const src = upload ? await upload(file) : await readAsDataUrl(file)\n // A new image starts uncropped.\n props.updateAttributes({ src, alt: file.name, crop: null })\n }\n catch {\n error.value = m.value.uploadFailed\n }\n finally {\n uploading.value = false\n }\n}\n\nfunction onFileChange(e: Event) {\n const file = (e.target as HTMLInputElement).files?.[0]\n if (file) handleFile(file)\n}\n\nfunction onDrop(e: DragEvent) {\n const file = e.dataTransfer?.files?.[0]\n if (!file) return\n e.preventDefault()\n e.stopPropagation()\n handleFile(file)\n}\n\nfunction submitLink() {\n error.value = ''\n try {\n const url = new URL(link.value.trim())\n if (!/^https?:$/.test(url.protocol)) throw new Error('bad protocol')\n props.updateAttributes({ src: url.toString() })\n }\n catch {\n error.value = m.value.invalidLink\n }\n}\n\n// Resize from either side; the image stays centered so both sides move.\nfunction startResize(e: PointerEvent, side: 1 | -1) {\n const parent = figure.value?.parentElement\n if (!parent) return\n e.preventDefault()\n const startX = e.clientX\n const startWidth = props.node.attrs.width as number\n const total = parent.getBoundingClientRect().width\n const move = (ev: PointerEvent) => {\n // Centered images grow on both sides, aligned ones on one.\n const factor = align.value === 'center' ? 2 : 1\n const delta = ((ev.clientX - startX) * side * factor / total) * 100\n props.updateAttributes({ width: Math.round(Math.min(100, Math.max(15, startWidth + delta))) })\n }\n const up = () => {\n window.removeEventListener('pointermove', move)\n window.removeEventListener('pointerup', up)\n }\n window.addEventListener('pointermove', move)\n window.addEventListener('pointerup', up)\n}\n\n// --- Toolbar (like Notion's image menu) ---------------------------------------------\ntype Align = 'left' | 'center' | 'right'\nconst align = computed(() => (props.node.attrs.align ?? 'center') as Align)\nconst ALIGN_ICONS = { left: AlignLeft, center: AlignCenter, right: AlignRight }\nconst crop = computed(() => props.node.attrs.crop as ImageCrop | null)\nconst captionShown = computed(() => props.node.attrs.showCaption ?? !!props.node.attrs.caption)\n/** The image URL if it is safe to load and open (KS-BUG-7: never `javascript:` / `data:text/html`). */\nconst src = computed(() => safeUrl(props.node.attrs.src, 'image'))\n/** A web URL (link actions apply); `isRemote` when it is on another origin (download fetches it). */\nconst isWeb = computed(() => !!src.value && isWebUrl(src.value))\nconst isRemote = computed(() => isWeb.value && !isSameOrigin(src.value!))\n\nconst menu = ref<'align' | 'more' | null>(null)\nconst toolbar = ref<HTMLElement | null>(null)\nuseClickOutside(toolbar, computed(() => menu.value !== null), () => (menu.value = null))\nconst captionInput = ref<HTMLInputElement | null>(null)\nconst cropping = ref(false)\nconst viewing = ref(false)\nconst copied = ref(false)\n\nfunction setAlign(value: Align) {\n props.updateAttributes({ align: value })\n menu.value = null\n}\nfunction toggleCaption() {\n const show = !captionShown.value\n props.updateAttributes({ showCaption: show })\n if (show) nextTick(() => captionInput.value?.focus())\n}\nfunction finishCrop(value: ImageCrop | null) {\n props.updateAttributes({ crop: value })\n cropping.value = false\n}\n\n/** Saves the original file; cross-origin links that refuse fetch open in a new tab. */\nasync function download() {\n const url = src.value\n if (!url) return\n const name = (props.node.attrs.alt as string) || 'image'\n const save = (href: string) => {\n const a = document.createElement('a')\n a.href = href\n a.download = name\n a.click()\n }\n if (!isRemote.value) return save(url)\n try {\n const blob = await (await fetch(url)).blob()\n const objectUrl = URL.createObjectURL(blob)\n save(objectUrl)\n setTimeout(() => URL.revokeObjectURL(objectUrl), 1000)\n }\n catch {\n window.open(url, '_blank', 'noopener')\n }\n}\n\nasync function copyLink() {\n if (!src.value) return\n await navigator.clipboard?.writeText(new URL(src.value, location.href).href)\n copied.value = true\n setTimeout(() => (copied.value = false), 1500)\n menu.value = null\n}\nfunction replace() {\n menu.value = null\n fileInput.value?.click()\n}\nfunction openOriginal() {\n menu.value = null\n if (src.value) window.open(src.value, '_blank', 'noopener')\n}\nfunction remove() {\n menu.value = null\n props.deleteNode()\n}\n\n// Cropped view: the frame takes the crop's aspect ratio and the image is offset inside it.\nconst cropStyle = computed(() => {\n const c = crop.value\n if (!c) return undefined\n return {\n width: `${100 / c.w}%`,\n left: `${(-c.x / c.w) * 100}%`,\n top: `${(-c.y / c.h) * 100}%`,\n }\n})\n</script>\n\n<template>\n <NodeViewWrapper class=\"me-media\" :class=\"{ 'is-readonly-empty': !editable && !node.attrs.src }\">\n <div v-if=\"!node.attrs.src\" class=\"me-media-empty\" contenteditable=\"false\" @dragover.prevent @drop=\"onDrop\">\n <div class=\"me-tabs\">\n <button\n v-for=\"t in (['upload', 'link'] as const)\"\n :key=\"t\"\n type=\"button\"\n class=\"me-tab\"\n :class=\"{ 'is-active': tab === t }\"\n @click=\"tab = t\"\n >\n <component :is=\"t === 'upload' ? Upload : LinkIcon\" />\n {{ t === 'upload' ? m.upload : m.link }}\n </button>\n </div>\n <div v-if=\"tab === 'upload'\" class=\"me-media-body\">\n <button type=\"button\" class=\"me-btn\" :disabled=\"uploading\" @click=\"fileInput?.click()\">\n <ImageIcon /> {{ uploading ? m.uploading : m.choose }}\n </button>\n <p class=\"me-hint\">\n {{ m.dropHint(config.maxImageSize) }}\n </p>\n <input ref=\"fileInput\" type=\"file\" accept=\"image/*\" hidden @change=\"onFileChange\">\n </div>\n <form v-else class=\"me-inline-form\" @submit.prevent=\"submitLink\">\n <input v-model=\"link\" class=\"me-input\" placeholder=\"https://...\" @keydown.stop>\n <button type=\"submit\" class=\"me-btn me-btn--primary\">\n {{ m.insert }}\n </button>\n </form>\n <p v-if=\"error\" class=\"me-error\">\n {{ error }}\n </p>\n </div>\n\n <figure\n v-else\n ref=\"figure\"\n class=\"me-figure\"\n :class=\"`me-figure--${align}`\"\n :style=\"{ width: `${node.attrs.width}%` }\"\n >\n <ImageCropper\n v-if=\"cropping && src\"\n :src=\"src\"\n :alt=\"node.attrs.alt\"\n :crop=\"crop\"\n :messages=\"m\"\n @done=\"finishCrop\"\n @cancel=\"cropping = false\"\n />\n <div\n v-else\n class=\"me-figure-frame\"\n :class=\"{ 'is-selected': selected, 'is-menu-open': menu !== null }\"\n >\n <!-- Only this layer clips (for crops), so the toolbar's menus can overflow the frame. -->\n <div class=\"me-figure-media\" :class=\"{ 'is-cropped': !!crop }\" :style=\"crop ? { aspectRatio: String(crop.ratio) } : undefined\">\n <img v-if=\"src\" :src=\"src\" :alt=\"node.attrs.alt || ''\" class=\"me-figure-img\" :style=\"cropStyle\" draggable=\"false\" @dblclick=\"viewing = true\">\n <p v-else class=\"me-error me-image-blocked\">\n {{ m.invalidLink }}\n </p>\n </div>\n\n <div ref=\"toolbar\" class=\"me-popover me-toolbar me-image-toolbar\" contenteditable=\"false\" @mousedown.stop>\n <template v-if=\"editable\">\n <div class=\"me-image-menu-anchor\">\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.align\" @click=\"menu = menu === 'align' ? null : 'align'\">\n <component :is=\"ALIGN_ICONS[align]\" />\n </button>\n <div v-if=\"menu === 'align'\" class=\"me-popover me-menu me-image-menu\">\n <button v-for=\"a in (['left', 'center', 'right'] as const)\" :key=\"a\" type=\"button\" class=\"me-menu-item\" @click=\"setAlign(a)\">\n <span class=\"me-menu-icon\"><component :is=\"ALIGN_ICONS[a]\" /></span>\n <span class=\"me-menu-title me-menu-text\">{{ m.alignments[a] }}</span>\n <Check v-if=\"align === a\" class=\"me-menu-check\" />\n </button>\n </div>\n </div>\n <button type=\"button\" class=\"me-tool-btn\" :class=\"{ 'is-active': captionShown }\" :title=\"m.captionToggle\" @click=\"toggleCaption\">\n <Captions />\n </button>\n <button type=\"button\" class=\"me-tool-btn\" :class=\"{ 'is-active': !!crop }\" :title=\"m.crop\" @click=\"cropping = true\">\n <Crop />\n </button>\n </template>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.zoom\" @click=\"viewing = true\">\n <ZoomIn />\n </button>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.download\" @click=\"download\">\n <Download />\n </button>\n <div class=\"me-image-menu-anchor\">\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.more\" @click=\"menu = menu === 'more' ? null : 'more'\">\n <Ellipsis />\n </button>\n <div v-if=\"menu === 'more'\" class=\"me-popover me-menu me-image-menu\">\n <button v-if=\"editable\" type=\"button\" class=\"me-menu-item\" @click=\"replace\">\n <span class=\"me-menu-icon\"><RefreshCw /></span>\n <span class=\"me-menu-title me-menu-text\">{{ m.replace }}</span>\n </button>\n <button v-if=\"isWeb\" type=\"button\" class=\"me-menu-item\" @click=\"copyLink\">\n <span class=\"me-menu-icon\"><component :is=\"copied ? Check : Copy\" /></span>\n <span class=\"me-menu-title me-menu-text\">{{ copied ? m.linkCopied : m.copyLink }}</span>\n </button>\n <button v-if=\"isWeb\" type=\"button\" class=\"me-menu-item\" @click=\"openOriginal\">\n <span class=\"me-menu-icon\"><ExternalLink /></span>\n <span class=\"me-menu-title me-menu-text\">{{ m.original }}</span>\n </button>\n <button v-if=\"editable\" type=\"button\" class=\"me-menu-item is-danger\" @click=\"remove\">\n <span class=\"me-menu-icon\"><Trash /></span>\n <span class=\"me-menu-title me-menu-text\">{{ m.delete }}</span>\n </button>\n </div>\n </div>\n </div>\n\n <template v-if=\"editable\">\n <span class=\"me-resize-handle me-resize-handle--left\" @pointerdown=\"startResize($event, -1)\" />\n <span class=\"me-resize-handle me-resize-handle--right\" @pointerdown=\"startResize($event, 1)\" />\n </template>\n </div>\n <input\n v-if=\"captionShown && !cropping\"\n ref=\"captionInput\"\n class=\"me-caption\"\n :value=\"node.attrs.caption\"\n :readonly=\"!editable\"\n :placeholder=\"editable ? m.caption : ''\"\n @input=\"updateAttributes({ caption: ($event.target as HTMLInputElement).value })\"\n @keydown.stop\n >\n <input ref=\"fileInput\" type=\"file\" accept=\"image/*\" hidden @change=\"onFileChange\">\n <p v-if=\"error\" class=\"me-error\">\n {{ error }}\n </p>\n </figure>\n\n <ImageLightbox\n v-if=\"viewing && src\"\n :src=\"src\"\n :alt=\"node.attrs.alt\"\n :messages=\"m\"\n :scope=\"scope\"\n @close=\"viewing = false\"\n @download=\"download\"\n />\n </NodeViewWrapper>\n</template>\n","<script setup lang=\"ts\">\nimport { NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport {\n AlignCenter, AlignLeft, AlignRight, Captions, Check, Copy, Crop, Download, Ellipsis, ExternalLink,\n Image as ImageIcon, Link as LinkIcon, RefreshCw, Trash, Upload, ZoomIn,\n} from '@lucide/vue'\nimport { computed, nextTick, ref } from 'vue'\nimport ImageCropper, { type ImageCrop } from '../components/ImageCropper.vue'\nimport ImageLightbox from '../components/ImageLightbox.vue'\nimport { useClickOutside } from '../composables/useClickOutside'\nimport { useEditable } from '../composables/useEditable'\nimport { useScope } from '../composables/useScope'\nimport { isSameOrigin, isWebUrl, safeUrl } from '../safe-url'\n\nconst props = defineProps(nodeViewProps)\nconst editable = useEditable(props.editor)\n\nconst config = computed(() => props.editor.storage.meiConfig)\nconst m = computed(() => config.value.messages.image)\nconst tab = ref<'upload' | 'link'>('upload')\nconst link = ref('')\nconst error = ref('')\nconst uploading = ref(false)\nconst fileInput = ref<HTMLInputElement | null>(null)\nconst figure = ref<HTMLElement | null>(null)\nconst scope = useScope(() => props.editor)\n\nconst readAsDataUrl = (file: File) => new Promise<string>((resolve, reject) => {\n const reader = new FileReader()\n reader.onload = () => resolve(reader.result as string)\n reader.onerror = () => reject(reader.error)\n reader.readAsDataURL(file)\n})\n\nasync function handleFile(file: File) {\n error.value = ''\n const maxMb = config.value.maxImageSize\n if (!file.type.startsWith('image/')) return (error.value = m.value.notImage)\n if (file.size > maxMb * 1024 * 1024) return (error.value = m.value.tooLarge(maxMb))\n\n uploading.value = true\n try {\n const upload = config.value.uploadImage\n const src = upload ? await upload(file) : await readAsDataUrl(file)\n // A new image starts uncropped.\n props.updateAttributes({ src, alt: file.name, crop: null })\n }\n catch {\n error.value = m.value.uploadFailed\n }\n finally {\n uploading.value = false\n }\n}\n\nfunction onFileChange(e: Event) {\n const file = (e.target as HTMLInputElement).files?.[0]\n if (file) handleFile(file)\n}\n\nfunction onDrop(e: DragEvent) {\n const file = e.dataTransfer?.files?.[0]\n if (!file) return\n e.preventDefault()\n e.stopPropagation()\n handleFile(file)\n}\n\nfunction submitLink() {\n error.value = ''\n try {\n const url = new URL(link.value.trim())\n if (!/^https?:$/.test(url.protocol)) throw new Error('bad protocol')\n props.updateAttributes({ src: url.toString() })\n }\n catch {\n error.value = m.value.invalidLink\n }\n}\n\n// Resize from either side; the image stays centered so both sides move.\nfunction startResize(e: PointerEvent, side: 1 | -1) {\n const parent = figure.value?.parentElement\n if (!parent) return\n e.preventDefault()\n const startX = e.clientX\n const startWidth = props.node.attrs.width as number\n const total = parent.getBoundingClientRect().width\n const move = (ev: PointerEvent) => {\n // Centered images grow on both sides, aligned ones on one.\n const factor = align.value === 'center' ? 2 : 1\n const delta = ((ev.clientX - startX) * side * factor / total) * 100\n props.updateAttributes({ width: Math.round(Math.min(100, Math.max(15, startWidth + delta))) })\n }\n const up = () => {\n window.removeEventListener('pointermove', move)\n window.removeEventListener('pointerup', up)\n }\n window.addEventListener('pointermove', move)\n window.addEventListener('pointerup', up)\n}\n\n// --- Toolbar (like Notion's image menu) ---------------------------------------------\ntype Align = 'left' | 'center' | 'right'\nconst align = computed(() => (props.node.attrs.align ?? 'center') as Align)\nconst ALIGN_ICONS = { left: AlignLeft, center: AlignCenter, right: AlignRight }\nconst crop = computed(() => props.node.attrs.crop as ImageCrop | null)\nconst captionShown = computed(() => props.node.attrs.showCaption ?? !!props.node.attrs.caption)\n/** The image URL if it is safe to load and open (KS-BUG-7: never `javascript:` / `data:text/html`). */\nconst src = computed(() => safeUrl(props.node.attrs.src, 'image'))\n/** A web URL (link actions apply); `isRemote` when it is on another origin (download fetches it). */\nconst isWeb = computed(() => !!src.value && isWebUrl(src.value))\nconst isRemote = computed(() => isWeb.value && !isSameOrigin(src.value!))\n\nconst menu = ref<'align' | 'more' | null>(null)\nconst toolbar = ref<HTMLElement | null>(null)\nuseClickOutside(toolbar, computed(() => menu.value !== null), () => (menu.value = null))\nconst captionInput = ref<HTMLInputElement | null>(null)\nconst cropping = ref(false)\nconst viewing = ref(false)\nconst copied = ref(false)\n\nfunction setAlign(value: Align) {\n props.updateAttributes({ align: value })\n menu.value = null\n}\nfunction toggleCaption() {\n const show = !captionShown.value\n props.updateAttributes({ showCaption: show })\n if (show) nextTick(() => captionInput.value?.focus())\n}\nfunction finishCrop(value: ImageCrop | null) {\n props.updateAttributes({ crop: value })\n cropping.value = false\n}\n\n/** Saves the original file; cross-origin links that refuse fetch open in a new tab. */\nasync function download() {\n const url = src.value\n if (!url) return\n const name = (props.node.attrs.alt as string) || 'image'\n const save = (href: string) => {\n const a = document.createElement('a')\n a.href = href\n a.download = name\n a.click()\n }\n if (!isRemote.value) return save(url)\n try {\n const blob = await (await fetch(url)).blob()\n const objectUrl = URL.createObjectURL(blob)\n save(objectUrl)\n setTimeout(() => URL.revokeObjectURL(objectUrl), 1000)\n }\n catch {\n window.open(url, '_blank', 'noopener')\n }\n}\n\nasync function copyLink() {\n if (!src.value) return\n await navigator.clipboard?.writeText(new URL(src.value, location.href).href)\n copied.value = true\n setTimeout(() => (copied.value = false), 1500)\n menu.value = null\n}\nfunction replace() {\n menu.value = null\n fileInput.value?.click()\n}\nfunction openOriginal() {\n menu.value = null\n if (src.value) window.open(src.value, '_blank', 'noopener')\n}\nfunction remove() {\n menu.value = null\n props.deleteNode()\n}\n\n// Cropped view: the frame takes the crop's aspect ratio and the image is offset inside it.\nconst cropStyle = computed(() => {\n const c = crop.value\n if (!c) return undefined\n return {\n width: `${100 / c.w}%`,\n left: `${(-c.x / c.w) * 100}%`,\n top: `${(-c.y / c.h) * 100}%`,\n }\n})\n</script>\n\n<template>\n <NodeViewWrapper class=\"me-media\" :class=\"{ 'is-readonly-empty': !editable && !node.attrs.src }\">\n <div v-if=\"!node.attrs.src\" class=\"me-media-empty\" contenteditable=\"false\" @dragover.prevent @drop=\"onDrop\">\n <div class=\"me-tabs\">\n <button\n v-for=\"t in (['upload', 'link'] as const)\"\n :key=\"t\"\n type=\"button\"\n class=\"me-tab\"\n :class=\"{ 'is-active': tab === t }\"\n @click=\"tab = t\"\n >\n <component :is=\"t === 'upload' ? Upload : LinkIcon\" />\n {{ t === 'upload' ? m.upload : m.link }}\n </button>\n </div>\n <div v-if=\"tab === 'upload'\" class=\"me-media-body\">\n <button type=\"button\" class=\"me-btn\" :disabled=\"uploading\" @click=\"fileInput?.click()\">\n <ImageIcon /> {{ uploading ? m.uploading : m.choose }}\n </button>\n <p class=\"me-hint\">\n {{ m.dropHint(config.maxImageSize) }}\n </p>\n <input ref=\"fileInput\" type=\"file\" accept=\"image/*\" hidden @change=\"onFileChange\">\n </div>\n <form v-else class=\"me-inline-form\" @submit.prevent=\"submitLink\">\n <input v-model=\"link\" class=\"me-input\" placeholder=\"https://...\" @keydown.stop>\n <button type=\"submit\" class=\"me-btn me-btn--primary\">\n {{ m.insert }}\n </button>\n </form>\n <p v-if=\"error\" class=\"me-error\">\n {{ error }}\n </p>\n </div>\n\n <figure\n v-else\n ref=\"figure\"\n class=\"me-figure\"\n :class=\"`me-figure--${align}`\"\n :style=\"{ width: `${node.attrs.width}%` }\"\n >\n <ImageCropper\n v-if=\"cropping && src\"\n :src=\"src\"\n :alt=\"node.attrs.alt\"\n :crop=\"crop\"\n :messages=\"m\"\n @done=\"finishCrop\"\n @cancel=\"cropping = false\"\n />\n <div\n v-else\n class=\"me-figure-frame\"\n :class=\"{ 'is-selected': selected, 'is-menu-open': menu !== null }\"\n >\n <!-- Only this layer clips (for crops), so the toolbar's menus can overflow the frame. -->\n <div class=\"me-figure-media\" :class=\"{ 'is-cropped': !!crop }\" :style=\"crop ? { aspectRatio: String(crop.ratio) } : undefined\">\n <img v-if=\"src\" :src=\"src\" :alt=\"node.attrs.alt || ''\" class=\"me-figure-img\" :style=\"cropStyle\" draggable=\"false\" @dblclick=\"viewing = true\">\n <p v-else class=\"me-error me-image-blocked\">\n {{ m.invalidLink }}\n </p>\n </div>\n\n <div ref=\"toolbar\" class=\"me-popover me-toolbar me-image-toolbar\" contenteditable=\"false\" @mousedown.stop>\n <template v-if=\"editable\">\n <div class=\"me-image-menu-anchor\">\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.align\" @click=\"menu = menu === 'align' ? null : 'align'\">\n <component :is=\"ALIGN_ICONS[align]\" />\n </button>\n <div v-if=\"menu === 'align'\" class=\"me-popover me-menu me-image-menu\">\n <button v-for=\"a in (['left', 'center', 'right'] as const)\" :key=\"a\" type=\"button\" class=\"me-menu-item\" @click=\"setAlign(a)\">\n <span class=\"me-menu-icon\"><component :is=\"ALIGN_ICONS[a]\" /></span>\n <span class=\"me-menu-title me-menu-text\">{{ m.alignments[a] }}</span>\n <Check v-if=\"align === a\" class=\"me-menu-check\" />\n </button>\n </div>\n </div>\n <button type=\"button\" class=\"me-tool-btn\" :class=\"{ 'is-active': captionShown }\" :title=\"m.captionToggle\" @click=\"toggleCaption\">\n <Captions />\n </button>\n <button type=\"button\" class=\"me-tool-btn\" :class=\"{ 'is-active': !!crop }\" :title=\"m.crop\" @click=\"cropping = true\">\n <Crop />\n </button>\n </template>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.zoom\" @click=\"viewing = true\">\n <ZoomIn />\n </button>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.download\" @click=\"download\">\n <Download />\n </button>\n <div class=\"me-image-menu-anchor\">\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.more\" @click=\"menu = menu === 'more' ? null : 'more'\">\n <Ellipsis />\n </button>\n <div v-if=\"menu === 'more'\" class=\"me-popover me-menu me-image-menu\">\n <button v-if=\"editable\" type=\"button\" class=\"me-menu-item\" @click=\"replace\">\n <span class=\"me-menu-icon\"><RefreshCw /></span>\n <span class=\"me-menu-title me-menu-text\">{{ m.replace }}</span>\n </button>\n <button v-if=\"isWeb\" type=\"button\" class=\"me-menu-item\" @click=\"copyLink\">\n <span class=\"me-menu-icon\"><component :is=\"copied ? Check : Copy\" /></span>\n <span class=\"me-menu-title me-menu-text\">{{ copied ? m.linkCopied : m.copyLink }}</span>\n </button>\n <button v-if=\"isWeb\" type=\"button\" class=\"me-menu-item\" @click=\"openOriginal\">\n <span class=\"me-menu-icon\"><ExternalLink /></span>\n <span class=\"me-menu-title me-menu-text\">{{ m.original }}</span>\n </button>\n <button v-if=\"editable\" type=\"button\" class=\"me-menu-item is-danger\" @click=\"remove\">\n <span class=\"me-menu-icon\"><Trash /></span>\n <span class=\"me-menu-title me-menu-text\">{{ m.delete }}</span>\n </button>\n </div>\n </div>\n </div>\n\n <template v-if=\"editable\">\n <span class=\"me-resize-handle me-resize-handle--left\" @pointerdown=\"startResize($event, -1)\" />\n <span class=\"me-resize-handle me-resize-handle--right\" @pointerdown=\"startResize($event, 1)\" />\n </template>\n </div>\n <input\n v-if=\"captionShown && !cropping\"\n ref=\"captionInput\"\n class=\"me-caption\"\n :value=\"node.attrs.caption\"\n :readonly=\"!editable\"\n :placeholder=\"editable ? m.caption : ''\"\n @input=\"updateAttributes({ caption: ($event.target as HTMLInputElement).value })\"\n @keydown.stop\n >\n <input ref=\"fileInput\" type=\"file\" accept=\"image/*\" hidden @change=\"onFileChange\">\n <p v-if=\"error\" class=\"me-error\">\n {{ error }}\n </p>\n </figure>\n\n <ImageLightbox\n v-if=\"viewing && src\"\n :src=\"src\"\n :alt=\"node.attrs.alt\"\n :messages=\"m\"\n :scope=\"scope\"\n @close=\"viewing = false\"\n @download=\"download\"\n />\n </NodeViewWrapper>\n</template>\n","import Image from '@tiptap/extension-image'\nimport { blockNodeView } from '../nodeviews/renderer'\nimport ImageView from '../nodeviews/ImageView.vue'\nimport { safeUrl } from '../safe-url'\n\nexport const ImageBlock = Image.extend({\n draggable: true,\n\n addAttributes() {\n const parent: Record<string, object> = this.parent?.() ?? {}\n return {\n ...parent,\n // Pasted / exported HTML never carries a `javascript:` or `data:text/html` source (KS-BUG-7).\n src: {\n ...parent.src,\n parseHTML: (el: HTMLElement) => safeUrl(el.getAttribute('src'), 'image'),\n renderHTML: (attrs: Record<string, unknown>) => ({ src: safeUrl(attrs.src, 'image') }),\n },\n width: {\n default: 100,\n parseHTML: el => Number(el.getAttribute('data-width')) || 100,\n renderHTML: attrs => ({ 'data-width': attrs.width }),\n },\n caption: {\n default: '',\n parseHTML: el => el.getAttribute('data-caption') || '',\n renderHTML: attrs => (attrs.caption ? { 'data-caption': attrs.caption } : {}),\n },\n /** Caption row shown (Notion hides it until \"Caption\" is clicked). Older docs: shown when there's text. */\n showCaption: {\n default: null,\n parseHTML: el => (el.hasAttribute('data-show-caption') ? el.getAttribute('data-show-caption') === 'true' : null),\n renderHTML: attrs => (attrs.showCaption === null ? {} : { 'data-show-caption': String(attrs.showCaption) }),\n },\n align: {\n default: 'center',\n parseHTML: el => el.getAttribute('data-align') || 'center',\n renderHTML: attrs => (attrs.align && attrs.align !== 'center' ? { 'data-align': attrs.align } : {}),\n },\n /** Non-destructive crop, see ImageCrop. */\n crop: {\n default: null,\n parseHTML: (el) => {\n try {\n return JSON.parse(el.getAttribute('data-crop') ?? 'null')\n }\n catch {\n return null\n }\n },\n renderHTML: attrs => (attrs.crop ? { 'data-crop': JSON.stringify(attrs.crop) } : {}),\n },\n }\n },\n\n addNodeView() {\n return blockNodeView(ImageView)\n },\n}).configure({ inline: false, allowBase64: true })\n","import { Image, Video } from '@lucide/vue'\nimport { isNode } from '../block-items'\nimport { defineBlock } from '../define-block'\nimport { Embed } from '../extensions/embed'\nimport { ImageBlock } from '../extensions/image-block'\n\n/** Images: upload (see the `uploadImage` prop) or paste a link. */\nexport const image = defineBlock({\n name: 'image',\n nodes: ['image'],\n extensions: () => [ImageBlock],\n items: () => [{\n id: 'image',\n icon: Image,\n group: 'media',\n keywords: ['image', 'photo', 'picture', 'img', 'anh', 'hinh anh', '图片', '图像'],\n insert: c => c.insertContent({ type: 'image', attrs: { src: null } }),\n matches: isNode('image'),\n }],\n})\n\nexport const embed = defineBlock({\n name: 'embed',\n nodes: ['embed'],\n extensions: () => [Embed],\n items: () => [{\n id: 'embed',\n icon: Video,\n group: 'media',\n keywords: ['video', 'youtube', 'embed', 'iframe', 'vimeo', 'nhung', '视频', '嵌入'],\n insert: c => c.setEmbed({ src: null }),\n matches: isNode('embed'),\n }],\n})\n","<script setup lang=\"ts\">\nimport type { Editor } from '@tiptap/core'\nimport { nextTick, ref, watch } from 'vue'\nimport { useScope } from '../composables/useScope'\nimport type { EmojiEntry } from '../emoji-data'\nimport { usePointerMoved } from '../composables/usePointerMoved'\n\nconst props = defineProps<{ editor: Editor, items: EmojiEntry[], command: (item: EmojiEntry) => void }>()\nconst scope = useScope(() => props.editor)\nconst selected = ref(0)\nconst root = ref<HTMLElement | null>(null)\nconst COLS = 8\n\nwatch(() => props.items, () => (selected.value = 0))\nwatch(selected, async (i) => {\n await nextTick()\n root.value?.querySelector(`[data-index=\"${i}\"]`)?.scrollIntoView({ block: 'nearest' })\n})\n\nfunction onKeyDown(e: KeyboardEvent) {\n const n = props.items.length\n if (!n) return false\n const step = { ArrowRight: 1, ArrowLeft: -1, ArrowDown: COLS, ArrowUp: -COLS }[e.key]\n if (step) {\n selected.value = Math.min(n - 1, Math.max(0, selected.value + step))\n return true\n }\n if (e.key === 'Enter' || e.key === 'Tab') {\n const item = props.items[selected.value]\n if (item) props.command(item)\n return true\n }\n return false\n}\ndefineExpose({ onKeyDown })\n\n// Hover selects a row only after a real pointer move (KS-BUG-3).\nconst pointerMoved = usePointerMoved()\n</script>\n\n<template>\n <!-- Always render a root element (the popup positions it); hide it while empty. -->\n <div ref=\"root\" v-bind=\"scope\" class=\"me-popover me-emoji-menu\" :hidden=\"!items.length\">\n <div class=\"me-emoji-menu-grid\">\n <button\n v-for=\"(e, i) in items\"\n :key=\"e.unicode\"\n type=\"button\"\n class=\"me-emoji\"\n :class=\"{ 'is-active': i === selected }\"\n :data-index=\"i\"\n :title=\"e.label\"\n @mousemove=\"pointerMoved($event) && (selected = i)\"\n @mousedown.prevent=\"command(e)\"\n >\n {{ e.unicode }}\n </button>\n </div>\n <div class=\"me-menu-desc me-emoji-menu-label\">\n {{ items[selected]?.label }}\n </div>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport type { Editor } from '@tiptap/core'\nimport { nextTick, ref, watch } from 'vue'\nimport { useScope } from '../composables/useScope'\nimport type { EmojiEntry } from '../emoji-data'\nimport { usePointerMoved } from '../composables/usePointerMoved'\n\nconst props = defineProps<{ editor: Editor, items: EmojiEntry[], command: (item: EmojiEntry) => void }>()\nconst scope = useScope(() => props.editor)\nconst selected = ref(0)\nconst root = ref<HTMLElement | null>(null)\nconst COLS = 8\n\nwatch(() => props.items, () => (selected.value = 0))\nwatch(selected, async (i) => {\n await nextTick()\n root.value?.querySelector(`[data-index=\"${i}\"]`)?.scrollIntoView({ block: 'nearest' })\n})\n\nfunction onKeyDown(e: KeyboardEvent) {\n const n = props.items.length\n if (!n) return false\n const step = { ArrowRight: 1, ArrowLeft: -1, ArrowDown: COLS, ArrowUp: -COLS }[e.key]\n if (step) {\n selected.value = Math.min(n - 1, Math.max(0, selected.value + step))\n return true\n }\n if (e.key === 'Enter' || e.key === 'Tab') {\n const item = props.items[selected.value]\n if (item) props.command(item)\n return true\n }\n return false\n}\ndefineExpose({ onKeyDown })\n\n// Hover selects a row only after a real pointer move (KS-BUG-3).\nconst pointerMoved = usePointerMoved()\n</script>\n\n<template>\n <!-- Always render a root element (the popup positions it); hide it while empty. -->\n <div ref=\"root\" v-bind=\"scope\" class=\"me-popover me-emoji-menu\" :hidden=\"!items.length\">\n <div class=\"me-emoji-menu-grid\">\n <button\n v-for=\"(e, i) in items\"\n :key=\"e.unicode\"\n type=\"button\"\n class=\"me-emoji\"\n :class=\"{ 'is-active': i === selected }\"\n :data-index=\"i\"\n :title=\"e.label\"\n @mousemove=\"pointerMoved($event) && (selected = i)\"\n @mousedown.prevent=\"command(e)\"\n >\n {{ e.unicode }}\n </button>\n </div>\n <div class=\"me-menu-desc me-emoji-menu-label\">\n {{ items[selected]?.label }}\n </div>\n </div>\n</template>\n","/** Emoji search data, loaded on first use (≈600KB per locale, split into its own chunk). */\nexport interface EmojiEntry { unicode: string, label: string, terms: string[] }\n\nconst normalize = (s: string) => s.normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/đ/g, 'd').toLowerCase()\n\ninterface Compact { hexcode: string, label: string, unicode: string, tags?: string[], group?: number }\nconst LOCALES: Record<string, () => Promise<{ default: Compact[] }>> = {\n vi: () => import('emojibase-data/vi/compact.json'),\n zh: () => import('emojibase-data/zh/compact.json'),\n}\n\nlet cache: Promise<EmojiEntry[]> | null = null\nlet cachedLocale = ''\n\n/** English labels + GitHub shortcodes always; plus labels/tags in `locale` when available. */\nexport function loadEmojis(locale: string): Promise<EmojiEntry[]> {\n if (cache && cachedLocale === locale) return cache\n cachedLocale = locale\n cache = Promise.all([\n import('emojibase-data/en/compact.json'),\n import('emojibase-data/en/shortcodes/github.json'),\n LOCALES[locale]?.() ?? Promise.resolve({ default: [] as Compact[] }),\n ]).then(([en, shortcodes, local]) => {\n const localByHex = new Map(local.default.map(e => [e.hexcode, e]))\n const codes = shortcodes.default as Record<string, string | string[]>\n return (en.default as Compact[])\n // Skip regional indicators / components (no group).\n .filter(e => e.group !== undefined && e.group !== 2)\n .map((e) => {\n const loc = localByHex.get(e.hexcode)\n const sc = codes[e.hexcode]\n return {\n unicode: e.unicode,\n label: loc?.label ?? e.label,\n terms: [e.label, ...(e.tags ?? []), ...(loc ? [loc.label, ...(loc.tags ?? [])] : []), ...(Array.isArray(sc) ? sc : sc ? [sc] : [])].map(normalize),\n }\n })\n })\n return cache\n}\n\nexport function searchEmojis(list: EmojiEntry[], query: string, limit = 40): EmojiEntry[] {\n const q = normalize(query.trim())\n if (!q) return list.slice(0, limit)\n const starts: EmojiEntry[] = []\n const contains: EmojiEntry[] = []\n for (const e of list) {\n if (e.terms.some(t => t.startsWith(q))) starts.push(e)\n else if (e.terms.some(t => t.includes(q))) contains.push(e)\n if (starts.length >= limit) break\n }\n return [...starts, ...contains].slice(0, limit)\n}\n","import { Extension } from '@tiptap/core'\nimport { PluginKey } from '@tiptap/pm/state'\nimport Suggestion from '@tiptap/suggestion'\nimport EmojiMenu from '../components/EmojiMenu.vue'\nimport { type EmojiEntry, loadEmojis, searchEmojis } from '../emoji-data'\nimport { suggestionRenderer } from './suggestion-renderer'\n\nexport const emojiPluginKey = new PluginKey('emoji')\n\n/** Type `:` + a word (e.g. `:smile`, `:cười`) to insert an emoji as text. */\nexport const EmojiSuggestion = Extension.create({\n name: 'emojiSuggestion',\n\n addProseMirrorPlugins() {\n return [\n Suggestion<EmojiEntry>({\n editor: this.editor,\n pluginKey: emojiPluginKey,\n char: ':',\n allow: ({ state, range }) => !state.doc.resolve(range.from).parent.type.spec.code,\n items: async ({ query, editor }) => {\n // Wait for 2 letters so \"10:30\" or \"Note:\" doesn't pop the menu.\n if (query.length < 2) return []\n return searchEmojis(await loadEmojis(editor.storage.meiConfig.locale), query, 48)\n },\n command: ({ editor, range, props }) => {\n editor.chain().focus().insertContentAt(range, `${props.unicode} `).run()\n },\n // The menu hides itself while there are no matches; a space ends the suggestion.\n render: suggestionRenderer<EmojiEntry>(EmojiMenu, emojiPluginKey),\n }),\n ]\n },\n})\n","<script setup lang=\"ts\">\nimport { NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport { AudioLines, Download, File as FileIcon, Film, Link as LinkIcon, Upload } from '@lucide/vue'\nimport { computed, ref } from 'vue'\nimport { useEditable } from '../composables/useEditable'\nimport { safeUrl } from '../safe-url'\nimport type { FileBlockOptions, FileKind } from '../extensions/file-block'\n\nconst props = defineProps(nodeViewProps)\nconst editable = useEditable(props.editor)\n\nconst options = computed(() => props.extension.options as FileBlockOptions)\nconst kind = computed(() => (props.node.attrs.kind ?? 'file') as FileKind)\nconst m = computed(() => props.editor.storage.meiConfig.messages.file)\nconst tab = ref<'upload' | 'link'>('upload')\nconst link = ref('')\nconst error = ref('')\nconst uploading = ref(false)\nconst fileInput = ref<HTMLInputElement | null>(null)\n\n// Web, blob, data and same-origin paths (uploads like `/api/v1/files/<id>`, KS-BUG-15);\n// never `javascript:`: pasted content could carry such links.\nconst safeSrc = computed(() => safeUrl(props.node.attrs.src, 'any'))\nconst accept = computed(() => ({ file: '', audio: 'audio/*', video: 'video/*' })[kind.value])\nconst icon = computed(() => ({ file: FileIcon, audio: AudioLines, video: Film })[kind.value])\nconst title = computed(() => ({ file: m.value.chooseFile, audio: m.value.chooseAudio, video: m.value.chooseVideo })[kind.value])\n\nconst readAsDataUrl = (file: File) => new Promise<string>((resolve, reject) => {\n const reader = new FileReader()\n reader.onload = () => resolve(reader.result as string)\n reader.onerror = () => reject(reader.error)\n reader.readAsDataURL(file)\n})\n\nasync function handleFile(file: File) {\n error.value = ''\n if (kind.value !== 'file' && !file.type.startsWith(`${kind.value}/`)) return (error.value = m.value.wrongType)\n if (file.size > options.value.maxSize * 1024 * 1024) return (error.value = m.value.tooLarge(options.value.maxSize))\n uploading.value = true\n try {\n const src = options.value.upload ? await options.value.upload(file, kind.value) : await readAsDataUrl(file)\n props.updateAttributes({ src, name: file.name, size: file.size, mime: file.type })\n }\n catch {\n error.value = m.value.uploadFailed\n }\n finally {\n uploading.value = false\n }\n}\n\nfunction onDrop(e: DragEvent) {\n const file = e.dataTransfer?.files?.[0]\n if (!file) return\n e.preventDefault()\n e.stopPropagation()\n handleFile(file)\n}\n\nfunction submitLink() {\n try {\n const url = new URL(link.value.trim())\n if (!/^https?:$/.test(url.protocol)) throw new Error('protocol')\n props.updateAttributes({ src: url.toString(), name: decodeURIComponent(url.pathname.split('/').pop() || url.hostname) })\n }\n catch {\n error.value = m.value.invalidLink\n }\n}\n\nconst sizeLabel = computed(() => {\n const bytes = Number(props.node.attrs.size)\n if (!bytes) return ''\n const units = ['B', 'KB', 'MB', 'GB']\n const i = Math.min(units.length - 1, Math.floor(Math.log(bytes) / Math.log(1024)))\n return `${(bytes / 1024 ** i).toFixed(i ? 1 : 0)} ${units[i]}`\n})\n</script>\n\n<template>\n <NodeViewWrapper class=\"me-media\" :class=\"{ 'is-readonly-empty': !editable && !node.attrs.src }\">\n <div v-if=\"!node.attrs.src\" class=\"me-media-empty\" contenteditable=\"false\" @dragover.prevent @drop=\"onDrop\">\n <div class=\"me-tabs\">\n <button v-for=\"t in (['upload', 'link'] as const)\" :key=\"t\" type=\"button\" class=\"me-tab\" :class=\"{ 'is-active': tab === t }\" @click=\"tab = t\">\n <component :is=\"t === 'upload' ? Upload : LinkIcon\" />\n {{ t === 'upload' ? m.upload : m.link }}\n </button>\n </div>\n <div v-if=\"tab === 'upload'\" class=\"me-media-body\">\n <button type=\"button\" class=\"me-btn\" :disabled=\"uploading\" @click=\"fileInput?.click()\">\n <component :is=\"icon\" /> {{ uploading ? m.uploading : title }}\n </button>\n <p class=\"me-hint\">\n {{ m.dropHint(options.maxSize) }}\n </p>\n <input ref=\"fileInput\" type=\"file\" :accept=\"accept\" hidden @change=\"($event.target as HTMLInputElement).files?.[0] && handleFile(($event.target as HTMLInputElement).files![0]!)\">\n </div>\n <form v-else class=\"me-inline-form\" @submit.prevent=\"submitLink\">\n <input v-model=\"link\" class=\"me-input\" placeholder=\"https://...\" @keydown.stop>\n <button type=\"submit\" class=\"me-btn me-btn--primary\">\n {{ m.embed }}\n </button>\n </form>\n <p v-if=\"error\" class=\"me-error\">\n {{ error }}\n </p>\n </div>\n\n <div v-else class=\"me-file\" :class=\"[`me-file--${kind}`, { 'is-selected': selected }]\" contenteditable=\"false\">\n <audio v-if=\"kind === 'audio' && safeSrc\" class=\"me-file-player\" :src=\"safeSrc\" controls preload=\"metadata\" />\n <video v-else-if=\"kind === 'video' && safeSrc\" class=\"me-file-player\" :src=\"safeSrc\" controls preload=\"metadata\" />\n <div class=\"me-file-row\">\n <component :is=\"icon\" class=\"me-file-icon\" />\n <span class=\"me-file-name\">{{ node.attrs.name || node.attrs.src }}</span>\n <span v-if=\"sizeLabel\" class=\"me-file-size\">{{ sizeLabel }}</span>\n <a v-if=\"safeSrc\" class=\"me-tool-btn\" :href=\"safeSrc\" :download=\"node.attrs.name || true\" target=\"_blank\" rel=\"noopener noreferrer\" :title=\"m.download\">\n <Download />\n </a>\n </div>\n </div>\n </NodeViewWrapper>\n</template>\n","<script setup lang=\"ts\">\nimport { NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport { AudioLines, Download, File as FileIcon, Film, Link as LinkIcon, Upload } from '@lucide/vue'\nimport { computed, ref } from 'vue'\nimport { useEditable } from '../composables/useEditable'\nimport { safeUrl } from '../safe-url'\nimport type { FileBlockOptions, FileKind } from '../extensions/file-block'\n\nconst props = defineProps(nodeViewProps)\nconst editable = useEditable(props.editor)\n\nconst options = computed(() => props.extension.options as FileBlockOptions)\nconst kind = computed(() => (props.node.attrs.kind ?? 'file') as FileKind)\nconst m = computed(() => props.editor.storage.meiConfig.messages.file)\nconst tab = ref<'upload' | 'link'>('upload')\nconst link = ref('')\nconst error = ref('')\nconst uploading = ref(false)\nconst fileInput = ref<HTMLInputElement | null>(null)\n\n// Web, blob, data and same-origin paths (uploads like `/api/v1/files/<id>`, KS-BUG-15);\n// never `javascript:`: pasted content could carry such links.\nconst safeSrc = computed(() => safeUrl(props.node.attrs.src, 'any'))\nconst accept = computed(() => ({ file: '', audio: 'audio/*', video: 'video/*' })[kind.value])\nconst icon = computed(() => ({ file: FileIcon, audio: AudioLines, video: Film })[kind.value])\nconst title = computed(() => ({ file: m.value.chooseFile, audio: m.value.chooseAudio, video: m.value.chooseVideo })[kind.value])\n\nconst readAsDataUrl = (file: File) => new Promise<string>((resolve, reject) => {\n const reader = new FileReader()\n reader.onload = () => resolve(reader.result as string)\n reader.onerror = () => reject(reader.error)\n reader.readAsDataURL(file)\n})\n\nasync function handleFile(file: File) {\n error.value = ''\n if (kind.value !== 'file' && !file.type.startsWith(`${kind.value}/`)) return (error.value = m.value.wrongType)\n if (file.size > options.value.maxSize * 1024 * 1024) return (error.value = m.value.tooLarge(options.value.maxSize))\n uploading.value = true\n try {\n const src = options.value.upload ? await options.value.upload(file, kind.value) : await readAsDataUrl(file)\n props.updateAttributes({ src, name: file.name, size: file.size, mime: file.type })\n }\n catch {\n error.value = m.value.uploadFailed\n }\n finally {\n uploading.value = false\n }\n}\n\nfunction onDrop(e: DragEvent) {\n const file = e.dataTransfer?.files?.[0]\n if (!file) return\n e.preventDefault()\n e.stopPropagation()\n handleFile(file)\n}\n\nfunction submitLink() {\n try {\n const url = new URL(link.value.trim())\n if (!/^https?:$/.test(url.protocol)) throw new Error('protocol')\n props.updateAttributes({ src: url.toString(), name: decodeURIComponent(url.pathname.split('/').pop() || url.hostname) })\n }\n catch {\n error.value = m.value.invalidLink\n }\n}\n\nconst sizeLabel = computed(() => {\n const bytes = Number(props.node.attrs.size)\n if (!bytes) return ''\n const units = ['B', 'KB', 'MB', 'GB']\n const i = Math.min(units.length - 1, Math.floor(Math.log(bytes) / Math.log(1024)))\n return `${(bytes / 1024 ** i).toFixed(i ? 1 : 0)} ${units[i]}`\n})\n</script>\n\n<template>\n <NodeViewWrapper class=\"me-media\" :class=\"{ 'is-readonly-empty': !editable && !node.attrs.src }\">\n <div v-if=\"!node.attrs.src\" class=\"me-media-empty\" contenteditable=\"false\" @dragover.prevent @drop=\"onDrop\">\n <div class=\"me-tabs\">\n <button v-for=\"t in (['upload', 'link'] as const)\" :key=\"t\" type=\"button\" class=\"me-tab\" :class=\"{ 'is-active': tab === t }\" @click=\"tab = t\">\n <component :is=\"t === 'upload' ? Upload : LinkIcon\" />\n {{ t === 'upload' ? m.upload : m.link }}\n </button>\n </div>\n <div v-if=\"tab === 'upload'\" class=\"me-media-body\">\n <button type=\"button\" class=\"me-btn\" :disabled=\"uploading\" @click=\"fileInput?.click()\">\n <component :is=\"icon\" /> {{ uploading ? m.uploading : title }}\n </button>\n <p class=\"me-hint\">\n {{ m.dropHint(options.maxSize) }}\n </p>\n <input ref=\"fileInput\" type=\"file\" :accept=\"accept\" hidden @change=\"($event.target as HTMLInputElement).files?.[0] && handleFile(($event.target as HTMLInputElement).files![0]!)\">\n </div>\n <form v-else class=\"me-inline-form\" @submit.prevent=\"submitLink\">\n <input v-model=\"link\" class=\"me-input\" placeholder=\"https://...\" @keydown.stop>\n <button type=\"submit\" class=\"me-btn me-btn--primary\">\n {{ m.embed }}\n </button>\n </form>\n <p v-if=\"error\" class=\"me-error\">\n {{ error }}\n </p>\n </div>\n\n <div v-else class=\"me-file\" :class=\"[`me-file--${kind}`, { 'is-selected': selected }]\" contenteditable=\"false\">\n <audio v-if=\"kind === 'audio' && safeSrc\" class=\"me-file-player\" :src=\"safeSrc\" controls preload=\"metadata\" />\n <video v-else-if=\"kind === 'video' && safeSrc\" class=\"me-file-player\" :src=\"safeSrc\" controls preload=\"metadata\" />\n <div class=\"me-file-row\">\n <component :is=\"icon\" class=\"me-file-icon\" />\n <span class=\"me-file-name\">{{ node.attrs.name || node.attrs.src }}</span>\n <span v-if=\"sizeLabel\" class=\"me-file-size\">{{ sizeLabel }}</span>\n <a v-if=\"safeSrc\" class=\"me-tool-btn\" :href=\"safeSrc\" :download=\"node.attrs.name || true\" target=\"_blank\" rel=\"noopener noreferrer\" :title=\"m.download\">\n <Download />\n </a>\n </div>\n </div>\n </NodeViewWrapper>\n</template>\n","import { mergeAttributes, Node } from '@tiptap/core'\nimport { blockNodeView } from '../nodeviews/renderer'\nimport FileView from '../nodeviews/FileView.vue'\n\nexport type FileKind = 'file' | 'audio' | 'video'\n\nexport interface FileBlockOptions {\n /** Uploads a file and resolves to its URL. Without it files are inlined as base64. */\n upload: ((file: File, kind: FileKind) => Promise<string>) | null\n /** Max size in MB. */\n maxSize: number\n}\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n fileBlock: { insertFileBlock: (kind?: FileKind) => ReturnType }\n }\n}\n\n/** Attachment, audio player or video player, uploaded or linked. */\nexport const FileBlock = Node.create<FileBlockOptions>({\n name: 'fileBlock',\n group: 'block',\n atom: true,\n draggable: true,\n\n addOptions: () => ({ upload: null, maxSize: 10 }),\n\n addAttributes() {\n const attr = (name: string, fallback: unknown = null) => ({\n default: fallback,\n parseHTML: (el: HTMLElement) => el.getAttribute(`data-${name}`) ?? fallback,\n renderHTML: (attrs: Record<string, any>) => (attrs[name] == null ? {} : { [`data-${name}`]: attrs[name] }),\n })\n return { src: attr('src'), name: attr('name'), size: attr('size'), mime: attr('mime'), kind: attr('kind', 'file') }\n },\n\n parseHTML: () => [{ tag: 'div[data-type=\"file\"]' }],\n renderHTML: ({ HTMLAttributes }) => ['div', mergeAttributes(HTMLAttributes, { 'data-type': 'file' })],\n\n addCommands() {\n return { insertFileBlock: (kind = 'file') => ({ commands }) => commands.insertContent({ type: this.name, attrs: { kind } }) }\n },\n\n addNodeView: () => blockNodeView(FileView),\n})\n","<script setup lang=\"ts\">\n/**\n * Notion-style HTML block. The page runs in a sandboxed iframe of fixed height; it only\n * takes clicks/scrolls after \"Interact\" (so scrolling the document isn't hijacked).\n * Editors can switch to Code to edit in place, upload an .html file, or drag the height.\n */\nimport { NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport { Code, CodeXml, Eye, Maximize2, Pointer, Upload, X } from '@lucide/vue'\nimport { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue'\nimport { useClickOutside } from '../composables/useClickOutside'\nimport { useEditable } from '../composables/useEditable'\nimport { useScope } from '../composables/useScope'\nimport { loadLanguage, lowlight } from '../extensions/code-block'\nimport { HTML_MAX_HEIGHT, HTML_MIN_HEIGHT, type HtmlBlockOptions, htmlBlockDocument } from '../extensions/html-block'\n\nconst props = defineProps(nodeViewProps)\n\nconst scope = useScope(() => props.editor)\nconst editable = useEditable(props.editor)\nconst m = computed(() => props.editor.storage.meiConfig.messages.html)\nconst options = computed(() => props.extension.options as HtmlBlockOptions)\nconst code = computed(() => (props.node.attrs.code as string) ?? '')\nconst height = computed(() => (props.node.attrs.height as number | null) ?? options.value.defaultHeight)\nconst name = computed(() => (props.node.attrs.fileName as string | null) || m.value.title)\nconst srcdoc = computed(() => htmlBlockDocument(code.value, options.value.network))\n\n// --- Modes ----------------------------------------------------------------------\nconst mode = ref<'preview' | 'code'>('preview')\nconst interacting = ref(false)\nconst fullscreen = ref(false)\nconst root = ref<HTMLElement | null>(null)\nuseClickOutside(root, interacting, () => (interacting.value = false))\n\nfunction showCode() {\n error.value = ''\n mode.value = 'code'\n interacting.value = false\n nextTick(() => textarea.value?.focus())\n}\nfunction showPreview() {\n error.value = ''\n commit()\n mode.value = 'preview'\n}\n\n// Read-only: back to the preview.\nwatch(editable, (value) => {\n if (!value && mode.value === 'code') showPreview()\n})\n\n// --- Code editor ----------------------------------------------------------------\nconst draft = ref(code.value)\nwatch(code, (value) => {\n if (value !== draft.value) draft.value = value\n})\nconst textarea = ref<HTMLTextAreaElement | null>(null)\nconst highlightEl = ref<HTMLElement | null>(null)\n\nlet timer: ReturnType<typeof setTimeout> | undefined\nfunction commit() {\n clearTimeout(timer)\n if (draft.value !== code.value) props.updateAttributes({ code: draft.value })\n}\nfunction onInput() {\n clearTimeout(timer)\n timer = setTimeout(commit, 400)\n}\nfunction onKeydown(e: KeyboardEvent) {\n if (e.key === 'Tab') {\n // Indent instead of leaving the editor.\n e.preventDefault()\n const el = e.target as HTMLTextAreaElement\n el.setRangeText(' ', el.selectionStart, el.selectionEnd, 'end')\n draft.value = el.value\n onInput()\n }\n else if (e.key === 'Escape' || (e.key === 'Enter' && (e.metaKey || e.ctrlKey))) {\n e.preventDefault()\n showPreview()\n }\n}\nfunction syncScroll() {\n if (highlightEl.value && textarea.value) {\n highlightEl.value.scrollTop = textarea.value.scrollTop\n highlightEl.value.scrollLeft = textarea.value.scrollLeft\n }\n}\n\n// Syntax colors: HTML grammar plus the CSS/JS it embeds, loaded on first use.\nconst grammarReady = ref(false)\nwatch(mode, (value) => {\n if (value === 'code' && !grammarReady.value) {\n Promise.all(['xml', 'css', 'javascript'].map(loadLanguage)).then(() => (grammarReady.value = true))\n }\n}, { immediate: true })\n\ntype HastNode = { type: string, value?: string, tagName?: string, properties?: { className?: string[] }, children?: HastNode[] }\nconst escapeHtml = (s: string) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')\nfunction toHtml(node: HastNode): string {\n if (node.type === 'text') return escapeHtml(node.value ?? '')\n const inner = (node.children ?? []).map(toHtml).join('')\n if (node.type === 'element') return `<span class=\"${(node.properties?.className ?? []).join(' ')}\">${inner}</span>`\n return inner\n}\nconst highlighted = computed(() => {\n // Trailing newline keeps the last line's height in sync with the textarea.\n const text = `${draft.value}\\n`\n if (!grammarReady.value || !lowlight.registered('xml')) return escapeHtml(text)\n return toHtml(lowlight.highlight('xml', text) as HastNode)\n})\n\n// --- Upload ---------------------------------------------------------------------\nconst fileInput = ref<HTMLInputElement | null>(null)\nconst error = ref('')\nasync function onFile(e: Event) {\n const input = e.target as HTMLInputElement\n const file = input.files?.[0]\n input.value = ''\n if (!file) return\n if (!/\\.html?$/i.test(file.name) && file.type !== 'text/html') {\n error.value = m.value.wrongType\n return\n }\n if (file.size > options.value.maxSize * 1024) {\n error.value = m.value.tooLarge(options.value.maxSize)\n return\n }\n error.value = ''\n const text = await file.text()\n draft.value = text\n props.updateAttributes({ code: text, fileName: file.name })\n mode.value = 'preview'\n}\n\n// --- Resize & fullscreen --------------------------------------------------------\nconst resizing = ref(false)\nfunction startResize(e: PointerEvent) {\n e.preventDefault()\n resizing.value = true\n const startY = e.clientY\n const startH = height.value\n const move = (ev: PointerEvent) => {\n props.updateAttributes({ height: Math.round(Math.min(HTML_MAX_HEIGHT, Math.max(HTML_MIN_HEIGHT, startH + ev.clientY - startY))) })\n }\n const up = () => {\n resizing.value = false\n window.removeEventListener('pointermove', move)\n window.removeEventListener('pointerup', up)\n }\n window.addEventListener('pointermove', move)\n window.addEventListener('pointerup', up)\n}\n\nfunction onFullscreenKey(e: KeyboardEvent) {\n if (e.key === 'Escape') fullscreen.value = false\n}\nwatch(fullscreen, (open) => {\n if (open) window.addEventListener('keydown', onFullscreenKey)\n else window.removeEventListener('keydown', onFullscreenKey)\n})\nonBeforeUnmount(() => {\n commit()\n window.removeEventListener('keydown', onFullscreenKey)\n})\n\n// Sandbox: scripts, forms and dialogs run, but never with the editor's origin.\nconst SANDBOX = 'allow-scripts allow-forms allow-modals allow-popups allow-pointer-lock allow-downloads'\n</script>\n\n<template>\n <NodeViewWrapper class=\"me-html\" :class=\"{ 'is-selected': selected, 'is-readonly-empty': !editable && !code }\">\n <div ref=\"root\" class=\"me-html-frame\" contenteditable=\"false\">\n <div class=\"me-block-bar me-html-bar\">\n <CodeXml />\n <span class=\"me-html-name\">{{ name }}</span>\n <div v-if=\"editable\" class=\"me-tabs me-tabs--inline\" role=\"tablist\">\n <button type=\"button\" class=\"me-tab\" :class=\"{ 'is-active': mode === 'code' }\" role=\"tab\" :aria-selected=\"mode === 'code'\" @click=\"showCode\">\n <Code /> {{ m.code }}\n </button>\n <button type=\"button\" class=\"me-tab\" :class=\"{ 'is-active': mode === 'preview' }\" role=\"tab\" :aria-selected=\"mode === 'preview'\" @click=\"showPreview\">\n <Eye /> {{ m.preview }}\n </button>\n </div>\n <button v-if=\"editable\" type=\"button\" class=\"me-tool-btn\" :title=\"m.upload\" @click=\"fileInput?.click()\">\n <Upload />\n </button>\n <button v-if=\"code\" type=\"button\" class=\"me-tool-btn\" :title=\"m.expand\" @click=\"commit(); fullscreen = true\">\n <Maximize2 />\n </button>\n <input ref=\"fileInput\" type=\"file\" accept=\".html,.htm,text/html\" hidden @change=\"onFile\">\n </div>\n\n <p v-if=\"error\" class=\"me-error me-html-error\">\n {{ error }}\n </p>\n\n <!-- Empty block: write or upload. -->\n <!-- Same layout and buttons as the image/file upload placeholders. -->\n <div v-if=\"mode === 'preview' && !code\" class=\"me-media-body me-html-empty\">\n <div v-if=\"editable\" class=\"me-inline-form\">\n <button type=\"button\" class=\"me-btn\" @click=\"showCode\">\n <Code /> {{ m.write }}\n </button>\n <button type=\"button\" class=\"me-btn\" @click=\"fileInput?.click()\">\n <Upload /> {{ m.uploadFile }}\n </button>\n </div>\n <p class=\"me-hint\">\n {{ m.emptyHint }}\n </p>\n </div>\n\n <div v-else-if=\"mode === 'preview'\" class=\"me-html-body\" :style=\"{ height: `${height}px` }\">\n <iframe\n class=\"me-html-iframe\"\n :class=\"{ 'is-live': interacting }\"\n :srcdoc=\"srcdoc\"\n :sandbox=\"SANDBOX\"\n :title=\"name\"\n loading=\"lazy\"\n referrerpolicy=\"no-referrer\"\n />\n <!-- Until \"Interact\", clicks and wheel go to the page, not the frame (like Notion). -->\n <div v-if=\"!interacting\" class=\"me-html-cover\" @dblclick=\"interacting = true\">\n <button type=\"button\" class=\"me-btn me-btn--floating\" @click=\"interacting = true\">\n <Pointer /> {{ m.interact }}\n </button>\n </div>\n </div>\n\n <div v-else class=\"me-html-editor\" :style=\"{ height: `${height}px` }\">\n <!-- A div, not <pre>: ProseMirror's unlayered `pre` styles would make it wrap. -->\n <div ref=\"highlightEl\" class=\"me-html-highlight\" aria-hidden=\"true\" v-html=\"highlighted\" />\n <textarea\n ref=\"textarea\"\n v-model=\"draft\"\n class=\"me-html-textarea\"\n spellcheck=\"false\"\n wrap=\"off\"\n autocapitalize=\"off\"\n autocomplete=\"off\"\n :placeholder=\"m.placeholder\"\n @input=\"onInput\"\n @blur=\"commit\"\n @scroll=\"syncScroll\"\n @keydown=\"onKeydown\"\n />\n </div>\n\n <!-- Iframes swallow pointer events; cover them while resizing. -->\n <div v-if=\"resizing\" class=\"me-embed-overlay\" />\n <span v-if=\"editable\" class=\"me-embed-resize\" @pointerdown=\"startResize\" />\n </div>\n\n <Teleport to=\"body\">\n <div v-if=\"fullscreen\" v-bind=\"scope\" class=\"me-html-modal\" @mousedown.self=\"fullscreen = false\">\n <div class=\"me-html-modal-panel\">\n <div class=\"me-block-bar me-html-bar\">\n <CodeXml />\n <span class=\"me-html-name\">{{ name }}</span>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.close\" @click=\"fullscreen = false\">\n <X />\n </button>\n </div>\n <iframe class=\"me-html-iframe is-live\" :srcdoc=\"srcdoc\" :sandbox=\"SANDBOX\" :title=\"name\" referrerpolicy=\"no-referrer\" />\n </div>\n </div>\n </Teleport>\n </NodeViewWrapper>\n</template>\n","<script setup lang=\"ts\">\n/**\n * Notion-style HTML block. The page runs in a sandboxed iframe of fixed height; it only\n * takes clicks/scrolls after \"Interact\" (so scrolling the document isn't hijacked).\n * Editors can switch to Code to edit in place, upload an .html file, or drag the height.\n */\nimport { NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport { Code, CodeXml, Eye, Maximize2, Pointer, Upload, X } from '@lucide/vue'\nimport { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue'\nimport { useClickOutside } from '../composables/useClickOutside'\nimport { useEditable } from '../composables/useEditable'\nimport { useScope } from '../composables/useScope'\nimport { loadLanguage, lowlight } from '../extensions/code-block'\nimport { HTML_MAX_HEIGHT, HTML_MIN_HEIGHT, type HtmlBlockOptions, htmlBlockDocument } from '../extensions/html-block'\n\nconst props = defineProps(nodeViewProps)\n\nconst scope = useScope(() => props.editor)\nconst editable = useEditable(props.editor)\nconst m = computed(() => props.editor.storage.meiConfig.messages.html)\nconst options = computed(() => props.extension.options as HtmlBlockOptions)\nconst code = computed(() => (props.node.attrs.code as string) ?? '')\nconst height = computed(() => (props.node.attrs.height as number | null) ?? options.value.defaultHeight)\nconst name = computed(() => (props.node.attrs.fileName as string | null) || m.value.title)\nconst srcdoc = computed(() => htmlBlockDocument(code.value, options.value.network))\n\n// --- Modes ----------------------------------------------------------------------\nconst mode = ref<'preview' | 'code'>('preview')\nconst interacting = ref(false)\nconst fullscreen = ref(false)\nconst root = ref<HTMLElement | null>(null)\nuseClickOutside(root, interacting, () => (interacting.value = false))\n\nfunction showCode() {\n error.value = ''\n mode.value = 'code'\n interacting.value = false\n nextTick(() => textarea.value?.focus())\n}\nfunction showPreview() {\n error.value = ''\n commit()\n mode.value = 'preview'\n}\n\n// Read-only: back to the preview.\nwatch(editable, (value) => {\n if (!value && mode.value === 'code') showPreview()\n})\n\n// --- Code editor ----------------------------------------------------------------\nconst draft = ref(code.value)\nwatch(code, (value) => {\n if (value !== draft.value) draft.value = value\n})\nconst textarea = ref<HTMLTextAreaElement | null>(null)\nconst highlightEl = ref<HTMLElement | null>(null)\n\nlet timer: ReturnType<typeof setTimeout> | undefined\nfunction commit() {\n clearTimeout(timer)\n if (draft.value !== code.value) props.updateAttributes({ code: draft.value })\n}\nfunction onInput() {\n clearTimeout(timer)\n timer = setTimeout(commit, 400)\n}\nfunction onKeydown(e: KeyboardEvent) {\n if (e.key === 'Tab') {\n // Indent instead of leaving the editor.\n e.preventDefault()\n const el = e.target as HTMLTextAreaElement\n el.setRangeText(' ', el.selectionStart, el.selectionEnd, 'end')\n draft.value = el.value\n onInput()\n }\n else if (e.key === 'Escape' || (e.key === 'Enter' && (e.metaKey || e.ctrlKey))) {\n e.preventDefault()\n showPreview()\n }\n}\nfunction syncScroll() {\n if (highlightEl.value && textarea.value) {\n highlightEl.value.scrollTop = textarea.value.scrollTop\n highlightEl.value.scrollLeft = textarea.value.scrollLeft\n }\n}\n\n// Syntax colors: HTML grammar plus the CSS/JS it embeds, loaded on first use.\nconst grammarReady = ref(false)\nwatch(mode, (value) => {\n if (value === 'code' && !grammarReady.value) {\n Promise.all(['xml', 'css', 'javascript'].map(loadLanguage)).then(() => (grammarReady.value = true))\n }\n}, { immediate: true })\n\ntype HastNode = { type: string, value?: string, tagName?: string, properties?: { className?: string[] }, children?: HastNode[] }\nconst escapeHtml = (s: string) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')\nfunction toHtml(node: HastNode): string {\n if (node.type === 'text') return escapeHtml(node.value ?? '')\n const inner = (node.children ?? []).map(toHtml).join('')\n if (node.type === 'element') return `<span class=\"${(node.properties?.className ?? []).join(' ')}\">${inner}</span>`\n return inner\n}\nconst highlighted = computed(() => {\n // Trailing newline keeps the last line's height in sync with the textarea.\n const text = `${draft.value}\\n`\n if (!grammarReady.value || !lowlight.registered('xml')) return escapeHtml(text)\n return toHtml(lowlight.highlight('xml', text) as HastNode)\n})\n\n// --- Upload ---------------------------------------------------------------------\nconst fileInput = ref<HTMLInputElement | null>(null)\nconst error = ref('')\nasync function onFile(e: Event) {\n const input = e.target as HTMLInputElement\n const file = input.files?.[0]\n input.value = ''\n if (!file) return\n if (!/\\.html?$/i.test(file.name) && file.type !== 'text/html') {\n error.value = m.value.wrongType\n return\n }\n if (file.size > options.value.maxSize * 1024) {\n error.value = m.value.tooLarge(options.value.maxSize)\n return\n }\n error.value = ''\n const text = await file.text()\n draft.value = text\n props.updateAttributes({ code: text, fileName: file.name })\n mode.value = 'preview'\n}\n\n// --- Resize & fullscreen --------------------------------------------------------\nconst resizing = ref(false)\nfunction startResize(e: PointerEvent) {\n e.preventDefault()\n resizing.value = true\n const startY = e.clientY\n const startH = height.value\n const move = (ev: PointerEvent) => {\n props.updateAttributes({ height: Math.round(Math.min(HTML_MAX_HEIGHT, Math.max(HTML_MIN_HEIGHT, startH + ev.clientY - startY))) })\n }\n const up = () => {\n resizing.value = false\n window.removeEventListener('pointermove', move)\n window.removeEventListener('pointerup', up)\n }\n window.addEventListener('pointermove', move)\n window.addEventListener('pointerup', up)\n}\n\nfunction onFullscreenKey(e: KeyboardEvent) {\n if (e.key === 'Escape') fullscreen.value = false\n}\nwatch(fullscreen, (open) => {\n if (open) window.addEventListener('keydown', onFullscreenKey)\n else window.removeEventListener('keydown', onFullscreenKey)\n})\nonBeforeUnmount(() => {\n commit()\n window.removeEventListener('keydown', onFullscreenKey)\n})\n\n// Sandbox: scripts, forms and dialogs run, but never with the editor's origin.\nconst SANDBOX = 'allow-scripts allow-forms allow-modals allow-popups allow-pointer-lock allow-downloads'\n</script>\n\n<template>\n <NodeViewWrapper class=\"me-html\" :class=\"{ 'is-selected': selected, 'is-readonly-empty': !editable && !code }\">\n <div ref=\"root\" class=\"me-html-frame\" contenteditable=\"false\">\n <div class=\"me-block-bar me-html-bar\">\n <CodeXml />\n <span class=\"me-html-name\">{{ name }}</span>\n <div v-if=\"editable\" class=\"me-tabs me-tabs--inline\" role=\"tablist\">\n <button type=\"button\" class=\"me-tab\" :class=\"{ 'is-active': mode === 'code' }\" role=\"tab\" :aria-selected=\"mode === 'code'\" @click=\"showCode\">\n <Code /> {{ m.code }}\n </button>\n <button type=\"button\" class=\"me-tab\" :class=\"{ 'is-active': mode === 'preview' }\" role=\"tab\" :aria-selected=\"mode === 'preview'\" @click=\"showPreview\">\n <Eye /> {{ m.preview }}\n </button>\n </div>\n <button v-if=\"editable\" type=\"button\" class=\"me-tool-btn\" :title=\"m.upload\" @click=\"fileInput?.click()\">\n <Upload />\n </button>\n <button v-if=\"code\" type=\"button\" class=\"me-tool-btn\" :title=\"m.expand\" @click=\"commit(); fullscreen = true\">\n <Maximize2 />\n </button>\n <input ref=\"fileInput\" type=\"file\" accept=\".html,.htm,text/html\" hidden @change=\"onFile\">\n </div>\n\n <p v-if=\"error\" class=\"me-error me-html-error\">\n {{ error }}\n </p>\n\n <!-- Empty block: write or upload. -->\n <!-- Same layout and buttons as the image/file upload placeholders. -->\n <div v-if=\"mode === 'preview' && !code\" class=\"me-media-body me-html-empty\">\n <div v-if=\"editable\" class=\"me-inline-form\">\n <button type=\"button\" class=\"me-btn\" @click=\"showCode\">\n <Code /> {{ m.write }}\n </button>\n <button type=\"button\" class=\"me-btn\" @click=\"fileInput?.click()\">\n <Upload /> {{ m.uploadFile }}\n </button>\n </div>\n <p class=\"me-hint\">\n {{ m.emptyHint }}\n </p>\n </div>\n\n <div v-else-if=\"mode === 'preview'\" class=\"me-html-body\" :style=\"{ height: `${height}px` }\">\n <iframe\n class=\"me-html-iframe\"\n :class=\"{ 'is-live': interacting }\"\n :srcdoc=\"srcdoc\"\n :sandbox=\"SANDBOX\"\n :title=\"name\"\n loading=\"lazy\"\n referrerpolicy=\"no-referrer\"\n />\n <!-- Until \"Interact\", clicks and wheel go to the page, not the frame (like Notion). -->\n <div v-if=\"!interacting\" class=\"me-html-cover\" @dblclick=\"interacting = true\">\n <button type=\"button\" class=\"me-btn me-btn--floating\" @click=\"interacting = true\">\n <Pointer /> {{ m.interact }}\n </button>\n </div>\n </div>\n\n <div v-else class=\"me-html-editor\" :style=\"{ height: `${height}px` }\">\n <!-- A div, not <pre>: ProseMirror's unlayered `pre` styles would make it wrap. -->\n <div ref=\"highlightEl\" class=\"me-html-highlight\" aria-hidden=\"true\" v-html=\"highlighted\" />\n <textarea\n ref=\"textarea\"\n v-model=\"draft\"\n class=\"me-html-textarea\"\n spellcheck=\"false\"\n wrap=\"off\"\n autocapitalize=\"off\"\n autocomplete=\"off\"\n :placeholder=\"m.placeholder\"\n @input=\"onInput\"\n @blur=\"commit\"\n @scroll=\"syncScroll\"\n @keydown=\"onKeydown\"\n />\n </div>\n\n <!-- Iframes swallow pointer events; cover them while resizing. -->\n <div v-if=\"resizing\" class=\"me-embed-overlay\" />\n <span v-if=\"editable\" class=\"me-embed-resize\" @pointerdown=\"startResize\" />\n </div>\n\n <Teleport to=\"body\">\n <div v-if=\"fullscreen\" v-bind=\"scope\" class=\"me-html-modal\" @mousedown.self=\"fullscreen = false\">\n <div class=\"me-html-modal-panel\">\n <div class=\"me-block-bar me-html-bar\">\n <CodeXml />\n <span class=\"me-html-name\">{{ name }}</span>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.close\" @click=\"fullscreen = false\">\n <X />\n </button>\n </div>\n <iframe class=\"me-html-iframe is-live\" :srcdoc=\"srcdoc\" :sandbox=\"SANDBOX\" :title=\"name\" referrerpolicy=\"no-referrer\" />\n </div>\n </div>\n </Teleport>\n </NodeViewWrapper>\n</template>\n","import { Node } from '@tiptap/core'\nimport { blockNodeView } from '../nodeviews/renderer'\nimport HtmlView from '../nodeviews/HtmlView.vue'\nimport type { HtmlBlockOptions } from './html-document'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n htmlBlock: {\n insertHtmlBlock: (attrs?: { code?: string, fileName?: string | null }) => ReturnType\n }\n }\n}\n\nexport { HTML_MAX_HEIGHT, HTML_MIN_HEIGHT, htmlBlockCsp, htmlBlockDocument, type HtmlBlockOptions } from './html-document'\n\n/** Notion-style HTML block: your own HTML/CSS/JS, running in a sandboxed frame. */\nexport const HtmlBlock = Node.create<HtmlBlockOptions>({\n name: 'htmlBlock',\n group: 'block',\n atom: true,\n draggable: true,\n\n addOptions: () => ({ network: false, maxSize: 1024, defaultHeight: 400 }),\n\n addAttributes() {\n return {\n code: { default: '' },\n fileName: { default: null },\n height: { default: null },\n }\n },\n\n parseHTML() {\n return [{\n tag: 'div[data-type=\"html-block\"]',\n getAttrs: el => ({\n code: el.getAttribute('data-code') ?? '',\n fileName: el.getAttribute('data-file-name'),\n height: Number(el.getAttribute('data-height')) || null,\n }),\n }]\n },\n\n // The code is kept in an attribute, so exported HTML never runs it.\n renderHTML({ node }) {\n return ['div', {\n 'data-type': 'html-block',\n 'data-code': node.attrs.code ?? '',\n ...(node.attrs.fileName ? { 'data-file-name': node.attrs.fileName } : {}),\n ...(node.attrs.height ? { 'data-height': node.attrs.height } : {}),\n }]\n },\n\n renderText: ({ node }) => node.attrs.code ?? '',\n\n addCommands() {\n return {\n insertHtmlBlock: attrs => ({ commands }) => commands.insertContent({ type: this.name, attrs: { height: this.options.defaultHeight, ...attrs } }),\n }\n },\n\n addNodeView() {\n return blockNodeView(HtmlView)\n },\n})\n","<script setup lang=\"ts\">\nimport { NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'\nimport { useClickOutside } from '../composables/useClickOutside'\nimport { useEditable } from '../composables/useEditable'\nimport { loadKatex } from '../lazy'\n\nconst props = defineProps(nodeViewProps)\nconst editable = useEditable(props.editor)\n\nconst m = computed(() => props.editor.storage.meiConfig.messages.math)\nconst inline = computed(() => props.node.type.name === 'mathInline')\nconst rendered = ref('')\nconst error = ref('')\nconst editing = ref(false)\nconst draft = ref(props.node.attrs.latex as string)\nconst root = ref<HTMLElement | null>(null)\nconst input = ref<HTMLTextAreaElement | null>(null)\n\nasync function render(latex: string) {\n if (!latex.trim()) {\n rendered.value = ''\n return\n }\n try {\n const katex = await loadKatex()\n rendered.value = katex.renderToString(latex, { displayMode: !inline.value, throwOnError: false })\n error.value = ''\n }\n catch {\n error.value = m.value.missing\n }\n}\n\nwatch(() => props.node.attrs.latex, latex => render(latex), { immediate: true })\nwatch(draft, latex => render(latex))\n\nfunction open() {\n if (!props.editor.isEditable) return\n draft.value = props.node.attrs.latex\n editing.value = true\n nextTick(() => input.value?.focus())\n}\nfunction commit() {\n if (!editing.value) return\n editing.value = false\n if (draft.value !== props.node.attrs.latex) props.updateAttributes({ latex: draft.value })\n if (!draft.value.trim() && inline.value) props.deleteNode()\n}\nfunction onKeydown(e: KeyboardEvent) {\n e.stopPropagation()\n if (e.key === 'Escape' || (e.key === 'Enter' && (inline.value || e.metaKey || e.ctrlKey))) {\n e.preventDefault()\n commit()\n props.editor.commands.focus()\n }\n}\nuseClickOutside(root, editing, commit)\n\n// Switching to read-only closes the editor, keeping what was typed (no deletes then).\nwatch(editable, (value) => {\n if (value || !editing.value) return\n editing.value = false\n if (draft.value !== props.node.attrs.latex) props.updateAttributes({ latex: draft.value })\n})\n\n// A freshly inserted empty equation opens straight into editing.\nonMounted(() => {\n if (!props.node.attrs.latex) open()\n})\nonBeforeUnmount(commit)\n</script>\n\n<template>\n <NodeViewWrapper\n ref=\"root\"\n :as=\"inline ? 'span' : 'div'\"\n :class=\"[inline ? 'me-math-inline' : 'me-math-block', { 'is-selected': selected, 'is-editing': editing, 'is-readonly-empty': !editable && !node.attrs.latex }]\"\n contenteditable=\"false\"\n >\n <span v-if=\"rendered\" class=\"me-math-render\" @click=\"open\" v-html=\"rendered\" />\n <span v-else class=\"me-math-empty\" @click=\"open\">{{ m.placeholder }}</span>\n <span v-if=\"error\" class=\"me-error\">{{ error }}</span>\n <span v-if=\"editing\" class=\"me-popover me-math-editor\">\n <textarea\n ref=\"input\"\n v-model=\"draft\"\n class=\"me-input me-math-input\"\n :rows=\"inline ? 1 : 3\"\n :placeholder=\"m.inputPlaceholder\"\n spellcheck=\"false\"\n @keydown=\"onKeydown\"\n />\n <span class=\"me-hint\">{{ inline ? m.hintInline : m.hintBlock }}</span>\n </span>\n </NodeViewWrapper>\n</template>\n","<script setup lang=\"ts\">\nimport { NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'\nimport { useClickOutside } from '../composables/useClickOutside'\nimport { useEditable } from '../composables/useEditable'\nimport { loadKatex } from '../lazy'\n\nconst props = defineProps(nodeViewProps)\nconst editable = useEditable(props.editor)\n\nconst m = computed(() => props.editor.storage.meiConfig.messages.math)\nconst inline = computed(() => props.node.type.name === 'mathInline')\nconst rendered = ref('')\nconst error = ref('')\nconst editing = ref(false)\nconst draft = ref(props.node.attrs.latex as string)\nconst root = ref<HTMLElement | null>(null)\nconst input = ref<HTMLTextAreaElement | null>(null)\n\nasync function render(latex: string) {\n if (!latex.trim()) {\n rendered.value = ''\n return\n }\n try {\n const katex = await loadKatex()\n rendered.value = katex.renderToString(latex, { displayMode: !inline.value, throwOnError: false })\n error.value = ''\n }\n catch {\n error.value = m.value.missing\n }\n}\n\nwatch(() => props.node.attrs.latex, latex => render(latex), { immediate: true })\nwatch(draft, latex => render(latex))\n\nfunction open() {\n if (!props.editor.isEditable) return\n draft.value = props.node.attrs.latex\n editing.value = true\n nextTick(() => input.value?.focus())\n}\nfunction commit() {\n if (!editing.value) return\n editing.value = false\n if (draft.value !== props.node.attrs.latex) props.updateAttributes({ latex: draft.value })\n if (!draft.value.trim() && inline.value) props.deleteNode()\n}\nfunction onKeydown(e: KeyboardEvent) {\n e.stopPropagation()\n if (e.key === 'Escape' || (e.key === 'Enter' && (inline.value || e.metaKey || e.ctrlKey))) {\n e.preventDefault()\n commit()\n props.editor.commands.focus()\n }\n}\nuseClickOutside(root, editing, commit)\n\n// Switching to read-only closes the editor, keeping what was typed (no deletes then).\nwatch(editable, (value) => {\n if (value || !editing.value) return\n editing.value = false\n if (draft.value !== props.node.attrs.latex) props.updateAttributes({ latex: draft.value })\n})\n\n// A freshly inserted empty equation opens straight into editing.\nonMounted(() => {\n if (!props.node.attrs.latex) open()\n})\nonBeforeUnmount(commit)\n</script>\n\n<template>\n <NodeViewWrapper\n ref=\"root\"\n :as=\"inline ? 'span' : 'div'\"\n :class=\"[inline ? 'me-math-inline' : 'me-math-block', { 'is-selected': selected, 'is-editing': editing, 'is-readonly-empty': !editable && !node.attrs.latex }]\"\n contenteditable=\"false\"\n >\n <span v-if=\"rendered\" class=\"me-math-render\" @click=\"open\" v-html=\"rendered\" />\n <span v-else class=\"me-math-empty\" @click=\"open\">{{ m.placeholder }}</span>\n <span v-if=\"error\" class=\"me-error\">{{ error }}</span>\n <span v-if=\"editing\" class=\"me-popover me-math-editor\">\n <textarea\n ref=\"input\"\n v-model=\"draft\"\n class=\"me-input me-math-input\"\n :rows=\"inline ? 1 : 3\"\n :placeholder=\"m.inputPlaceholder\"\n spellcheck=\"false\"\n @keydown=\"onKeydown\"\n />\n <span class=\"me-hint\">{{ inline ? m.hintInline : m.hintBlock }}</span>\n </span>\n </NodeViewWrapper>\n</template>\n","import { InputRule, mergeAttributes, Node } from '@tiptap/core'\nimport { blockNodeView } from '../nodeviews/renderer'\nimport MathView from '../nodeviews/MathView.vue'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n math: {\n insertMathBlock: (latex?: string) => ReturnType\n insertMathInline: (latex?: string) => ReturnType\n }\n }\n}\n\nconst latexAttr = {\n latex: {\n default: '',\n parseHTML: (el: HTMLElement) => el.getAttribute('data-latex') ?? '',\n renderHTML: (attrs: Record<string, any>) => ({ 'data-latex': attrs.latex }),\n },\n}\n\n/** Display equation (KaTeX, loaded on first render). Type `$$ ` on an empty line. */\nexport const MathBlock = Node.create({\n name: 'mathBlock',\n group: 'block',\n atom: true,\n draggable: true,\n addAttributes: () => latexAttr,\n parseHTML: () => [{ tag: 'div[data-type=\"math-block\"]' }],\n renderHTML: ({ HTMLAttributes }) => ['div', mergeAttributes(HTMLAttributes, { 'data-type': 'math-block' })],\n addCommands() {\n return { insertMathBlock: (latex = '') => ({ commands }) => commands.insertContent({ type: this.name, attrs: { latex } }) }\n },\n addInputRules() {\n return [new InputRule({\n find: /^\\$\\$\\s$/,\n handler: ({ range, chain }) => {\n chain().deleteRange(range).insertMathBlock().run()\n },\n })]\n },\n addNodeView: () => blockNodeView(MathView),\n})\n\n/** Inline equation. Type `$$x^2$$` (single `$` would catch prices like $5). */\nexport const MathInline = Node.create({\n name: 'mathInline',\n group: 'inline',\n inline: true,\n atom: true,\n addAttributes: () => latexAttr,\n parseHTML: () => [{ tag: 'span[data-type=\"math-inline\"]' }],\n renderHTML: ({ HTMLAttributes }) => ['span', mergeAttributes(HTMLAttributes, { 'data-type': 'math-inline' })],\n renderText: ({ node }) => `$${node.attrs.latex}$`,\n addCommands() {\n return { insertMathInline: (latex = '') => ({ commands }) => commands.insertContent({ type: this.name, attrs: { latex } }) }\n },\n addInputRules() {\n return [new InputRule({\n find: /\\$\\$([^$\\n]+)\\$\\$$/,\n handler: ({ state, range, match }) => {\n state.tr.replaceWith(range.from, range.to, this.type.create({ latex: match[1]!.trim() }))\n },\n })]\n },\n addNodeView: () => blockNodeView(MathView),\n})\n","<script setup lang=\"ts\">\nimport type { Editor } from '@tiptap/core'\nimport { Calendar, FileText, User } from '@lucide/vue'\nimport { computed, nextTick, ref, watch } from 'vue'\nimport { useScope } from '../composables/useScope'\nimport type { MentionItem } from '../extensions/mention'\nimport { usePointerMoved } from '../composables/usePointerMoved'\n\nconst props = defineProps<{ editor: Editor, items: MentionItem[], command: (item: MentionItem) => void }>()\nconst scope = useScope(() => props.editor)\nconst m = computed(() => props.editor.storage.meiConfig.messages.mention)\nconst selected = ref(0)\nconst root = ref<HTMLElement | null>(null)\nconst ICONS = { user: User, page: FileText, date: Calendar }\n\nconst groups = computed(() => {\n const order: MentionItem['kind'][] = ['user', 'page', 'date']\n const label = { user: m.value.people, page: m.value.pages, date: m.value.dates }\n return order\n .map(kind => ({ kind, label: label[kind], entries: props.items.map((item, index) => ({ item, index })).filter(e => e.item.kind === kind) }))\n .filter(g => g.entries.length)\n})\n\nwatch(() => props.items, () => (selected.value = 0))\nwatch(selected, async (i) => {\n await nextTick()\n root.value?.querySelector(`[data-index=\"${i}\"]`)?.scrollIntoView({ block: 'nearest' })\n})\n\nfunction onKeyDown(e: KeyboardEvent) {\n const n = props.items.length\n if (!n) return false\n if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {\n selected.value = (selected.value + (e.key === 'ArrowDown' ? 1 : n - 1)) % n\n return true\n }\n if (e.key === 'Enter' || e.key === 'Tab') {\n const item = props.items[selected.value]\n if (item) props.command(item)\n return true\n }\n return false\n}\ndefineExpose({ onKeyDown })\n\n// Hover selects a row only after a real pointer move (KS-BUG-3).\nconst pointerMoved = usePointerMoved()\n</script>\n\n<template>\n <div ref=\"root\" v-bind=\"scope\" class=\"me-popover me-menu\">\n <div v-for=\"g in groups\" :key=\"g.kind\">\n <div class=\"me-menu-label\">\n {{ g.label }}\n </div>\n <button\n v-for=\"{ item, index } in g.entries\"\n :key=\"`${item.kind}-${item.id}`\"\n type=\"button\"\n class=\"me-menu-item\"\n :class=\"{ 'is-active': index === selected }\"\n :data-index=\"index\"\n @mousemove=\"pointerMoved($event) && (selected = index)\"\n @mousedown.prevent=\"command(item)\"\n >\n <img v-if=\"item.avatar\" class=\"me-menu-icon me-avatar\" :src=\"item.avatar\" alt=\"\">\n <span v-else class=\"me-menu-icon\"><component :is=\"ICONS[item.kind]\" /></span>\n <span class=\"me-menu-text\">\n <span class=\"me-menu-title\">{{ item.label }}</span>\n <span v-if=\"item.description\" class=\"me-menu-desc\">{{ item.description }}</span>\n </span>\n </button>\n </div>\n <div v-if=\"!items.length\" class=\"me-menu-empty\">\n {{ m.empty }}\n </div>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport type { Editor } from '@tiptap/core'\nimport { Calendar, FileText, User } from '@lucide/vue'\nimport { computed, nextTick, ref, watch } from 'vue'\nimport { useScope } from '../composables/useScope'\nimport type { MentionItem } from '../extensions/mention'\nimport { usePointerMoved } from '../composables/usePointerMoved'\n\nconst props = defineProps<{ editor: Editor, items: MentionItem[], command: (item: MentionItem) => void }>()\nconst scope = useScope(() => props.editor)\nconst m = computed(() => props.editor.storage.meiConfig.messages.mention)\nconst selected = ref(0)\nconst root = ref<HTMLElement | null>(null)\nconst ICONS = { user: User, page: FileText, date: Calendar }\n\nconst groups = computed(() => {\n const order: MentionItem['kind'][] = ['user', 'page', 'date']\n const label = { user: m.value.people, page: m.value.pages, date: m.value.dates }\n return order\n .map(kind => ({ kind, label: label[kind], entries: props.items.map((item, index) => ({ item, index })).filter(e => e.item.kind === kind) }))\n .filter(g => g.entries.length)\n})\n\nwatch(() => props.items, () => (selected.value = 0))\nwatch(selected, async (i) => {\n await nextTick()\n root.value?.querySelector(`[data-index=\"${i}\"]`)?.scrollIntoView({ block: 'nearest' })\n})\n\nfunction onKeyDown(e: KeyboardEvent) {\n const n = props.items.length\n if (!n) return false\n if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {\n selected.value = (selected.value + (e.key === 'ArrowDown' ? 1 : n - 1)) % n\n return true\n }\n if (e.key === 'Enter' || e.key === 'Tab') {\n const item = props.items[selected.value]\n if (item) props.command(item)\n return true\n }\n return false\n}\ndefineExpose({ onKeyDown })\n\n// Hover selects a row only after a real pointer move (KS-BUG-3).\nconst pointerMoved = usePointerMoved()\n</script>\n\n<template>\n <div ref=\"root\" v-bind=\"scope\" class=\"me-popover me-menu\">\n <div v-for=\"g in groups\" :key=\"g.kind\">\n <div class=\"me-menu-label\">\n {{ g.label }}\n </div>\n <button\n v-for=\"{ item, index } in g.entries\"\n :key=\"`${item.kind}-${item.id}`\"\n type=\"button\"\n class=\"me-menu-item\"\n :class=\"{ 'is-active': index === selected }\"\n :data-index=\"index\"\n @mousemove=\"pointerMoved($event) && (selected = index)\"\n @mousedown.prevent=\"command(item)\"\n >\n <img v-if=\"item.avatar\" class=\"me-menu-icon me-avatar\" :src=\"item.avatar\" alt=\"\">\n <span v-else class=\"me-menu-icon\"><component :is=\"ICONS[item.kind]\" /></span>\n <span class=\"me-menu-text\">\n <span class=\"me-menu-title\">{{ item.label }}</span>\n <span v-if=\"item.description\" class=\"me-menu-desc\">{{ item.description }}</span>\n </span>\n </button>\n </div>\n <div v-if=\"!items.length\" class=\"me-menu-empty\">\n {{ m.empty }}\n </div>\n </div>\n</template>\n","<script setup lang=\"ts\">\n/**\n * Notion-style date picker for date mentions: typed date/time inputs, month calendar,\n * end date (range), date & time formats, reminders, clear.\n */\nimport { Check, ChevronLeft, ChevronRight, CircleQuestionMark } from '@lucide/vue'\nimport { computed, ref, watch } from 'vue'\nimport {\n DATE_FORMATS, type DateFormat, type DateValue, formatDate, formatTime, isoDate, parseDateInput, parseIsoDate,\n parseTimeInput, REMINDERS_DATE, REMINDERS_TIME, type TimeFormat,\n} from '../date-utils'\nimport type { EditorMessages } from '../locale'\n\nconst props = defineProps<{\n value: DateValue\n locale: string\n messages: EditorMessages['datePicker']\n relative: { today: string, tomorrow: string, yesterday: string }\n helpUrl?: string | null\n}>()\nconst emit = defineEmits<{ change: [value: DateValue], clear: [] }>()\n\nconst m = computed(() => props.messages)\nconst v = computed(() => props.value)\nconst update = (patch: Partial<DateValue>) => emit('change', { ...props.value, ...patch })\n\n// --- Typed inputs -------------------------------------------------------------\n/** Which input the next calendar click fills (Notion alternates start → end). */\nconst editing = ref<'start' | 'end'>('start')\nconst inputFmt = (id: string | null | undefined) => (id ? formatDate(id, props.locale, 'short') : '')\nconst draft = ref({ start: '', end: '', time: '', endTime: '' })\nwatch(() => props.value, (val) => {\n draft.value = {\n start: inputFmt(val.start),\n end: inputFmt(val.end),\n time: val.time ? formatTime(val.time, props.locale, val.timeFormat ?? '24') : '',\n endTime: val.endTime ? formatTime(val.endTime, props.locale, val.timeFormat ?? '24') : '',\n }\n}, { immediate: true, deep: true })\n\nfunction commitDate(which: 'start' | 'end') {\n const parsed = parseDateInput(draft.value[which], props.locale)\n if (!parsed) {\n draft.value[which] = inputFmt(which === 'start' ? v.value.start : v.value.end)\n return\n }\n if (which === 'start') update({ start: parsed })\n else update({ end: parsed })\n view.value = monthOf(parsed)\n}\nfunction commitTime(which: 'time' | 'endTime') {\n const parsed = parseTimeInput(draft.value[which])\n if (parsed) update({ [which]: parsed })\n else draft.value[which] = v.value[which] ? formatTime(v.value[which]!, props.locale, v.value.timeFormat ?? '24') : ''\n}\n\n// --- Calendar -----------------------------------------------------------------\nconst monthOf = (id: string) => {\n const d = parseIsoDate(id) ?? new Date()\n return new Date(d.getFullYear(), d.getMonth(), 1)\n}\nconst view = ref(monthOf(props.value.start))\nconst today = isoDate(new Date())\n// \"Oct 2026\" / \"Tháng 11 2026\": month + year only, short enough for one line.\nconst monthLabel = computed(() => {\n // Chinese / Japanese / Korean read year first: \"2026年10月\".\n if (/^(zh|ja|ko)/.test(props.locale)) return new Intl.DateTimeFormat(props.locale, { year: 'numeric', month: 'long' }).format(view.value)\n const month = new Intl.DateTimeFormat(props.locale, { month: props.locale.startsWith('en') ? 'short' : 'long' }).format(view.value)\n return `${month.charAt(0).toUpperCase()}${month.slice(1)} ${view.value.getFullYear()}`\n})\n// Weeks start on Monday (like Notion's default).\nconst weekdays = computed(() => {\n const fmt = new Intl.DateTimeFormat(props.locale, { weekday: /^(vi|zh)/.test(props.locale) ? 'narrow' : 'short' })\n return Array.from({ length: 7 }, (_, i) => fmt.format(new Date(2023, 0, 2 + i)).slice(0, 2))\n})\nconst days = computed(() => {\n const first = view.value\n const offset = (first.getDay() + 6) % 7\n return Array.from({ length: 42 }, (_, i) => {\n const d = new Date(first.getFullYear(), first.getMonth(), 1 - offset + i)\n return { id: isoDate(d), day: d.getDate(), inMonth: d.getMonth() === first.getMonth() }\n })\n})\nconst inRange = (id: string) => !!v.value.end && id > v.value.start && id < v.value.end\n\nfunction pick(id: string) {\n if (!v.value.end || editing.value === 'start') {\n // With a range, keep start ≤ end.\n if (v.value.end && id > v.value.end) update({ start: id, end: id })\n else update({ start: id })\n if (v.value.end) editing.value = 'end'\n }\n else {\n if (id < v.value.start) update({ start: id, end: v.value.start })\n else update({ end: id })\n editing.value = 'start'\n }\n}\nfunction goToday() {\n view.value = monthOf(today)\n}\n\n// --- Options ------------------------------------------------------------------\nconst submenu = ref<'format' | 'timeFormat' | 'remind' | null>(null)\nconst reminders = computed(() => (v.value.time ? REMINDERS_TIME : REMINDERS_DATE))\nconst formatLabel = (f: DateFormat) => m.value.formats[f]\n\nfunction toggleEnd() {\n if (v.value.end) update({ end: null, endTime: null })\n else {\n update({ end: v.value.start, endTime: v.value.time ?? null })\n editing.value = 'end'\n }\n}\nfunction toggleTime() {\n // Date-only and timed reminders differ; reset an incompatible reminder.\n const remind = v.value.remind && v.value.remind !== 'none' ? null : v.value.remind\n if (v.value.time) update({ time: null, endTime: null, remind })\n else update({ time: '09:00', endTime: v.value.end ? '10:00' : null, remind })\n}\nfunction setFormat(format: DateFormat) {\n update({ format })\n submenu.value = null\n}\nfunction setTimeFormat(timeFormat: TimeFormat) {\n update({ timeFormat })\n submenu.value = null\n}\nfunction setRemind(remind: string) {\n update({ remind: remind === 'none' ? null : remind })\n submenu.value = null\n}\n</script>\n\n<template>\n <div class=\"me-datepicker\" @mouseleave=\"submenu = null\">\n <!-- Start and end side by side; stacked once times are shown too (like Notion). -->\n <div class=\"me-datepicker-inputs\" :class=\"{ 'is-split': !!value.end && !value.time }\">\n <div class=\"me-datepicker-field\" :class=\"{ 'is-active': editing === 'start' && !!value.end }\">\n <input v-model=\"draft.start\" class=\"me-datepicker-input\" @focus=\"editing = 'start'\" @keydown.enter.prevent=\"commitDate('start')\" @blur=\"commitDate('start')\">\n <input v-if=\"value.time\" v-model=\"draft.time\" class=\"me-datepicker-input me-datepicker-time\" @keydown.enter.prevent=\"commitTime('time')\" @blur=\"commitTime('time')\">\n </div>\n <div v-if=\"value.end\" class=\"me-datepicker-field\" :class=\"{ 'is-active': editing === 'end' }\">\n <input v-model=\"draft.end\" class=\"me-datepicker-input\" @focus=\"editing = 'end'\" @keydown.enter.prevent=\"commitDate('end')\" @blur=\"commitDate('end')\">\n <input v-if=\"value.time\" v-model=\"draft.endTime\" class=\"me-datepicker-input me-datepicker-time\" @keydown.enter.prevent=\"commitTime('endTime')\" @blur=\"commitTime('endTime')\">\n </div>\n </div>\n\n <div class=\"me-datepicker-head\">\n <span class=\"me-datepicker-month\">{{ monthLabel }}</span>\n <button type=\"button\" class=\"me-datepicker-today\" @click=\"goToday\">\n {{ relative.today }}\n </button>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.prevMonth\" @click=\"view = new Date(view.getFullYear(), view.getMonth() - 1, 1)\">\n <ChevronLeft />\n </button>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.nextMonth\" @click=\"view = new Date(view.getFullYear(), view.getMonth() + 1, 1)\">\n <ChevronRight />\n </button>\n </div>\n <div class=\"me-datepicker-grid\">\n <span v-for=\"(w, i) in weekdays\" :key=\"i\" class=\"me-datepicker-weekday\">{{ w }}</span>\n <button\n v-for=\"d in days\"\n :key=\"d.id\"\n type=\"button\"\n class=\"me-datepicker-day\"\n :class=\"{\n 'is-outside': !d.inMonth,\n 'is-today': d.id === today,\n 'is-selected': d.id === value.start || d.id === value.end,\n 'is-in-range': inRange(d.id),\n }\"\n @click=\"pick(d.id)\"\n >\n {{ d.day }}\n </button>\n </div>\n\n <div class=\"me-datepicker-options\">\n <button type=\"button\" class=\"me-menu-item\" @click=\"toggleEnd\" @mouseenter=\"submenu = null\">\n <span class=\"me-menu-title me-menu-text\">{{ m.endDate }}</span>\n <span class=\"me-switch\" :class=\"{ 'is-on': !!value.end }\" role=\"switch\" :aria-checked=\"!!value.end\" />\n </button>\n <div class=\"me-submenu-anchor\" @mouseenter=\"submenu = 'format'\">\n <button type=\"button\" class=\"me-menu-item\" :class=\"{ 'is-active': submenu === 'format' }\" @click=\"submenu = 'format'\">\n <span class=\"me-menu-title me-menu-text\">{{ m.dateFormat }}</span>\n <span class=\"me-menu-shortcut\">{{ formatLabel(value.format ?? 'relative') }}</span>\n <ChevronRight class=\"me-menu-chevron\" />\n </button>\n <div v-if=\"submenu === 'format'\" class=\"me-popover me-submenu\">\n <button v-for=\"f in DATE_FORMATS\" :key=\"f\" type=\"button\" class=\"me-menu-item\" @click=\"setFormat(f)\">\n <span class=\"me-menu-title me-menu-text\">{{ formatLabel(f) }}</span>\n <Check v-if=\"(value.format ?? 'relative') === f\" class=\"me-menu-check\" />\n </button>\n </div>\n </div>\n <button type=\"button\" class=\"me-menu-item\" @click=\"toggleTime\" @mouseenter=\"submenu = null\">\n <span class=\"me-menu-title me-menu-text\">{{ m.includeTime }}</span>\n <span class=\"me-switch\" :class=\"{ 'is-on': !!value.time }\" role=\"switch\" :aria-checked=\"!!value.time\" />\n </button>\n <div v-if=\"value.time\" class=\"me-submenu-anchor\" @mouseenter=\"submenu = 'timeFormat'\">\n <button type=\"button\" class=\"me-menu-item\" :class=\"{ 'is-active': submenu === 'timeFormat' }\" @click=\"submenu = 'timeFormat'\">\n <span class=\"me-menu-title me-menu-text\">{{ m.timeFormat }}</span>\n <span class=\"me-menu-shortcut\">{{ (value.timeFormat ?? '24') === '12' ? m.hour12 : m.hour24 }}</span>\n <ChevronRight class=\"me-menu-chevron\" />\n </button>\n <div v-if=\"submenu === 'timeFormat'\" class=\"me-popover me-submenu\">\n <button v-for=\"t in (['12', '24'] as const)\" :key=\"t\" type=\"button\" class=\"me-menu-item\" @click=\"setTimeFormat(t)\">\n <span class=\"me-menu-title me-menu-text\">{{ t === '12' ? m.hour12 : m.hour24 }}</span>\n <Check v-if=\"(value.timeFormat ?? '24') === t\" class=\"me-menu-check\" />\n </button>\n </div>\n </div>\n <div class=\"me-submenu-anchor\" @mouseenter=\"submenu = 'remind'\">\n <button type=\"button\" class=\"me-menu-item\" :class=\"{ 'is-active': submenu === 'remind' }\" @click=\"submenu = 'remind'\">\n <span class=\"me-menu-title me-menu-text\">{{ m.remind }}</span>\n <span class=\"me-menu-shortcut\">{{ m.reminders[value.remind ?? 'none'] ?? m.reminders.none }}</span>\n <ChevronRight class=\"me-menu-chevron\" />\n </button>\n <div v-if=\"submenu === 'remind'\" class=\"me-popover me-submenu\">\n <button v-for=\"r in reminders\" :key=\"r\" type=\"button\" class=\"me-menu-item\" @click=\"setRemind(r)\">\n <span class=\"me-menu-title me-menu-text\">{{ m.reminders[r] }}</span>\n <Check v-if=\"(value.remind ?? 'none') === r\" class=\"me-menu-check\" />\n </button>\n </div>\n </div>\n </div>\n\n <div class=\"me-datepicker-options\">\n <button type=\"button\" class=\"me-menu-item\" @click=\"emit('clear')\" @mouseenter=\"submenu = null\">\n <span class=\"me-menu-title me-menu-text\">{{ m.clear }}</span>\n </button>\n </div>\n <a v-if=\"helpUrl\" class=\"me-menu-item me-datepicker-help\" :href=\"helpUrl\" target=\"_blank\" rel=\"noopener noreferrer\">\n <CircleQuestionMark class=\"me-menu-chevron\" />\n <span class=\"me-menu-title me-menu-text\">{{ m.learnReminders }}</span>\n </a>\n </div>\n</template>\n","<script setup lang=\"ts\">\n/**\n * Notion-style date picker for date mentions: typed date/time inputs, month calendar,\n * end date (range), date & time formats, reminders, clear.\n */\nimport { Check, ChevronLeft, ChevronRight, CircleQuestionMark } from '@lucide/vue'\nimport { computed, ref, watch } from 'vue'\nimport {\n DATE_FORMATS, type DateFormat, type DateValue, formatDate, formatTime, isoDate, parseDateInput, parseIsoDate,\n parseTimeInput, REMINDERS_DATE, REMINDERS_TIME, type TimeFormat,\n} from '../date-utils'\nimport type { EditorMessages } from '../locale'\n\nconst props = defineProps<{\n value: DateValue\n locale: string\n messages: EditorMessages['datePicker']\n relative: { today: string, tomorrow: string, yesterday: string }\n helpUrl?: string | null\n}>()\nconst emit = defineEmits<{ change: [value: DateValue], clear: [] }>()\n\nconst m = computed(() => props.messages)\nconst v = computed(() => props.value)\nconst update = (patch: Partial<DateValue>) => emit('change', { ...props.value, ...patch })\n\n// --- Typed inputs -------------------------------------------------------------\n/** Which input the next calendar click fills (Notion alternates start → end). */\nconst editing = ref<'start' | 'end'>('start')\nconst inputFmt = (id: string | null | undefined) => (id ? formatDate(id, props.locale, 'short') : '')\nconst draft = ref({ start: '', end: '', time: '', endTime: '' })\nwatch(() => props.value, (val) => {\n draft.value = {\n start: inputFmt(val.start),\n end: inputFmt(val.end),\n time: val.time ? formatTime(val.time, props.locale, val.timeFormat ?? '24') : '',\n endTime: val.endTime ? formatTime(val.endTime, props.locale, val.timeFormat ?? '24') : '',\n }\n}, { immediate: true, deep: true })\n\nfunction commitDate(which: 'start' | 'end') {\n const parsed = parseDateInput(draft.value[which], props.locale)\n if (!parsed) {\n draft.value[which] = inputFmt(which === 'start' ? v.value.start : v.value.end)\n return\n }\n if (which === 'start') update({ start: parsed })\n else update({ end: parsed })\n view.value = monthOf(parsed)\n}\nfunction commitTime(which: 'time' | 'endTime') {\n const parsed = parseTimeInput(draft.value[which])\n if (parsed) update({ [which]: parsed })\n else draft.value[which] = v.value[which] ? formatTime(v.value[which]!, props.locale, v.value.timeFormat ?? '24') : ''\n}\n\n// --- Calendar -----------------------------------------------------------------\nconst monthOf = (id: string) => {\n const d = parseIsoDate(id) ?? new Date()\n return new Date(d.getFullYear(), d.getMonth(), 1)\n}\nconst view = ref(monthOf(props.value.start))\nconst today = isoDate(new Date())\n// \"Oct 2026\" / \"Tháng 11 2026\": month + year only, short enough for one line.\nconst monthLabel = computed(() => {\n // Chinese / Japanese / Korean read year first: \"2026年10月\".\n if (/^(zh|ja|ko)/.test(props.locale)) return new Intl.DateTimeFormat(props.locale, { year: 'numeric', month: 'long' }).format(view.value)\n const month = new Intl.DateTimeFormat(props.locale, { month: props.locale.startsWith('en') ? 'short' : 'long' }).format(view.value)\n return `${month.charAt(0).toUpperCase()}${month.slice(1)} ${view.value.getFullYear()}`\n})\n// Weeks start on Monday (like Notion's default).\nconst weekdays = computed(() => {\n const fmt = new Intl.DateTimeFormat(props.locale, { weekday: /^(vi|zh)/.test(props.locale) ? 'narrow' : 'short' })\n return Array.from({ length: 7 }, (_, i) => fmt.format(new Date(2023, 0, 2 + i)).slice(0, 2))\n})\nconst days = computed(() => {\n const first = view.value\n const offset = (first.getDay() + 6) % 7\n return Array.from({ length: 42 }, (_, i) => {\n const d = new Date(first.getFullYear(), first.getMonth(), 1 - offset + i)\n return { id: isoDate(d), day: d.getDate(), inMonth: d.getMonth() === first.getMonth() }\n })\n})\nconst inRange = (id: string) => !!v.value.end && id > v.value.start && id < v.value.end\n\nfunction pick(id: string) {\n if (!v.value.end || editing.value === 'start') {\n // With a range, keep start ≤ end.\n if (v.value.end && id > v.value.end) update({ start: id, end: id })\n else update({ start: id })\n if (v.value.end) editing.value = 'end'\n }\n else {\n if (id < v.value.start) update({ start: id, end: v.value.start })\n else update({ end: id })\n editing.value = 'start'\n }\n}\nfunction goToday() {\n view.value = monthOf(today)\n}\n\n// --- Options ------------------------------------------------------------------\nconst submenu = ref<'format' | 'timeFormat' | 'remind' | null>(null)\nconst reminders = computed(() => (v.value.time ? REMINDERS_TIME : REMINDERS_DATE))\nconst formatLabel = (f: DateFormat) => m.value.formats[f]\n\nfunction toggleEnd() {\n if (v.value.end) update({ end: null, endTime: null })\n else {\n update({ end: v.value.start, endTime: v.value.time ?? null })\n editing.value = 'end'\n }\n}\nfunction toggleTime() {\n // Date-only and timed reminders differ; reset an incompatible reminder.\n const remind = v.value.remind && v.value.remind !== 'none' ? null : v.value.remind\n if (v.value.time) update({ time: null, endTime: null, remind })\n else update({ time: '09:00', endTime: v.value.end ? '10:00' : null, remind })\n}\nfunction setFormat(format: DateFormat) {\n update({ format })\n submenu.value = null\n}\nfunction setTimeFormat(timeFormat: TimeFormat) {\n update({ timeFormat })\n submenu.value = null\n}\nfunction setRemind(remind: string) {\n update({ remind: remind === 'none' ? null : remind })\n submenu.value = null\n}\n</script>\n\n<template>\n <div class=\"me-datepicker\" @mouseleave=\"submenu = null\">\n <!-- Start and end side by side; stacked once times are shown too (like Notion). -->\n <div class=\"me-datepicker-inputs\" :class=\"{ 'is-split': !!value.end && !value.time }\">\n <div class=\"me-datepicker-field\" :class=\"{ 'is-active': editing === 'start' && !!value.end }\">\n <input v-model=\"draft.start\" class=\"me-datepicker-input\" @focus=\"editing = 'start'\" @keydown.enter.prevent=\"commitDate('start')\" @blur=\"commitDate('start')\">\n <input v-if=\"value.time\" v-model=\"draft.time\" class=\"me-datepicker-input me-datepicker-time\" @keydown.enter.prevent=\"commitTime('time')\" @blur=\"commitTime('time')\">\n </div>\n <div v-if=\"value.end\" class=\"me-datepicker-field\" :class=\"{ 'is-active': editing === 'end' }\">\n <input v-model=\"draft.end\" class=\"me-datepicker-input\" @focus=\"editing = 'end'\" @keydown.enter.prevent=\"commitDate('end')\" @blur=\"commitDate('end')\">\n <input v-if=\"value.time\" v-model=\"draft.endTime\" class=\"me-datepicker-input me-datepicker-time\" @keydown.enter.prevent=\"commitTime('endTime')\" @blur=\"commitTime('endTime')\">\n </div>\n </div>\n\n <div class=\"me-datepicker-head\">\n <span class=\"me-datepicker-month\">{{ monthLabel }}</span>\n <button type=\"button\" class=\"me-datepicker-today\" @click=\"goToday\">\n {{ relative.today }}\n </button>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.prevMonth\" @click=\"view = new Date(view.getFullYear(), view.getMonth() - 1, 1)\">\n <ChevronLeft />\n </button>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.nextMonth\" @click=\"view = new Date(view.getFullYear(), view.getMonth() + 1, 1)\">\n <ChevronRight />\n </button>\n </div>\n <div class=\"me-datepicker-grid\">\n <span v-for=\"(w, i) in weekdays\" :key=\"i\" class=\"me-datepicker-weekday\">{{ w }}</span>\n <button\n v-for=\"d in days\"\n :key=\"d.id\"\n type=\"button\"\n class=\"me-datepicker-day\"\n :class=\"{\n 'is-outside': !d.inMonth,\n 'is-today': d.id === today,\n 'is-selected': d.id === value.start || d.id === value.end,\n 'is-in-range': inRange(d.id),\n }\"\n @click=\"pick(d.id)\"\n >\n {{ d.day }}\n </button>\n </div>\n\n <div class=\"me-datepicker-options\">\n <button type=\"button\" class=\"me-menu-item\" @click=\"toggleEnd\" @mouseenter=\"submenu = null\">\n <span class=\"me-menu-title me-menu-text\">{{ m.endDate }}</span>\n <span class=\"me-switch\" :class=\"{ 'is-on': !!value.end }\" role=\"switch\" :aria-checked=\"!!value.end\" />\n </button>\n <div class=\"me-submenu-anchor\" @mouseenter=\"submenu = 'format'\">\n <button type=\"button\" class=\"me-menu-item\" :class=\"{ 'is-active': submenu === 'format' }\" @click=\"submenu = 'format'\">\n <span class=\"me-menu-title me-menu-text\">{{ m.dateFormat }}</span>\n <span class=\"me-menu-shortcut\">{{ formatLabel(value.format ?? 'relative') }}</span>\n <ChevronRight class=\"me-menu-chevron\" />\n </button>\n <div v-if=\"submenu === 'format'\" class=\"me-popover me-submenu\">\n <button v-for=\"f in DATE_FORMATS\" :key=\"f\" type=\"button\" class=\"me-menu-item\" @click=\"setFormat(f)\">\n <span class=\"me-menu-title me-menu-text\">{{ formatLabel(f) }}</span>\n <Check v-if=\"(value.format ?? 'relative') === f\" class=\"me-menu-check\" />\n </button>\n </div>\n </div>\n <button type=\"button\" class=\"me-menu-item\" @click=\"toggleTime\" @mouseenter=\"submenu = null\">\n <span class=\"me-menu-title me-menu-text\">{{ m.includeTime }}</span>\n <span class=\"me-switch\" :class=\"{ 'is-on': !!value.time }\" role=\"switch\" :aria-checked=\"!!value.time\" />\n </button>\n <div v-if=\"value.time\" class=\"me-submenu-anchor\" @mouseenter=\"submenu = 'timeFormat'\">\n <button type=\"button\" class=\"me-menu-item\" :class=\"{ 'is-active': submenu === 'timeFormat' }\" @click=\"submenu = 'timeFormat'\">\n <span class=\"me-menu-title me-menu-text\">{{ m.timeFormat }}</span>\n <span class=\"me-menu-shortcut\">{{ (value.timeFormat ?? '24') === '12' ? m.hour12 : m.hour24 }}</span>\n <ChevronRight class=\"me-menu-chevron\" />\n </button>\n <div v-if=\"submenu === 'timeFormat'\" class=\"me-popover me-submenu\">\n <button v-for=\"t in (['12', '24'] as const)\" :key=\"t\" type=\"button\" class=\"me-menu-item\" @click=\"setTimeFormat(t)\">\n <span class=\"me-menu-title me-menu-text\">{{ t === '12' ? m.hour12 : m.hour24 }}</span>\n <Check v-if=\"(value.timeFormat ?? '24') === t\" class=\"me-menu-check\" />\n </button>\n </div>\n </div>\n <div class=\"me-submenu-anchor\" @mouseenter=\"submenu = 'remind'\">\n <button type=\"button\" class=\"me-menu-item\" :class=\"{ 'is-active': submenu === 'remind' }\" @click=\"submenu = 'remind'\">\n <span class=\"me-menu-title me-menu-text\">{{ m.remind }}</span>\n <span class=\"me-menu-shortcut\">{{ m.reminders[value.remind ?? 'none'] ?? m.reminders.none }}</span>\n <ChevronRight class=\"me-menu-chevron\" />\n </button>\n <div v-if=\"submenu === 'remind'\" class=\"me-popover me-submenu\">\n <button v-for=\"r in reminders\" :key=\"r\" type=\"button\" class=\"me-menu-item\" @click=\"setRemind(r)\">\n <span class=\"me-menu-title me-menu-text\">{{ m.reminders[r] }}</span>\n <Check v-if=\"(value.remind ?? 'none') === r\" class=\"me-menu-check\" />\n </button>\n </div>\n </div>\n </div>\n\n <div class=\"me-datepicker-options\">\n <button type=\"button\" class=\"me-menu-item\" @click=\"emit('clear')\" @mouseenter=\"submenu = null\">\n <span class=\"me-menu-title me-menu-text\">{{ m.clear }}</span>\n </button>\n </div>\n <a v-if=\"helpUrl\" class=\"me-menu-item me-datepicker-help\" :href=\"helpUrl\" target=\"_blank\" rel=\"noopener noreferrer\">\n <CircleQuestionMark class=\"me-menu-chevron\" />\n <span class=\"me-menu-title me-menu-text\">{{ m.learnReminders }}</span>\n </a>\n </div>\n</template>\n","<script setup lang=\"ts\">\n/**\n * @mention chip. Click (when editable):\n * - date → calendar to change the date\n * - person/page → searchable list to switch to someone/something else\n * Read-only: calls the block's `onClick`, or opens a page's link.\n */\nimport { NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport { autoUpdate, computePosition, flip, offset, shift } from '@floating-ui/dom'\nimport { Calendar, ExternalLink, FileText, User } from '@lucide/vue'\nimport { computed, nextTick, onBeforeUnmount, onMounted, ref, shallowRef, watch } from 'vue'\nimport DatePicker from '../components/DatePicker.vue'\nimport { useScope } from '../composables/useScope'\nimport { type DateValue, formatDateValue, reminderTime } from '../date-utils'\nimport type { MentionItem, MentionOptions } from '../extensions/mention'\nimport { readTokenPx } from '../theme/read'\nimport { safeUrl } from '../safe-url'\n\nconst props = defineProps(nodeViewProps)\n\nconst scope = useScope(() => props.editor)\nconst config = computed(() => props.editor.storage.meiConfig)\nconst m = computed(() => config.value.messages.mention)\nconst options = computed(() => props.extension.options as MentionOptions)\nconst kind = computed(() => (props.node.attrs.kind ?? 'user') as MentionItem['kind'])\n\n/** A date mention's value, from its attributes (id = start date). */\nconst dateValue = computed<DateValue>(() => {\n const a = props.node.attrs\n return { start: a.id, end: a.end, time: a.time, endTime: a.endTime, format: a.format ?? 'relative', timeFormat: a.timeFormat, remind: a.remind }\n})\n/** Dates render from the stored value, so relative labels and locale stay current. */\nconst label = computed(() => (kind.value === 'date'\n ? formatDateValue(dateValue.value, config.value.locale, m.value)\n : props.node.attrs.label ?? props.node.attrs.id))\n\n// --- Popover ------------------------------------------------------------------\nconst open = ref(false)\nconst chip = ref<HTMLElement | null>(null)\nconst panel = ref<HTMLElement | null>(null)\nlet cleanup: (() => void) | null = null\n\n// Close on clicks outside the popover — but not on the chip itself (it toggles).\nfunction onDocPointer(e: PointerEvent) {\n if (!open.value) return\n const t = e.target as Node\n if (panel.value?.contains(t) || chip.value?.contains(t)) return\n close()\n}\nonMounted(() => document.addEventListener('pointerdown', onDocPointer, true))\n\nfunction position() {\n const el = panel.value\n const ref = chip.value\n if (!el || !ref) return\n const gap = readTokenPx(props.editor.view.dom, 'popover.offset')\n cleanup?.()\n cleanup = autoUpdate(ref, el, () => {\n computePosition(ref, el, { placement: 'bottom-start', strategy: 'fixed', middleware: [offset(gap), flip({ padding: gap }), shift({ padding: gap })] })\n .then(({ x, y }) => Object.assign(el.style, { left: `${x}px`, top: `${y}px` }))\n })\n}\n\n/** Link and avatar from the document, only if safe (never `javascript:`). */\nconst href = computed(() => safeUrl(props.node.attrs.href))\nconst avatar = computed(() => safeUrl(props.node.attrs.avatar, 'image'))\n\nfunction onClick(e: MouseEvent) {\n if (!props.editor.isEditable) {\n const item = props.node.attrs as MentionItem\n if (options.value.onClick) options.value.onClick(item)\n else if (href.value) window.open(href.value, '_blank', 'noopener')\n return\n }\n e.preventDefault()\n if (open.value) return close()\n open.value = true\n query.value = ''\n nextTick(() => {\n position()\n searchInput.value?.focus()\n })\n}\n\nfunction close() {\n open.value = false\n cleanup?.()\n cleanup = null\n}\n\nfunction apply(attrs: Record<string, unknown>) {\n props.updateAttributes(attrs)\n close()\n props.editor.commands.focus()\n}\n\n// --- Date ---------------------------------------------------------------------\n/** Saves changes right away and keeps the picker open (like Notion). */\nfunction changeDate(next: DateValue) {\n const before = dateValue.value.remind ?? null\n props.updateAttributes({\n id: next.start,\n end: next.end ?? null,\n time: next.time ?? null,\n endTime: next.endTime ?? null,\n format: next.format ?? 'relative',\n timeFormat: next.timeFormat ?? null,\n remind: next.remind ?? null,\n // Plain-text label (copy/export): absolute, so it doesn't go stale.\n label: formatDateValue({ ...next, format: next.format === 'relative' ? 'short' : next.format }, config.value.locale),\n })\n if ((next.remind ?? null) !== before || (next.remind && (next.start !== dateValue.value.start || next.time !== dateValue.value.time))) {\n const fireAt = reminderTime(next)\n options.value.onRemind?.(fireAt && next.remind ? { date: next.start, time: next.time ?? null, remind: next.remind, fireAt } : null, next)\n }\n}\nfunction clearDate() {\n close()\n props.deleteNode()\n props.editor.commands.focus()\n}\n\n// --- People / pages -------------------------------------------------------------\nconst query = ref('')\nconst results = shallowRef<MentionItem[]>([])\nconst active = ref(0)\nconst searchInput = ref<HTMLInputElement | null>(null)\nlet searchToken = 0\n\nwatch([query, open], async () => {\n if (!open.value || kind.value === 'date') return\n const token = ++searchToken\n const found = options.value.search ? await options.value.search(query.value) : []\n if (token !== searchToken) return\n results.value = found.filter(r => r.kind !== 'date')\n active.value = 0\n})\n\nfunction pickItem(item: MentionItem) {\n apply({ id: item.id, label: item.label, kind: item.kind, href: item.href ?? null, avatar: item.avatar ?? null })\n}\n\nfunction onKeydown(e: KeyboardEvent) {\n e.stopPropagation()\n const n = results.value.length\n if (e.key === 'Escape') {\n close()\n props.editor.commands.focus()\n }\n else if (n && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {\n e.preventDefault()\n active.value = (active.value + (e.key === 'ArrowDown' ? 1 : n - 1)) % n\n }\n else if (e.key === 'Enter' && results.value[active.value]) {\n e.preventDefault()\n pickItem(results.value[active.value]!)\n }\n}\n\nconst ICONS = { user: User, page: FileText, date: Calendar }\nonBeforeUnmount(() => {\n cleanup?.()\n document.removeEventListener('pointerdown', onDocPointer, true)\n})\n</script>\n\n<template>\n <NodeViewWrapper as=\"span\" class=\"me-mention-wrap\">\n <span\n ref=\"chip\"\n class=\"me-mention\"\n :class=\"[`me-mention--${kind}`, { 'is-selected': selected, 'is-open': open }]\"\n :data-kind=\"kind\"\n @click=\"onClick\"\n >\n <img v-if=\"kind === 'user' && avatar\" class=\"me-mention-avatar\" :src=\"avatar\" alt=\"\">\n <FileText v-else-if=\"kind === 'page'\" class=\"me-mention-icon\" />\n <span>{{ kind === 'page' ? '' : '@' }}{{ label }}</span>\n </span>\n\n <Teleport to=\"body\">\n <div\n v-if=\"open\"\n ref=\"panel\"\n v-bind=\"scope\"\n class=\"me-popover me-mention-popover\"\n :class=\"{ 'me-mention-popover--date': kind === 'date' }\"\n contenteditable=\"false\"\n @mousedown.stop\n @keydown=\"onKeydown\"\n >\n <DatePicker\n v-if=\"kind === 'date'\"\n :value=\"dateValue\"\n :locale=\"config.locale\"\n :messages=\"config.messages.datePicker\"\n :relative=\"m\"\n :help-url=\"options.reminderHelpUrl\"\n @change=\"changeDate\"\n @clear=\"clearDate\"\n />\n <template v-else>\n <input ref=\"searchInput\" v-model=\"query\" class=\"me-input me-mention-search\" :placeholder=\"m.searchPlaceholder\">\n <div class=\"me-mention-results\">\n <button\n v-for=\"(item, i) in results\"\n :key=\"`${item.kind}-${item.id}`\"\n type=\"button\"\n class=\"me-menu-item\"\n :class=\"{ 'is-active': i === active, 'is-current': item.id === node.attrs.id }\"\n @mouseenter=\"active = i\"\n @click=\"pickItem(item)\"\n >\n <img v-if=\"safeUrl(item.avatar, 'image')\" class=\"me-menu-icon me-avatar\" :src=\"safeUrl(item.avatar, 'image')!\" alt=\"\">\n <span v-else class=\"me-menu-icon\"><component :is=\"ICONS[item.kind]\" /></span>\n <span class=\"me-menu-text\">\n <span class=\"me-menu-title\">{{ item.label }}</span>\n <span v-if=\"item.description\" class=\"me-menu-desc\">{{ item.description }}</span>\n </span>\n </button>\n <div v-if=\"!results.length\" class=\"me-menu-empty\">\n {{ options.search ? m.empty : m.noSearch }}\n </div>\n </div>\n <a v-if=\"kind === 'page' && href\" class=\"me-menu-item me-mention-open\" :href=\"href\" target=\"_blank\" rel=\"noopener noreferrer\">\n <span class=\"me-menu-icon\"><ExternalLink /></span>\n <span class=\"me-menu-title me-menu-text\">{{ m.openPage }}</span>\n </a>\n </template>\n </div>\n </Teleport>\n </NodeViewWrapper>\n</template>\n","<script setup lang=\"ts\">\n/**\n * @mention chip. Click (when editable):\n * - date → calendar to change the date\n * - person/page → searchable list to switch to someone/something else\n * Read-only: calls the block's `onClick`, or opens a page's link.\n */\nimport { NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport { autoUpdate, computePosition, flip, offset, shift } from '@floating-ui/dom'\nimport { Calendar, ExternalLink, FileText, User } from '@lucide/vue'\nimport { computed, nextTick, onBeforeUnmount, onMounted, ref, shallowRef, watch } from 'vue'\nimport DatePicker from '../components/DatePicker.vue'\nimport { useScope } from '../composables/useScope'\nimport { type DateValue, formatDateValue, reminderTime } from '../date-utils'\nimport type { MentionItem, MentionOptions } from '../extensions/mention'\nimport { readTokenPx } from '../theme/read'\nimport { safeUrl } from '../safe-url'\n\nconst props = defineProps(nodeViewProps)\n\nconst scope = useScope(() => props.editor)\nconst config = computed(() => props.editor.storage.meiConfig)\nconst m = computed(() => config.value.messages.mention)\nconst options = computed(() => props.extension.options as MentionOptions)\nconst kind = computed(() => (props.node.attrs.kind ?? 'user') as MentionItem['kind'])\n\n/** A date mention's value, from its attributes (id = start date). */\nconst dateValue = computed<DateValue>(() => {\n const a = props.node.attrs\n return { start: a.id, end: a.end, time: a.time, endTime: a.endTime, format: a.format ?? 'relative', timeFormat: a.timeFormat, remind: a.remind }\n})\n/** Dates render from the stored value, so relative labels and locale stay current. */\nconst label = computed(() => (kind.value === 'date'\n ? formatDateValue(dateValue.value, config.value.locale, m.value)\n : props.node.attrs.label ?? props.node.attrs.id))\n\n// --- Popover ------------------------------------------------------------------\nconst open = ref(false)\nconst chip = ref<HTMLElement | null>(null)\nconst panel = ref<HTMLElement | null>(null)\nlet cleanup: (() => void) | null = null\n\n// Close on clicks outside the popover — but not on the chip itself (it toggles).\nfunction onDocPointer(e: PointerEvent) {\n if (!open.value) return\n const t = e.target as Node\n if (panel.value?.contains(t) || chip.value?.contains(t)) return\n close()\n}\nonMounted(() => document.addEventListener('pointerdown', onDocPointer, true))\n\nfunction position() {\n const el = panel.value\n const ref = chip.value\n if (!el || !ref) return\n const gap = readTokenPx(props.editor.view.dom, 'popover.offset')\n cleanup?.()\n cleanup = autoUpdate(ref, el, () => {\n computePosition(ref, el, { placement: 'bottom-start', strategy: 'fixed', middleware: [offset(gap), flip({ padding: gap }), shift({ padding: gap })] })\n .then(({ x, y }) => Object.assign(el.style, { left: `${x}px`, top: `${y}px` }))\n })\n}\n\n/** Link and avatar from the document, only if safe (never `javascript:`). */\nconst href = computed(() => safeUrl(props.node.attrs.href))\nconst avatar = computed(() => safeUrl(props.node.attrs.avatar, 'image'))\n\nfunction onClick(e: MouseEvent) {\n if (!props.editor.isEditable) {\n const item = props.node.attrs as MentionItem\n if (options.value.onClick) options.value.onClick(item)\n else if (href.value) window.open(href.value, '_blank', 'noopener')\n return\n }\n e.preventDefault()\n if (open.value) return close()\n open.value = true\n query.value = ''\n nextTick(() => {\n position()\n searchInput.value?.focus()\n })\n}\n\nfunction close() {\n open.value = false\n cleanup?.()\n cleanup = null\n}\n\nfunction apply(attrs: Record<string, unknown>) {\n props.updateAttributes(attrs)\n close()\n props.editor.commands.focus()\n}\n\n// --- Date ---------------------------------------------------------------------\n/** Saves changes right away and keeps the picker open (like Notion). */\nfunction changeDate(next: DateValue) {\n const before = dateValue.value.remind ?? null\n props.updateAttributes({\n id: next.start,\n end: next.end ?? null,\n time: next.time ?? null,\n endTime: next.endTime ?? null,\n format: next.format ?? 'relative',\n timeFormat: next.timeFormat ?? null,\n remind: next.remind ?? null,\n // Plain-text label (copy/export): absolute, so it doesn't go stale.\n label: formatDateValue({ ...next, format: next.format === 'relative' ? 'short' : next.format }, config.value.locale),\n })\n if ((next.remind ?? null) !== before || (next.remind && (next.start !== dateValue.value.start || next.time !== dateValue.value.time))) {\n const fireAt = reminderTime(next)\n options.value.onRemind?.(fireAt && next.remind ? { date: next.start, time: next.time ?? null, remind: next.remind, fireAt } : null, next)\n }\n}\nfunction clearDate() {\n close()\n props.deleteNode()\n props.editor.commands.focus()\n}\n\n// --- People / pages -------------------------------------------------------------\nconst query = ref('')\nconst results = shallowRef<MentionItem[]>([])\nconst active = ref(0)\nconst searchInput = ref<HTMLInputElement | null>(null)\nlet searchToken = 0\n\nwatch([query, open], async () => {\n if (!open.value || kind.value === 'date') return\n const token = ++searchToken\n const found = options.value.search ? await options.value.search(query.value) : []\n if (token !== searchToken) return\n results.value = found.filter(r => r.kind !== 'date')\n active.value = 0\n})\n\nfunction pickItem(item: MentionItem) {\n apply({ id: item.id, label: item.label, kind: item.kind, href: item.href ?? null, avatar: item.avatar ?? null })\n}\n\nfunction onKeydown(e: KeyboardEvent) {\n e.stopPropagation()\n const n = results.value.length\n if (e.key === 'Escape') {\n close()\n props.editor.commands.focus()\n }\n else if (n && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {\n e.preventDefault()\n active.value = (active.value + (e.key === 'ArrowDown' ? 1 : n - 1)) % n\n }\n else if (e.key === 'Enter' && results.value[active.value]) {\n e.preventDefault()\n pickItem(results.value[active.value]!)\n }\n}\n\nconst ICONS = { user: User, page: FileText, date: Calendar }\nonBeforeUnmount(() => {\n cleanup?.()\n document.removeEventListener('pointerdown', onDocPointer, true)\n})\n</script>\n\n<template>\n <NodeViewWrapper as=\"span\" class=\"me-mention-wrap\">\n <span\n ref=\"chip\"\n class=\"me-mention\"\n :class=\"[`me-mention--${kind}`, { 'is-selected': selected, 'is-open': open }]\"\n :data-kind=\"kind\"\n @click=\"onClick\"\n >\n <img v-if=\"kind === 'user' && avatar\" class=\"me-mention-avatar\" :src=\"avatar\" alt=\"\">\n <FileText v-else-if=\"kind === 'page'\" class=\"me-mention-icon\" />\n <span>{{ kind === 'page' ? '' : '@' }}{{ label }}</span>\n </span>\n\n <Teleport to=\"body\">\n <div\n v-if=\"open\"\n ref=\"panel\"\n v-bind=\"scope\"\n class=\"me-popover me-mention-popover\"\n :class=\"{ 'me-mention-popover--date': kind === 'date' }\"\n contenteditable=\"false\"\n @mousedown.stop\n @keydown=\"onKeydown\"\n >\n <DatePicker\n v-if=\"kind === 'date'\"\n :value=\"dateValue\"\n :locale=\"config.locale\"\n :messages=\"config.messages.datePicker\"\n :relative=\"m\"\n :help-url=\"options.reminderHelpUrl\"\n @change=\"changeDate\"\n @clear=\"clearDate\"\n />\n <template v-else>\n <input ref=\"searchInput\" v-model=\"query\" class=\"me-input me-mention-search\" :placeholder=\"m.searchPlaceholder\">\n <div class=\"me-mention-results\">\n <button\n v-for=\"(item, i) in results\"\n :key=\"`${item.kind}-${item.id}`\"\n type=\"button\"\n class=\"me-menu-item\"\n :class=\"{ 'is-active': i === active, 'is-current': item.id === node.attrs.id }\"\n @mouseenter=\"active = i\"\n @click=\"pickItem(item)\"\n >\n <img v-if=\"safeUrl(item.avatar, 'image')\" class=\"me-menu-icon me-avatar\" :src=\"safeUrl(item.avatar, 'image')!\" alt=\"\">\n <span v-else class=\"me-menu-icon\"><component :is=\"ICONS[item.kind]\" /></span>\n <span class=\"me-menu-text\">\n <span class=\"me-menu-title\">{{ item.label }}</span>\n <span v-if=\"item.description\" class=\"me-menu-desc\">{{ item.description }}</span>\n </span>\n </button>\n <div v-if=\"!results.length\" class=\"me-menu-empty\">\n {{ options.search ? m.empty : m.noSearch }}\n </div>\n </div>\n <a v-if=\"kind === 'page' && href\" class=\"me-menu-item me-mention-open\" :href=\"href\" target=\"_blank\" rel=\"noopener noreferrer\">\n <span class=\"me-menu-icon\"><ExternalLink /></span>\n <span class=\"me-menu-title me-menu-text\">{{ m.openPage }}</span>\n </a>\n </template>\n </div>\n </Teleport>\n </NodeViewWrapper>\n</template>\n","import Mention from '@tiptap/extension-mention'\nimport { type JSONContent, mergeAttributes } from '@tiptap/core'\nimport { PluginKey } from '@tiptap/pm/state'\nimport type { SuggestionOptions } from '@tiptap/suggestion'\nimport MentionMenu from '../components/MentionMenu.vue'\nimport { blockNodeView } from '../nodeviews/renderer'\nimport MentionView from '../nodeviews/MentionView.vue'\nimport { type DateValue, isoDate, reminderTime } from '../date-utils'\n\nexport { formatDateValue, formatMentionDate, isoDate, parseIsoDate, reminderTime, type DateFormat, type DateValue, type TimeFormat } from '../date-utils'\nimport { suggestionRenderer } from './suggestion-renderer'\nimport { safeUrl } from '../safe-url'\n\nexport type MentionKind = 'user' | 'page' | 'date'\n\nexport interface MentionItem {\n id: string\n label: string\n kind: MentionKind\n /** Avatar image URL (users) — optional. */\n avatar?: string\n /** Link for pages — opened on ⌘/Ctrl+click when no `onClick` is given. */\n href?: string\n /** Secondary text in the menu (email, path…). */\n description?: string\n}\n\nexport interface MentionReminder {\n /** Start date of the mention (`YYYY-MM-DD`). */\n date: string\n time: string | null\n /** Preset, e.g. `'1d'`, `'30m'`. */\n remind: string\n /** When to notify. */\n fireAt: Date\n}\n\nexport interface MentionOptions {\n /** Finds people/pages for `@query`. Dates (today, tomorrow…) are built in. */\n search: ((query: string) => MentionItem[] | Promise<MentionItem[]>) | null\n /** Called when a mention is clicked (read-only editors). */\n onClick: ((item: MentionItem) => void) | null\n /**\n * Called when a date mention's reminder is set or cleared. The editor can't send\n * notifications itself — schedule them on your backend (see `getMentionReminders`).\n */\n onRemind: ((reminder: MentionReminder | null, value: DateValue) => void) | null\n /** \"Learn about reminders\" link in the date picker (hidden when not set). */\n reminderHelpUrl: string | null\n}\n\n/** All reminders in a document, for scheduling notifications server-side. */\nexport function getMentionReminders(doc: JSONContent): MentionReminder[] {\n const out: MentionReminder[] = []\n const visit = (node: JSONContent) => {\n const a = node.attrs ?? {}\n if (node.type === 'mention' && a.kind === 'date' && a.remind && a.remind !== 'none') {\n const fireAt = reminderTime({ start: a.id, time: a.time, remind: a.remind })\n if (fireAt) out.push({ date: a.id, time: a.time ?? null, remind: a.remind, fireAt })\n }\n node.content?.forEach(visit)\n }\n visit(doc)\n return out\n}\n\nexport const mentionPluginKey = new PluginKey('mention')\n\nconst iso = isoDate\n\n/** Date suggestions: today/tomorrow/yesterday, plus a typed date like 25/12 or 2026-12-25. */\nfunction dateItems(query: string, labels: { today: string, tomorrow: string, yesterday: string }, locale: string): MentionItem[] {\n const day = (offset: number) => {\n const d = new Date()\n d.setDate(d.getDate() + offset)\n return d\n }\n const fmt = new Intl.DateTimeFormat(locale, { day: 'numeric', month: 'short', year: 'numeric' })\n const make = (d: Date, label: string): MentionItem => ({ id: iso(d), kind: 'date', label, description: fmt.format(d) })\n const items = [make(day(0), labels.today), make(day(1), labels.tomorrow), make(day(-1), labels.yesterday)]\n\n const typed = query.match(/^(\\d{1,2})[/.-](\\d{1,2})(?:[/.-](\\d{2,4}))?$/) ?? query.match(/^(\\d{4})-(\\d{1,2})-(\\d{1,2})$/)\n if (typed) {\n const [, a, b, c] = typed\n const d = query.includes('-') && a!.length === 4\n ? new Date(Number(a), Number(b) - 1, Number(c))\n : new Date(c ? Number(c.length === 2 ? `20${c}` : c) : new Date().getFullYear(), Number(b) - 1, Number(a))\n if (!Number.isNaN(d.getTime())) items.unshift(make(d, fmt.format(d)))\n }\n const norm = (t: string) => t.normalize('NFD').replace(/[\\u0300-\\u036F]/g, '').replace(/đ/g, 'd').toLowerCase()\n const q = norm(query)\n return typed ? items : items.filter(i => !q || norm(i.label).includes(q) || i.id.includes(q))\n}\n\n/** `@` mentions of people, pages and dates. */\nexport const MentionNode = Mention.extend<MentionOptions & Record<string, any>>({\n addOptions() {\n return { ...this.parent?.(), search: null, onClick: null, onRemind: null, reminderHelpUrl: null }\n },\n\n addAttributes() {\n // `key` is the attribute name in JSON, `data` its `data-*` name in HTML.\n const attr = (key: string, data = key) => ({\n default: null,\n parseHTML: (el: HTMLElement) => el.getAttribute(`data-${data}`),\n renderHTML: (attrs: Record<string, any>) => (attrs[key] ? { [`data-${data}`]: attrs[key] } : {}),\n })\n return {\n ...this.parent?.(),\n kind: attr('kind'),\n // Pasted HTML can carry any data-href / data-avatar: only web, blob and relative URLs.\n href: { ...attr('href'), parseHTML: (el: HTMLElement) => safeUrl(el.getAttribute('data-href')) },\n avatar: { ...attr('avatar'), parseHTML: (el: HTMLElement) => safeUrl(el.getAttribute('data-avatar'), 'image') },\n // Date mentions (id = start date): see DateValue.\n end: attr('end'),\n time: attr('time'),\n endTime: attr('endTime', 'end-time'),\n format: attr('format'),\n timeFormat: attr('timeFormat', 'time-format'),\n remind: attr('remind'),\n }\n },\n\n renderHTML({ node, HTMLAttributes }) {\n const prefix = node.attrs.kind === 'page' ? '' : '@'\n return ['span', mergeAttributes({ 'data-type': 'mention', 'class': `me-mention me-mention--${node.attrs.kind ?? 'user'}` }, HTMLAttributes), `${prefix}${node.attrs.label ?? node.attrs.id}`]\n },\n\n renderText({ node }) {\n return `${node.attrs.kind === 'page' ? '' : '@'}${node.attrs.label ?? node.attrs.id}`\n },\n\n // Clickable chip: date picker for dates, people/page picker otherwise (read-only: onClick/href).\n addNodeView() {\n return blockNodeView(MentionView)\n },\n}).configure({ suggestion: mentionSuggestion() })\n\nfunction mentionSuggestion(): Omit<SuggestionOptions<MentionItem>, 'editor'> {\n return {\n char: '@',\n pluginKey: mentionPluginKey,\n allowSpaces: true,\n items: async ({ query, editor }) => {\n const ext = editor.extensionManager.extensions.find(e => e.name === 'mention')\n const search = ext?.options.search as MentionOptions['search']\n const { messages, locale } = editor.storage.meiConfig\n const people = search ? await search(query) : []\n return [...people, ...dateItems(query, messages.mention, locale)].slice(0, 12)\n },\n command: ({ editor, range, props: item }) => {\n editor.chain().focus().insertContentAt(range, [\n // Dates show the actual date, not \"Today\", which would be wrong tomorrow.\n { type: 'mention', attrs: { id: item.id, label: item.kind === 'date' ? item.description : item.label, kind: item.kind, href: item.href ?? null, avatar: item.avatar ?? null } },\n { type: 'text', text: ' ' },\n ]).run()\n },\n render: suggestionRenderer<MentionItem>(MentionMenu, mentionPluginKey, {\n // Close once the query clearly isn't a name anymore.\n onUpdate: props => (props.query.split(' ').length > 3 ? false : undefined),\n }),\n }\n}\n","import { Extension } from '@tiptap/core'\n\n/** Marker: when loaded, code blocks in the `mermaid` language show a live diagram. */\nexport const MermaidPreview = Extension.create({ name: 'mermaidPreview' })\n\nexport const SAMPLE_MERMAID = 'flowchart LR\\n A[Ý tưởng] --> B{Duyệt?}\\n B -- Có --> C[Làm]\\n B -- Không --> A'\n","<script setup lang=\"ts\">\nimport { NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport { TextSelection } from '@tiptap/pm/state'\nimport { computed, onBeforeUnmount, shallowRef } from 'vue'\n\nconst props = defineProps(nodeViewProps)\nconst m = computed(() => props.editor.storage.meiConfig.messages.toc)\n\ninterface Entry { pos: number, level: number, text: string }\nconst entries = shallowRef<Entry[]>([])\n\nfunction collect() {\n const list: Entry[] = []\n props.editor.state.doc.descendants((node, pos) => {\n if (node.type.name === 'heading') list.push({ pos, level: node.attrs.level, text: node.textContent })\n else if (node.type.name === 'details' && node.attrs.level) list.push({ pos, level: node.attrs.level, text: node.firstChild?.textContent ?? '' })\n return node.type.name !== 'heading'\n })\n entries.value = list\n}\ncollect()\nprops.editor.on('update', collect)\nonBeforeUnmount(() => props.editor.off('update', collect))\n\nconst minLevel = computed(() => Math.min(...entries.value.map(e => e.level), 4))\n\nfunction go(entry: Entry) {\n const { view } = props.editor\n ;(view.nodeDOM(entry.pos) as HTMLElement | null)?.scrollIntoView({ behavior: 'smooth', block: 'start' })\n view.dispatch(view.state.tr.setSelection(TextSelection.near(view.state.doc.resolve(entry.pos + 1))))\n view.focus()\n}\n</script>\n\n<template>\n <NodeViewWrapper class=\"me-toc\" :class=\"{ 'is-selected': selected }\" contenteditable=\"false\">\n <button\n v-for=\"e in entries\"\n :key=\"e.pos\"\n type=\"button\"\n class=\"me-toc-item\"\n :data-depth=\"e.level - minLevel\"\n @click=\"go(e)\"\n >\n {{ e.text || m.untitled }}\n </button>\n <p v-if=\"!entries.length\" class=\"me-hint\">\n {{ m.empty }}\n </p>\n </NodeViewWrapper>\n</template>\n","<script setup lang=\"ts\">\nimport { NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport { TextSelection } from '@tiptap/pm/state'\nimport { computed, onBeforeUnmount, shallowRef } from 'vue'\n\nconst props = defineProps(nodeViewProps)\nconst m = computed(() => props.editor.storage.meiConfig.messages.toc)\n\ninterface Entry { pos: number, level: number, text: string }\nconst entries = shallowRef<Entry[]>([])\n\nfunction collect() {\n const list: Entry[] = []\n props.editor.state.doc.descendants((node, pos) => {\n if (node.type.name === 'heading') list.push({ pos, level: node.attrs.level, text: node.textContent })\n else if (node.type.name === 'details' && node.attrs.level) list.push({ pos, level: node.attrs.level, text: node.firstChild?.textContent ?? '' })\n return node.type.name !== 'heading'\n })\n entries.value = list\n}\ncollect()\nprops.editor.on('update', collect)\nonBeforeUnmount(() => props.editor.off('update', collect))\n\nconst minLevel = computed(() => Math.min(...entries.value.map(e => e.level), 4))\n\nfunction go(entry: Entry) {\n const { view } = props.editor\n ;(view.nodeDOM(entry.pos) as HTMLElement | null)?.scrollIntoView({ behavior: 'smooth', block: 'start' })\n view.dispatch(view.state.tr.setSelection(TextSelection.near(view.state.doc.resolve(entry.pos + 1))))\n view.focus()\n}\n</script>\n\n<template>\n <NodeViewWrapper class=\"me-toc\" :class=\"{ 'is-selected': selected }\" contenteditable=\"false\">\n <button\n v-for=\"e in entries\"\n :key=\"e.pos\"\n type=\"button\"\n class=\"me-toc-item\"\n :data-depth=\"e.level - minLevel\"\n @click=\"go(e)\"\n >\n {{ e.text || m.untitled }}\n </button>\n <p v-if=\"!entries.length\" class=\"me-hint\">\n {{ m.empty }}\n </p>\n </NodeViewWrapper>\n</template>\n","import { Node } from '@tiptap/core'\nimport { blockNodeView } from '../nodeviews/renderer'\nimport TocView from '../nodeviews/TocView.vue'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n tableOfContents: { insertTableOfContents: () => ReturnType }\n }\n}\n\n/** Table of contents built live from the document's headings and toggle headings. */\nexport const TableOfContents = Node.create({\n name: 'tableOfContents',\n group: 'block',\n atom: true,\n draggable: true,\n parseHTML: () => [{ tag: 'div[data-type=\"table-of-contents\"]' }],\n renderHTML: ({ HTMLAttributes }) => ['div', { ...HTMLAttributes, 'data-type': 'table-of-contents' }],\n addCommands() {\n return { insertTableOfContents: () => ({ commands }) => commands.insertContent({ type: this.name }) }\n },\n addNodeView: () => blockNodeView(TocView),\n})\n","import { AudioLines, AtSign, CodeXml, File, Film, Radical, Sigma, TableOfContents, Workflow } from '@lucide/vue'\nimport { type BlockType, isNode } from '../block-items'\nimport { defineBlock } from '../define-block'\nimport { CodeBlock } from '../extensions/code-block'\nimport { EmojiSuggestion } from '../extensions/emoji'\nimport { FileBlock, type FileBlockOptions, type FileKind } from '../extensions/file-block'\nimport { HtmlBlock, type HtmlBlockOptions } from '../extensions/html-block'\nimport { MathBlock, MathInline } from '../extensions/math'\nimport { MentionNode, type MentionOptions } from '../extensions/mention'\nimport { MermaidPreview, SAMPLE_MERMAID } from '../extensions/mermaid'\nimport { TableOfContents as TocNode } from '../extensions/toc'\n\n/** Table of contents from the document's headings. */\nexport const toc = defineBlock({\n name: 'toc',\n nodes: ['tableOfContents'],\n extensions: () => [TocNode],\n items: () => [{\n id: 'toc',\n icon: TableOfContents,\n group: 'advanced',\n keywords: ['toc', 'table of contents', 'outline', 'muc luc', '目录'],\n insert: c => c.insertTableOfContents(),\n matches: isNode('tableOfContents'),\n }],\n})\n\n/**\n * Equations with KaTeX (peer dependency `katex`, loaded on first use). `$$ ` → block, `$$x$$` → inline.\n * Vue apps also import 'katex/dist/katex.min.css' (the Nuxt module adds it automatically).\n */\nexport const math = defineBlock({\n name: 'math',\n nodes: ['mathBlock'],\n extensions: () => [MathBlock, MathInline],\n items: () => [\n { id: 'mathBlock', icon: Sigma, group: 'advanced', keywords: ['math', 'equation', 'latex', 'katex', 'cong thuc', 'toan', '公式', '数学'], shortcut: '$$', insert: c => c.insertMathBlock(), matches: isNode('mathBlock') },\n { id: 'mathInline', icon: Radical, group: 'advanced', keywords: ['inline math', 'equation', 'latex', 'cong thuc', '行内公式', '公式'], insert: c => c.insertMathInline() },\n ],\n})\n\n/** Mermaid diagrams: code blocks in `mermaid` with a live preview (peer dependency `mermaid`). */\nexport const mermaid = defineBlock({\n name: 'mermaid',\n nodes: ['codeBlock'],\n extensions: () => [CodeBlock, MermaidPreview],\n items: () => [{\n id: 'mermaid',\n icon: Workflow,\n group: 'advanced',\n keywords: ['mermaid', 'diagram', 'flowchart', 'chart', 'so do', '图表', '流程图'],\n insert: c => c.setCodeBlock({ language: 'mermaid' }).insertContent(SAMPLE_MERMAID),\n matches: n => n.type.name === 'codeBlock' && n.attrs.language === 'mermaid',\n }],\n})\n\n/** `:` emoji picker (inserts unicode text). */\nexport const emoji = defineBlock({\n name: 'emoji',\n extensions: () => [EmojiSuggestion],\n})\n\nconst FILE_ICONS = { file: File, audio: AudioLines, video: Film } as const\n\n/** File attachments, audio and video. `file.configure({ upload, maxSize })`. */\nexport const file = defineBlock<FileBlockOptions>({\n name: 'file',\n defaults: { upload: null, maxSize: 10 },\n nodes: ['fileBlock'],\n extensions: o => [FileBlock.configure(o)],\n items: () => (['file', 'audio', 'video'] as FileKind[]).map((kind): BlockType => ({\n id: `file-${kind}`,\n icon: FILE_ICONS[kind],\n group: 'media',\n keywords: kind === 'file' ? ['file', 'attachment', 'upload', 'tep', 'dinh kem', '文件', '附件'] : kind === 'audio' ? ['audio', 'sound', 'music', 'am thanh', '音频', '音乐'] : ['video', 'upload', 'mp4', 'tai len', '视频', '上传'],\n insert: c => c.insertFileBlock(kind),\n matches: n => n.type.name === 'fileBlock' && n.attrs.kind === kind,\n })),\n})\n\n/** `@` mentions: dates built in; people/pages via `mention.configure({ search })`. */\nexport const mention = defineBlock<MentionOptions>({\n name: 'mention',\n defaults: { search: null, onClick: null, onRemind: null, reminderHelpUrl: null },\n extensions: o => [MentionNode.configure(o)],\n items: () => [{\n id: 'mention',\n icon: AtSign,\n group: 'basic',\n keywords: ['mention', 'person', 'page', 'date', 'nhac', 'ngay', '提及', '日期', '成员'],\n insert: c => c.insertContent('@'),\n }],\n})\n\n\n/**\n * Notion-style HTML block: HTML/CSS/JS in a sandboxed frame (edit in place or upload a\n * file). Network access is off by default; `html.configure({ network: ['https://cdn.jsdelivr.net'] })`.\n */\nexport const html = defineBlock<HtmlBlockOptions>({\n name: 'html',\n defaults: { network: false, maxSize: 1024, defaultHeight: 400 },\n nodes: ['htmlBlock'],\n extensions: o => [HtmlBlock.configure(o)],\n items: () => [{\n id: 'html',\n icon: CodeXml,\n group: 'advanced',\n keywords: ['html', 'code', 'widget', 'interactive', 'prototype', 'nhung', 'tuong tac', '网页', '交互'],\n insert: c => c.insertHtmlBlock(),\n matches: isNode('htmlBlock'),\n }],\n})\n","/**\n * Built-in blocks. Pass the ones you want to `<MeiEditor :blocks>`:\n * [...defaultBlocks, math, toc, file.configure({ upload })]\n * Heavy libraries (code grammars, KaTeX, Mermaid, emoji data) load on first use.\n */\nimport type { BlockDefinition } from '../define-block'\nimport { callout, codeBlock, columns, table, toggle, toggleHeading } from './advanced'\nimport { bulletList, divider, heading, orderedList, quote, taskList, text } from './basic'\nimport { embed, image } from './media'\n\nexport { callout, codeBlock, columns, table, toggle, toggleHeading } from './advanced'\nexport { bulletList, divider, heading, orderedList, quote, taskList, text } from './basic'\nexport { emoji, file, html, math, mention, mermaid, toc } from './extras'\nexport { embed, image } from './media'\n\n/** What `<MeiEditor>` loads when `blocks` isn't given. */\nexport const defaultBlocks: BlockDefinition[] = [\n heading, bulletList, orderedList, taskList, quote, divider, codeBlock,\n image, embed, callout, toggle, toggleHeading, table, columns,\n]\n\nexport { BLOCK_NAMES, type BlockName } from '../block-names'\n","import type { Schema } from '@tiptap/pm/model'\nimport type { JSONContent } from '@tiptap/vue-3'\n\n/** What happened while loading a document (see the `content-error` event). */\nexport interface ContentIssue {\n kind: 'unknown' | 'repaired' | 'invalid'\n /** Node type of the affected block. */\n type: string\n message?: string\n}\n\nexport class ContentError extends Error {\n constructor(message: string, public content: unknown) {\n super(message)\n this.name = 'ContentError'\n }\n}\n\n/**\n * Wraps nodes the schema doesn't know into `unknownBlock` / `unknownInline` so the\n * editor can load documents written with other blocks enabled. Unknown marks are dropped.\n */\nexport function wrapUnknown(doc: JSONContent | null | undefined, schema: Schema, issues: ContentIssue[] = []): JSONContent | null {\n if (!doc) return null\n const visit = (node: JSONContent, inline: boolean): JSONContent => {\n const type = node.type && schema.nodes[node.type]\n if (!type) {\n issues.push({ kind: 'unknown', type: String(node.type) })\n return { type: inline ? 'unknownInline' : 'unknownBlock', attrs: { data: node } }\n }\n const out: JSONContent = { ...node }\n if (node.marks) out.marks = node.marks.filter(m => schema.marks[m.type])\n if (node.content) out.content = node.content.map(child => visit(child, type.inlineContent))\n return out\n }\n return visit(doc, false)\n}\n\n/** Light repairs for common invalid JSON: empty text nodes, missing text. */\nfunction repair(node: JSONContent): JSONContent {\n if (!node.content) return node\n const content = node.content\n .filter(child => !(child.type === 'text' && !child.text))\n .map(repair)\n return { ...node, content }\n}\n\n/**\n * Validates a document block by block so one broken block never blanks the editor\n * (Tiptap shows an empty doc on invalid content, and the next save would overwrite it).\n * Fixable blocks are repaired; others are kept verbatim inside `unknownBlock`.\n * Throws {@link ContentError} only when the input isn't a document at all.\n */\nexport function sanitizeContent(doc: unknown, schema: Schema, issues: ContentIssue[] = []): JSONContent | null {\n if (doc == null || doc === '') return null\n if (typeof doc !== 'object' || (doc as JSONContent).type !== 'doc' || !Array.isArray((doc as JSONContent).content ?? [])) {\n throw new ContentError('Content is not a document ({ type: \"doc\", content: [...] })', doc)\n }\n\n const wrapped = wrapUnknown(doc as JSONContent, schema, issues)!\n const valid = (json: JSONContent) => {\n try {\n schema.nodeFromJSON(json).check()\n return true\n }\n catch {\n return false\n }\n }\n\n // Fast path: the whole document is valid (the normal case) — one parse, no per-block work.\n if (valid(wrapped)) return wrapped\n\n const blocks = (wrapped.content ?? []).map((block) => {\n if (valid(block)) return block\n const fixed = repair(block)\n if (valid(fixed)) {\n issues.push({ kind: 'repaired', type: String(block.type) })\n return fixed\n }\n issues.push({ kind: 'invalid', type: String(block.type) })\n return { type: 'unknownBlock', attrs: { data: block, invalid: true } }\n })\n return { ...wrapped, content: blocks }\n}\n\n/** Reverses {@link wrapUnknown}: puts the original JSON back. */\nexport function unwrapUnknown(doc: JSONContent): JSONContent {\n if (doc.type === 'unknownBlock' || doc.type === 'unknownInline') return doc.attrs?.data ?? { type: 'paragraph' }\n return doc.content ? { ...doc, content: doc.content.map(unwrapUnknown) } : doc\n}\n","export { component, PALETTE_NAMES, primitive, semanticBase, semanticDark, semanticLight, type PaletteName, type ThemeTokens } from './tokens'\nexport { baseTokensCss, installBaseTokens, injectStyle, LAYER, overridesCss } from './css'\nexport { cssVar, ref } from './define'\n\n/** Light / dark mode of an editor. `auto` follows `<html class=\"dark\">`. */\nexport type ThemeMode = 'light' | 'dark' | 'auto'\n\n/** Identity helper for typed token overrides: `defineTokens({ color: { accent: '#7c3aed' } })`. */\nexport const defineTokens = <T extends import('./tokens').ThemeTokens>(tokens: T) => tokens\n","import { PALETTE_NAMES } from './theme/tokens'\n\n/** Color names offered in menus. `default` removes the color. Actual colors come from theme tokens. */\nexport const COLORS = ['default', ...PALETTE_NAMES] as const\nexport type ColorName = typeof COLORS[number]\n","<script lang=\"ts\">\nimport { COLORS, type ColorName } from '../colors'\nimport type { RecentColor } from '../recent'\n\nexport interface ColorRow { section: 'recent' | 'text' | 'bg', kind: 'text' | 'bg', color: ColorName }\n\n/** Rows in display order, so parents can drive keyboard navigation by index. */\nexport function colorRows(recent: RecentColor[]): ColorRow[] {\n return [\n ...recent.map(r => ({ section: 'recent' as const, ...r })),\n ...COLORS.map(color => ({ section: 'text' as const, kind: 'text' as const, color })),\n ...COLORS.map(color => ({ section: 'bg' as const, kind: 'bg' as const, color })),\n ]\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Check } from '@lucide/vue'\nimport { computed } from 'vue'\nimport type { EditorMessages } from '../locale'\n\nconst props = defineProps<{\n messages: EditorMessages\n recent: RecentColor[]\n /** Colors currently applied (null = mixed / none). */\n current?: { text: string | null, bg: string | null }\n activeIndex?: number\n}>()\ndefineEmits<{ pick: [kind: 'text' | 'bg', color: ColorName], hover: [index: number] }>()\n\nconst rows = computed(() => colorRows(props.recent))\nconst label = (s: ColorRow['section']) => ({ recent: props.messages.blockMenu.recent, text: props.messages.blockMenu.textColor, bg: props.messages.blockMenu.backgroundColor })[s]\n/** `default` has no data-color, so it falls back to the normal text/background. */\nconst attr = (c: ColorName) => (c === 'default' ? undefined : c)\nconst isCurrent = (row: ColorRow) => row.section !== 'recent' && props.current?.[row.kind] === row.color\nconst name = (row: ColorRow) => {\n const color = props.messages.colors[row.color] ?? row.color\n if (row.section !== 'recent') return color\n return row.kind === 'text' ? props.messages.slash.textColor(color) : props.messages.slash.bgColor(color)\n}\n</script>\n\n<template>\n <template v-for=\"(row, i) in rows\" :key=\"`${row.section}-${row.kind}-${row.color}`\">\n <div v-if=\"i === 0 || rows[i - 1]!.section !== row.section\" class=\"me-menu-label\">\n {{ label(row.section) }}\n </div>\n <button\n type=\"button\"\n class=\"me-menu-item\"\n :class=\"{ 'is-active': i === activeIndex }\"\n :data-index=\"i\"\n @mouseenter=\"$emit('hover', i)\"\n @click=\"$emit('pick', row.kind, row.color)\"\n >\n <span class=\"me-menu-icon\" :class=\"row.kind === 'text' ? 'me-swatch--text' : 'me-swatch--bg'\" :data-color=\"attr(row.color)\">A</span>\n <span class=\"me-menu-title me-menu-text\">{{ name(row) }}</span>\n <Check v-if=\"isCurrent(row)\" class=\"me-menu-check\" />\n </button>\n </template>\n</template>\n","<script lang=\"ts\">\nimport { COLORS, type ColorName } from '../colors'\nimport type { RecentColor } from '../recent'\n\nexport interface ColorRow { section: 'recent' | 'text' | 'bg', kind: 'text' | 'bg', color: ColorName }\n\n/** Rows in display order, so parents can drive keyboard navigation by index. */\nexport function colorRows(recent: RecentColor[]): ColorRow[] {\n return [\n ...recent.map(r => ({ section: 'recent' as const, ...r })),\n ...COLORS.map(color => ({ section: 'text' as const, kind: 'text' as const, color })),\n ...COLORS.map(color => ({ section: 'bg' as const, kind: 'bg' as const, color })),\n ]\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Check } from '@lucide/vue'\nimport { computed } from 'vue'\nimport type { EditorMessages } from '../locale'\n\nconst props = defineProps<{\n messages: EditorMessages\n recent: RecentColor[]\n /** Colors currently applied (null = mixed / none). */\n current?: { text: string | null, bg: string | null }\n activeIndex?: number\n}>()\ndefineEmits<{ pick: [kind: 'text' | 'bg', color: ColorName], hover: [index: number] }>()\n\nconst rows = computed(() => colorRows(props.recent))\nconst label = (s: ColorRow['section']) => ({ recent: props.messages.blockMenu.recent, text: props.messages.blockMenu.textColor, bg: props.messages.blockMenu.backgroundColor })[s]\n/** `default` has no data-color, so it falls back to the normal text/background. */\nconst attr = (c: ColorName) => (c === 'default' ? undefined : c)\nconst isCurrent = (row: ColorRow) => row.section !== 'recent' && props.current?.[row.kind] === row.color\nconst name = (row: ColorRow) => {\n const color = props.messages.colors[row.color] ?? row.color\n if (row.section !== 'recent') return color\n return row.kind === 'text' ? props.messages.slash.textColor(color) : props.messages.slash.bgColor(color)\n}\n</script>\n\n<template>\n <template v-for=\"(row, i) in rows\" :key=\"`${row.section}-${row.kind}-${row.color}`\">\n <div v-if=\"i === 0 || rows[i - 1]!.section !== row.section\" class=\"me-menu-label\">\n {{ label(row.section) }}\n </div>\n <button\n type=\"button\"\n class=\"me-menu-item\"\n :class=\"{ 'is-active': i === activeIndex }\"\n :data-index=\"i\"\n @mouseenter=\"$emit('hover', i)\"\n @click=\"$emit('pick', row.kind, row.color)\"\n >\n <span class=\"me-menu-icon\" :class=\"row.kind === 'text' ? 'me-swatch--text' : 'me-swatch--bg'\" :data-color=\"attr(row.color)\">A</span>\n <span class=\"me-menu-title me-menu-text\">{{ name(row) }}</span>\n <Check v-if=\"isCurrent(row)\" class=\"me-menu-check\" />\n </button>\n </template>\n</template>\n","<script setup lang=\"ts\">\nimport type { Editor } from '@tiptap/vue-3'\nimport type { Component } from 'vue'\nimport { ArrowDown, ArrowUp, Check, ChevronRight, Copy, Link2, Palette, Repeat2, Search, Trash } from '@lucide/vue'\nimport { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'\nimport { type BlockType, blockTitle, turnIntoBlocks } from '../block-items'\nimport {\n type BlockRange, blocksIn, colorBlocks, deleteBlocks, duplicateBlocks, moveBlocks, rangeColors, turnBlocksInto,\n} from '../block-ops'\nimport type { ColorName } from '../colors'\nimport { useClickOutside } from '../composables/useClickOutside'\nimport { useScope } from '../composables/useScope'\nimport { TURN_INTO_SHORTCUTS } from '../extensions/block-selection'\nimport { isMod, kbd } from '../keys'\nimport { pushRecentColor, recent } from '../recent'\nimport { readTokenPx } from '../theme/read'\nimport ColorList, { colorRows } from './ColorList.vue'\n\nconst props = defineProps<{\n editor: Editor\n range: BlockRange\n anchor: DOMRect\n}>()\nconst emit = defineEmits<{ close: [], copyLink: [id: string] }>()\n\nconst root = ref<HTMLElement | null>(null)\nconst input = ref<HTMLInputElement | null>(null)\nuseClickOutside(root, ref(true), () => emit('close'))\n\nconst m = computed(() => props.editor.storage.meiConfig.messages)\nconst scope = useScope(() => props.editor)\nconst blocks = computed(() => blocksIn(props.editor.state.doc, props.range))\nconst targets = computed(() => turnIntoBlocks(props.editor))\n/** Current type when every selected block has the same one. */\nconst current = computed(() => {\n const types = blocks.value.map(b => targets.value.find(t => t.matches?.(b.node))?.id)\n return types.every(t => t && t === types[0]) ? targets.value.find(t => t.id === types[0]) : undefined\n})\nconst canTurnInto = computed(() => blocks.value.every(b => targets.value.some(t => t.matches?.(b.node)) || b.node.type.name === 'callout'))\nconst hasText = computed(() => blocks.value.some(b => b.node.textContent.length > 0 || b.node.isTextblock))\nconst colors = computed(() => rangeColors(props.editor.state, props.range))\nconst blockId = computed(() => (blocks.value.length === 1 ? blocks.value[0]!.node.attrs.id as string | undefined : undefined))\n\n// --- Rows ------------------------------------------------------------------\ninterface Row {\n key: string\n label: string\n icon?: Component\n /** Swatch for color rows. */\n swatch?: { kind: 'text' | 'bg', color: ColorName }\n hint?: string\n checked?: boolean\n submenu?: 'turn' | 'color'\n group?: string\n run?: () => void\n}\n\nfunction done(fn: () => void) {\n emit('close')\n fn()\n}\nconst shortcutFor = (b: BlockType) => {\n const key = Object.entries(TURN_INTO_SHORTCUTS).find(([, id]) => id === b.id)?.[0]\n return key ? kbd(`Mod-Alt-${key}`) : undefined\n}\nconst turnInto = (b: BlockType) => done(() => turnBlocksInto(props.editor, props.range, b))\nfunction pickColor(kind: 'text' | 'bg', color: ColorName) {\n if (color !== 'default') pushRecentColor({ kind, color })\n done(() => colorBlocks(props.editor, props.range, kind, color))\n}\n\nconst actions = computed<Row[]>(() => [\n { key: 'delete', label: m.value.blockMenu.delete, icon: Trash, hint: kbd('Delete'), run: () => done(() => deleteBlocks(props.editor, props.range)) },\n { key: 'duplicate', label: m.value.blockMenu.duplicate, icon: Copy, hint: kbd('Mod-d'), run: () => done(() => duplicateBlocks(props.editor, props.range)) },\n ...(blockId.value ? [{ key: 'link', label: m.value.blockMenu.copyLink, icon: Link2, run: () => done(() => emit('copyLink', blockId.value!)) }] : []),\n { key: 'up', label: m.value.blockMenu.moveUp, icon: ArrowUp, hint: kbd('Mod-Shift-ArrowUp'), run: () => done(() => moveBlocks(props.editor, props.range, 'up')) },\n { key: 'down', label: m.value.blockMenu.moveDown, icon: ArrowDown, hint: kbd('Mod-Shift-ArrowDown'), run: () => done(() => moveBlocks(props.editor, props.range, 'down')) },\n ...(canTurnInto.value ? [{ key: 'turn', label: m.value.blockMenu.turnInto, icon: Repeat2, submenu: 'turn' as const }] : []),\n ...(hasText.value ? [{ key: 'color', label: m.value.blockMenu.color, icon: Palette, submenu: 'color' as const }] : []),\n])\n\nconst turnRows = computed<Row[]>(() => targets.value.map(b => ({\n key: `turn-${b.id}`,\n label: blockTitle(m.value, b),\n icon: b.icon,\n hint: shortcutFor(b),\n checked: current.value?.id === b.id,\n group: m.value.blockMenu.turnInto,\n run: () => turnInto(b),\n})))\nconst colorRowList = computed(() => colorRows(recent.value.colors))\n\n// --- Search ----------------------------------------------------------------\nconst query = ref('')\nconst normalize = (s: string) => s.normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/đ/g, 'd').toLowerCase()\n\n/** Main list: actions; while searching, also matching turn-into types and colors. */\nconst rows = computed<Row[]>(() => {\n const q = normalize(query.value.trim())\n if (!q) return actions.value\n const match = (r: Row) => normalize(`${r.group ?? ''} ${r.label}`).includes(q)\n const colorMatches: Row[] = hasText.value\n ? colorRowList.value.filter(r => r.section !== 'recent').map(r => ({\n key: `color-${r.kind}-${r.color}`,\n label: r.kind === 'text' ? m.value.slash.textColor(m.value.colors[r.color] ?? r.color) : m.value.slash.bgColor(m.value.colors[r.color] ?? r.color),\n swatch: { kind: r.kind, color: r.color },\n group: m.value.blockMenu.color,\n run: () => pickColor(r.kind, r.color),\n }))\n : []\n return [\n ...actions.value.filter(r => !r.submenu).map(r => ({ ...r, group: m.value.blockMenu.actions })),\n ...(canTurnInto.value ? turnRows.value : []),\n ...colorMatches,\n ].filter(match)\n})\n\n// --- Navigation --------------------------------------------------------------\nconst active = ref(0)\nconst submenu = ref<'turn' | 'color' | null>(null)\nconst subActive = ref(-1)\nconst subCount = computed(() => (submenu.value === 'turn' ? turnRows.value.length : submenu.value === 'color' ? colorRowList.value.length : 0))\n\nwatch(query, () => {\n active.value = 0\n submenu.value = null\n})\n\nfunction scrollActive() {\n nextTick(() => root.value?.querySelector('.me-menu-item.is-active:not(.has-submenu-open), .me-submenu .me-menu-item.is-active')?.scrollIntoView({ block: 'nearest' }))\n}\n\nfunction openSubmenu(which: 'turn' | 'color', focusFirst = false) {\n submenu.value = which\n subActive.value = focusFirst ? 0 : -1\n}\n\nfunction runRow(row: Row | undefined) {\n if (!row) return\n if (row.submenu) return openSubmenu(row.submenu, true)\n row.run?.()\n}\n\nfunction runSubmenuItem(index: number) {\n if (submenu.value === 'turn') return runRow(turnRows.value[index])\n const row = colorRowList.value[index]\n if (row) pickColor(row.kind, row.color)\n}\n\nfunction onKeydown(e: KeyboardEvent) {\n const inSub = submenu.value && subActive.value >= 0\n const count = inSub ? subCount.value : rows.value.length\n const move = (delta: number) => {\n e.preventDefault()\n if (!count) return\n if (inSub) subActive.value = (subActive.value + delta + count) % count\n else active.value = (active.value + delta + count) % count\n scrollActive()\n }\n\n if (e.key === 'ArrowDown') return move(1)\n if (e.key === 'ArrowUp' && !e.shiftKey && !isMod(e)) return move(-1)\n if (e.key === 'ArrowRight' && !inSub && rows.value[active.value]?.submenu) {\n e.preventDefault()\n return openSubmenu(rows.value[active.value]!.submenu!, true)\n }\n if ((e.key === 'ArrowLeft' || e.key === 'Escape') && submenu.value) {\n e.preventDefault()\n submenu.value = null\n return\n }\n if (e.key === 'Escape') {\n e.preventDefault()\n return emit('close')\n }\n if (e.key === 'Enter') {\n e.preventDefault()\n return inSub ? runSubmenuItem(subActive.value) : runRow(rows.value[active.value])\n }\n // Menu shortcuts (only when not editing the search text).\n if ((e.key === 'Delete' || e.key === 'Backspace') && !query.value) {\n e.preventDefault()\n return done(() => deleteBlocks(props.editor, props.range))\n }\n if (isMod(e) && e.key.toLowerCase() === 'd') {\n e.preventDefault()\n return done(() => duplicateBlocks(props.editor, props.range))\n }\n if (isMod(e) && e.shiftKey && (e.key === 'ArrowUp' || e.key === 'ArrowDown')) {\n e.preventDefault()\n return done(() => moveBlocks(props.editor, props.range, e.key === 'ArrowUp' ? 'up' : 'down'))\n }\n}\n\n// Hover intent: submenus open/close after a short delay so diagonal mouse moves don't flicker.\nlet timer: ReturnType<typeof setTimeout> | undefined\nfunction hoverRow(index: number) {\n active.value = index\n clearTimeout(timer)\n const target = rows.value[index]?.submenu ?? null\n if (target === submenu.value) return\n timer = setTimeout(() => {\n if (target) openSubmenu(target)\n else submenu.value = null\n }, 150)\n}\nconst keepSubmenu = () => clearTimeout(timer)\n\n// --- Position --------------------------------------------------------------\n// Below the handle, kept inside the viewport (the menu is at most ~420px tall).\nconst gap = readTokenPx(props.editor.view.dom, 'popover.offset')\nconst style = computed(() => {\n const top = Math.min(props.anchor.bottom + gap, window.innerHeight - 420)\n return { left: `${Math.max(gap, props.anchor.left)}px`, top: `${Math.max(gap, top)}px` }\n})\n// Open submenus to the left when there's no room on the right.\nconst flipSubmenu = computed(() => {\n const el = props.editor.view.dom\n const width = readTokenPx(el, 'menu.width') + readTokenPx(el, 'menu.submenuWidth') + gap * 2\n return props.anchor.left + width > window.innerWidth\n})\n\nonMounted(() => input.value?.focus({ preventScroll: true }))\nonBeforeUnmount(() => clearTimeout(timer))\n</script>\n\n<template>\n <Teleport to=\"body\">\n <div\n ref=\"root\"\n v-bind=\"scope\"\n class=\"me-popover me-floating me-block-menu\"\n :class=\"{ 'is-flipped': flipSubmenu }\"\n :style=\"style\"\n @keydown=\"onKeydown\"\n >\n <label class=\"me-menu-search\">\n <Search />\n <input ref=\"input\" v-model=\"query\" class=\"me-menu-search-input\" :placeholder=\"m.blockMenu.search\">\n </label>\n <div v-if=\"blocks.length > 1\" class=\"me-menu-label\">\n {{ m.blockMenu.selected(blocks.length) }}\n </div>\n\n <!-- Scrolls only while searching: in the action list, submenus sit outside the box. -->\n <div class=\"me-block-menu-list\" :class=\"{ 'is-scroll': query }\">\n <template v-for=\"(row, i) in rows\" :key=\"row.key\">\n <div v-if=\"query && row.group && (i === 0 || rows[i - 1]!.group !== row.group)\" class=\"me-menu-label\">\n {{ row.group }}\n </div>\n <div class=\"me-submenu-anchor\" @mouseenter=\"hoverRow(i)\">\n <button\n type=\"button\"\n class=\"me-menu-item\"\n :class=\"{ 'is-active': i === active, 'has-submenu-open': row.submenu && submenu === row.submenu }\"\n @mousedown.prevent\n @click=\"runRow(row)\"\n >\n <span v-if=\"row.swatch\" class=\"me-menu-icon\" :class=\"row.swatch.kind === 'text' ? 'me-swatch--text' : 'me-swatch--bg'\" :data-color=\"row.swatch.color === 'default' ? undefined : row.swatch.color\">A</span>\n <span v-else class=\"me-menu-icon\"><component :is=\"row.icon\" /></span>\n <span class=\"me-menu-title me-menu-text\">{{ row.label }}</span>\n <Check v-if=\"row.checked\" class=\"me-menu-check\" />\n <span v-if=\"row.hint\" class=\"me-menu-shortcut\">{{ row.hint }}</span>\n <ChevronRight v-if=\"row.submenu\" class=\"me-menu-chevron\" />\n </button>\n\n <div v-if=\"row.submenu && submenu === row.submenu\" class=\"me-popover me-submenu\" @mouseenter=\"keepSubmenu\" @mousedown.prevent>\n <template v-if=\"row.submenu === 'turn'\">\n <button\n v-for=\"(t, ti) in turnRows\"\n :key=\"t.key\"\n type=\"button\"\n class=\"me-menu-item\"\n :class=\"{ 'is-active': ti === subActive }\"\n @mouseenter=\"subActive = ti\"\n @click=\"t.run?.()\"\n >\n <span class=\"me-menu-icon\"><component :is=\"t.icon\" /></span>\n <span class=\"me-menu-title me-menu-text\">{{ t.label }}</span>\n <Check v-if=\"t.checked\" class=\"me-menu-check\" />\n <span v-if=\"t.hint\" class=\"me-menu-shortcut\">{{ t.hint }}</span>\n </button>\n </template>\n <ColorList\n v-else\n :messages=\"m\"\n :recent=\"recent.colors\"\n :current=\"colors\"\n :active-index=\"subActive\"\n @hover=\"subActive = $event\"\n @pick=\"pickColor\"\n />\n </div>\n </div>\n </template>\n </div>\n <div v-if=\"!rows.length\" class=\"me-menu-empty\">\n {{ m.blockMenu.noResults }}\n </div>\n </div>\n </Teleport>\n</template>\n","<script setup lang=\"ts\">\nimport type { Editor } from '@tiptap/vue-3'\nimport type { Component } from 'vue'\nimport { ArrowDown, ArrowUp, Check, ChevronRight, Copy, Link2, Palette, Repeat2, Search, Trash } from '@lucide/vue'\nimport { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'\nimport { type BlockType, blockTitle, turnIntoBlocks } from '../block-items'\nimport {\n type BlockRange, blocksIn, colorBlocks, deleteBlocks, duplicateBlocks, moveBlocks, rangeColors, turnBlocksInto,\n} from '../block-ops'\nimport type { ColorName } from '../colors'\nimport { useClickOutside } from '../composables/useClickOutside'\nimport { useScope } from '../composables/useScope'\nimport { TURN_INTO_SHORTCUTS } from '../extensions/block-selection'\nimport { isMod, kbd } from '../keys'\nimport { pushRecentColor, recent } from '../recent'\nimport { readTokenPx } from '../theme/read'\nimport ColorList, { colorRows } from './ColorList.vue'\n\nconst props = defineProps<{\n editor: Editor\n range: BlockRange\n anchor: DOMRect\n}>()\nconst emit = defineEmits<{ close: [], copyLink: [id: string] }>()\n\nconst root = ref<HTMLElement | null>(null)\nconst input = ref<HTMLInputElement | null>(null)\nuseClickOutside(root, ref(true), () => emit('close'))\n\nconst m = computed(() => props.editor.storage.meiConfig.messages)\nconst scope = useScope(() => props.editor)\nconst blocks = computed(() => blocksIn(props.editor.state.doc, props.range))\nconst targets = computed(() => turnIntoBlocks(props.editor))\n/** Current type when every selected block has the same one. */\nconst current = computed(() => {\n const types = blocks.value.map(b => targets.value.find(t => t.matches?.(b.node))?.id)\n return types.every(t => t && t === types[0]) ? targets.value.find(t => t.id === types[0]) : undefined\n})\nconst canTurnInto = computed(() => blocks.value.every(b => targets.value.some(t => t.matches?.(b.node)) || b.node.type.name === 'callout'))\nconst hasText = computed(() => blocks.value.some(b => b.node.textContent.length > 0 || b.node.isTextblock))\nconst colors = computed(() => rangeColors(props.editor.state, props.range))\nconst blockId = computed(() => (blocks.value.length === 1 ? blocks.value[0]!.node.attrs.id as string | undefined : undefined))\n\n// --- Rows ------------------------------------------------------------------\ninterface Row {\n key: string\n label: string\n icon?: Component\n /** Swatch for color rows. */\n swatch?: { kind: 'text' | 'bg', color: ColorName }\n hint?: string\n checked?: boolean\n submenu?: 'turn' | 'color'\n group?: string\n run?: () => void\n}\n\nfunction done(fn: () => void) {\n emit('close')\n fn()\n}\nconst shortcutFor = (b: BlockType) => {\n const key = Object.entries(TURN_INTO_SHORTCUTS).find(([, id]) => id === b.id)?.[0]\n return key ? kbd(`Mod-Alt-${key}`) : undefined\n}\nconst turnInto = (b: BlockType) => done(() => turnBlocksInto(props.editor, props.range, b))\nfunction pickColor(kind: 'text' | 'bg', color: ColorName) {\n if (color !== 'default') pushRecentColor({ kind, color })\n done(() => colorBlocks(props.editor, props.range, kind, color))\n}\n\nconst actions = computed<Row[]>(() => [\n { key: 'delete', label: m.value.blockMenu.delete, icon: Trash, hint: kbd('Delete'), run: () => done(() => deleteBlocks(props.editor, props.range)) },\n { key: 'duplicate', label: m.value.blockMenu.duplicate, icon: Copy, hint: kbd('Mod-d'), run: () => done(() => duplicateBlocks(props.editor, props.range)) },\n ...(blockId.value ? [{ key: 'link', label: m.value.blockMenu.copyLink, icon: Link2, run: () => done(() => emit('copyLink', blockId.value!)) }] : []),\n { key: 'up', label: m.value.blockMenu.moveUp, icon: ArrowUp, hint: kbd('Mod-Shift-ArrowUp'), run: () => done(() => moveBlocks(props.editor, props.range, 'up')) },\n { key: 'down', label: m.value.blockMenu.moveDown, icon: ArrowDown, hint: kbd('Mod-Shift-ArrowDown'), run: () => done(() => moveBlocks(props.editor, props.range, 'down')) },\n ...(canTurnInto.value ? [{ key: 'turn', label: m.value.blockMenu.turnInto, icon: Repeat2, submenu: 'turn' as const }] : []),\n ...(hasText.value ? [{ key: 'color', label: m.value.blockMenu.color, icon: Palette, submenu: 'color' as const }] : []),\n])\n\nconst turnRows = computed<Row[]>(() => targets.value.map(b => ({\n key: `turn-${b.id}`,\n label: blockTitle(m.value, b),\n icon: b.icon,\n hint: shortcutFor(b),\n checked: current.value?.id === b.id,\n group: m.value.blockMenu.turnInto,\n run: () => turnInto(b),\n})))\nconst colorRowList = computed(() => colorRows(recent.value.colors))\n\n// --- Search ----------------------------------------------------------------\nconst query = ref('')\nconst normalize = (s: string) => s.normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/đ/g, 'd').toLowerCase()\n\n/** Main list: actions; while searching, also matching turn-into types and colors. */\nconst rows = computed<Row[]>(() => {\n const q = normalize(query.value.trim())\n if (!q) return actions.value\n const match = (r: Row) => normalize(`${r.group ?? ''} ${r.label}`).includes(q)\n const colorMatches: Row[] = hasText.value\n ? colorRowList.value.filter(r => r.section !== 'recent').map(r => ({\n key: `color-${r.kind}-${r.color}`,\n label: r.kind === 'text' ? m.value.slash.textColor(m.value.colors[r.color] ?? r.color) : m.value.slash.bgColor(m.value.colors[r.color] ?? r.color),\n swatch: { kind: r.kind, color: r.color },\n group: m.value.blockMenu.color,\n run: () => pickColor(r.kind, r.color),\n }))\n : []\n return [\n ...actions.value.filter(r => !r.submenu).map(r => ({ ...r, group: m.value.blockMenu.actions })),\n ...(canTurnInto.value ? turnRows.value : []),\n ...colorMatches,\n ].filter(match)\n})\n\n// --- Navigation --------------------------------------------------------------\nconst active = ref(0)\nconst submenu = ref<'turn' | 'color' | null>(null)\nconst subActive = ref(-1)\nconst subCount = computed(() => (submenu.value === 'turn' ? turnRows.value.length : submenu.value === 'color' ? colorRowList.value.length : 0))\n\nwatch(query, () => {\n active.value = 0\n submenu.value = null\n})\n\nfunction scrollActive() {\n nextTick(() => root.value?.querySelector('.me-menu-item.is-active:not(.has-submenu-open), .me-submenu .me-menu-item.is-active')?.scrollIntoView({ block: 'nearest' }))\n}\n\nfunction openSubmenu(which: 'turn' | 'color', focusFirst = false) {\n submenu.value = which\n subActive.value = focusFirst ? 0 : -1\n}\n\nfunction runRow(row: Row | undefined) {\n if (!row) return\n if (row.submenu) return openSubmenu(row.submenu, true)\n row.run?.()\n}\n\nfunction runSubmenuItem(index: number) {\n if (submenu.value === 'turn') return runRow(turnRows.value[index])\n const row = colorRowList.value[index]\n if (row) pickColor(row.kind, row.color)\n}\n\nfunction onKeydown(e: KeyboardEvent) {\n const inSub = submenu.value && subActive.value >= 0\n const count = inSub ? subCount.value : rows.value.length\n const move = (delta: number) => {\n e.preventDefault()\n if (!count) return\n if (inSub) subActive.value = (subActive.value + delta + count) % count\n else active.value = (active.value + delta + count) % count\n scrollActive()\n }\n\n if (e.key === 'ArrowDown') return move(1)\n if (e.key === 'ArrowUp' && !e.shiftKey && !isMod(e)) return move(-1)\n if (e.key === 'ArrowRight' && !inSub && rows.value[active.value]?.submenu) {\n e.preventDefault()\n return openSubmenu(rows.value[active.value]!.submenu!, true)\n }\n if ((e.key === 'ArrowLeft' || e.key === 'Escape') && submenu.value) {\n e.preventDefault()\n submenu.value = null\n return\n }\n if (e.key === 'Escape') {\n e.preventDefault()\n return emit('close')\n }\n if (e.key === 'Enter') {\n e.preventDefault()\n return inSub ? runSubmenuItem(subActive.value) : runRow(rows.value[active.value])\n }\n // Menu shortcuts (only when not editing the search text).\n if ((e.key === 'Delete' || e.key === 'Backspace') && !query.value) {\n e.preventDefault()\n return done(() => deleteBlocks(props.editor, props.range))\n }\n if (isMod(e) && e.key.toLowerCase() === 'd') {\n e.preventDefault()\n return done(() => duplicateBlocks(props.editor, props.range))\n }\n if (isMod(e) && e.shiftKey && (e.key === 'ArrowUp' || e.key === 'ArrowDown')) {\n e.preventDefault()\n return done(() => moveBlocks(props.editor, props.range, e.key === 'ArrowUp' ? 'up' : 'down'))\n }\n}\n\n// Hover intent: submenus open/close after a short delay so diagonal mouse moves don't flicker.\nlet timer: ReturnType<typeof setTimeout> | undefined\nfunction hoverRow(index: number) {\n active.value = index\n clearTimeout(timer)\n const target = rows.value[index]?.submenu ?? null\n if (target === submenu.value) return\n timer = setTimeout(() => {\n if (target) openSubmenu(target)\n else submenu.value = null\n }, 150)\n}\nconst keepSubmenu = () => clearTimeout(timer)\n\n// --- Position --------------------------------------------------------------\n// Below the handle, kept inside the viewport (the menu is at most ~420px tall).\nconst gap = readTokenPx(props.editor.view.dom, 'popover.offset')\nconst style = computed(() => {\n const top = Math.min(props.anchor.bottom + gap, window.innerHeight - 420)\n return { left: `${Math.max(gap, props.anchor.left)}px`, top: `${Math.max(gap, top)}px` }\n})\n// Open submenus to the left when there's no room on the right.\nconst flipSubmenu = computed(() => {\n const el = props.editor.view.dom\n const width = readTokenPx(el, 'menu.width') + readTokenPx(el, 'menu.submenuWidth') + gap * 2\n return props.anchor.left + width > window.innerWidth\n})\n\nonMounted(() => input.value?.focus({ preventScroll: true }))\nonBeforeUnmount(() => clearTimeout(timer))\n</script>\n\n<template>\n <Teleport to=\"body\">\n <div\n ref=\"root\"\n v-bind=\"scope\"\n class=\"me-popover me-floating me-block-menu\"\n :class=\"{ 'is-flipped': flipSubmenu }\"\n :style=\"style\"\n @keydown=\"onKeydown\"\n >\n <label class=\"me-menu-search\">\n <Search />\n <input ref=\"input\" v-model=\"query\" class=\"me-menu-search-input\" :placeholder=\"m.blockMenu.search\">\n </label>\n <div v-if=\"blocks.length > 1\" class=\"me-menu-label\">\n {{ m.blockMenu.selected(blocks.length) }}\n </div>\n\n <!-- Scrolls only while searching: in the action list, submenus sit outside the box. -->\n <div class=\"me-block-menu-list\" :class=\"{ 'is-scroll': query }\">\n <template v-for=\"(row, i) in rows\" :key=\"row.key\">\n <div v-if=\"query && row.group && (i === 0 || rows[i - 1]!.group !== row.group)\" class=\"me-menu-label\">\n {{ row.group }}\n </div>\n <div class=\"me-submenu-anchor\" @mouseenter=\"hoverRow(i)\">\n <button\n type=\"button\"\n class=\"me-menu-item\"\n :class=\"{ 'is-active': i === active, 'has-submenu-open': row.submenu && submenu === row.submenu }\"\n @mousedown.prevent\n @click=\"runRow(row)\"\n >\n <span v-if=\"row.swatch\" class=\"me-menu-icon\" :class=\"row.swatch.kind === 'text' ? 'me-swatch--text' : 'me-swatch--bg'\" :data-color=\"row.swatch.color === 'default' ? undefined : row.swatch.color\">A</span>\n <span v-else class=\"me-menu-icon\"><component :is=\"row.icon\" /></span>\n <span class=\"me-menu-title me-menu-text\">{{ row.label }}</span>\n <Check v-if=\"row.checked\" class=\"me-menu-check\" />\n <span v-if=\"row.hint\" class=\"me-menu-shortcut\">{{ row.hint }}</span>\n <ChevronRight v-if=\"row.submenu\" class=\"me-menu-chevron\" />\n </button>\n\n <div v-if=\"row.submenu && submenu === row.submenu\" class=\"me-popover me-submenu\" @mouseenter=\"keepSubmenu\" @mousedown.prevent>\n <template v-if=\"row.submenu === 'turn'\">\n <button\n v-for=\"(t, ti) in turnRows\"\n :key=\"t.key\"\n type=\"button\"\n class=\"me-menu-item\"\n :class=\"{ 'is-active': ti === subActive }\"\n @mouseenter=\"subActive = ti\"\n @click=\"t.run?.()\"\n >\n <span class=\"me-menu-icon\"><component :is=\"t.icon\" /></span>\n <span class=\"me-menu-title me-menu-text\">{{ t.label }}</span>\n <Check v-if=\"t.checked\" class=\"me-menu-check\" />\n <span v-if=\"t.hint\" class=\"me-menu-shortcut\">{{ t.hint }}</span>\n </button>\n </template>\n <ColorList\n v-else\n :messages=\"m\"\n :recent=\"recent.colors\"\n :current=\"colors\"\n :active-index=\"subActive\"\n @hover=\"subActive = $event\"\n @pick=\"pickColor\"\n />\n </div>\n </div>\n </template>\n </div>\n <div v-if=\"!rows.length\" class=\"me-menu-empty\">\n {{ m.blockMenu.noResults }}\n </div>\n </div>\n </Teleport>\n</template>\n","<script setup lang=\"ts\">\nimport type { Editor as CoreEditor } from '@tiptap/core'\nimport type { Editor } from '@tiptap/vue-3'\nimport { BubbleMenu } from '@tiptap/vue-3/menus'\nimport { type EditorState, NodeSelection } from '@tiptap/pm/state'\nimport { CellSelection } from '@tiptap/pm/tables'\nimport { Baseline, Bold, Check, ChevronDown, Code, Italic, Link, Strikethrough, Underline, Unlink } from '@lucide/vue'\nimport { computed, nextTick, ref } from 'vue'\nimport { blockTitle, turnIntoBlocks } from '../block-items'\nimport type { ColorName } from '../colors'\nimport { useScope } from '../composables/useScope'\nimport { readTokenPx } from '../theme/read'\nimport { pushRecentColor, recent } from '../recent'\nimport { blocksIn, currentRange, isBlockSelection, rangeColors, turnBlocksInto } from '../block-ops'\nimport type { FormatAction } from '../define-block'\nimport ColorList from './ColorList.vue'\n\nconst props = defineProps<{ editor: Editor }>()\n\nconst panel = ref<'turn' | 'color' | 'link' | null>(null)\nconst linkUrl = ref('')\nconst linkInput = ref<HTMLInputElement | null>(null)\nconst m = computed(() => props.editor.storage.meiConfig.messages)\nconst scope = useScope(() => props.editor)\nconst offset = readTokenPx(props.editor.view.dom, 'popover.offset')\n\n/** Bubble-menu buttons from blocks (e.g. \"Comment\"); read-only editors show only `readOnly` ones. */\nconst actionsFor = (editor: CoreEditor) => (editor.storage.meiConfig?.formatActions ?? [])\n .filter(a => (editor.isEditable || a.readOnly) && (a.isVisible?.(editor) ?? true))\n\nconst shouldShow = ({ editor, state, from, to }: { editor: CoreEditor, state: EditorState, from: number, to: number }) => {\n if (from === to) return false\n if (!editor.isEditable && !actionsFor(editor).length) return false\n // Whole-block selections use the ⋮⋮ menu instead, like Notion.\n // Whole cells use the table toolbar.\n if (state.selection instanceof NodeSelection || state.selection instanceof CellSelection || isBlockSelection(state)) return false\n if (editor.isActive('codeBlock')) return false\n return state.doc.textBetween(from, to).length > 0\n}\n\n// `isEditable` isn't reactive; reading the (reactive) state re-evaluates it on each transaction.\nconst editable = computed(() => {\n void props.editor.state\n return props.editor.isEditable\n})\n// Re-read on every render of the menu (selection changes re-render it).\nconst actions = computed(() => {\n void props.editor.state.selection\n return actionsFor(props.editor as CoreEditor)\n})\nconst actionTitle = (a: FormatAction) => (typeof a.title === 'function' ? a.title(props.editor as CoreEditor) : a.title)\nfunction runAction(a: FormatAction) {\n panel.value = null\n a.run(props.editor as CoreEditor)\n}\n\nconst targets = computed(() => turnIntoBlocks(props.editor))\nconst current = computed(() => {\n const range = currentRange(props.editor.state)\n const first = range && blocksIn(props.editor.state.doc, range)[0]\n return first ? targets.value.find(b => b.matches?.(first.node)) : undefined\n})\n\nconst marks = computed(() => [\n { name: 'bold', icon: Bold, title: `${m.value.format.bold} (⌘B)`, run: () => props.editor.chain().focus().toggleBold().run() },\n { name: 'italic', icon: Italic, title: `${m.value.format.italic} (⌘I)`, run: () => props.editor.chain().focus().toggleItalic().run() },\n { name: 'underline', icon: Underline, title: `${m.value.format.underline} (⌘U)`, run: () => props.editor.chain().focus().toggleUnderline().run() },\n { name: 'strike', icon: Strikethrough, title: `${m.value.format.strike} (⌘⇧S)`, run: () => props.editor.chain().focus().toggleStrike().run() },\n { name: 'code', icon: Code, title: `${m.value.format.code} (⌘E)`, run: () => props.editor.chain().focus().toggleCode().run() },\n])\n\nfunction toggle(p: typeof panel.value) {\n panel.value = panel.value === p ? null : p\n if (p === 'link' && panel.value === 'link') {\n linkUrl.value = props.editor.getAttributes('link').href ?? ''\n nextTick(() => linkInput.value?.focus())\n }\n}\n\nfunction turnInto(id: string) {\n const range = currentRange(props.editor.state)\n const target = targets.value.find(b => b.id === id)\n if (range && target) turnBlocksInto(props.editor, range, target)\n panel.value = null\n}\n\nfunction applyLink(href = linkUrl.value.trim()) {\n const chain = props.editor.chain().focus().extendMarkRange('link')\n if (!href) chain.unsetLink().run()\n else chain.setLink({ href: /^[a-z]+:/i.test(href) ? href : `https://${href}` }).run()\n panel.value = null\n}\n\nfunction setColor(kind: 'text' | 'bg', color: ColorName) {\n if (color !== 'default') pushRecentColor({ kind, color })\n const chain = props.editor.chain().focus()\n ;(kind === 'text' ? chain.setTextColor(color) : chain.setBgColor(color)).run()\n panel.value = null\n}\n\n// Colors of the selected text, to tick them in the menu.\nconst selectionColors = computed(() => {\n const { from, to } = props.editor.state.selection\n return rangeColors(props.editor.state, { from, to, depth: 0 })\n})\nconst activeTextColor = computed(() => props.editor.getAttributes('textColor').color as string | undefined)\n</script>\n\n<template>\n <BubbleMenu\n :editor=\"editor\"\n :should-show=\"shouldShow\"\n :options=\"{ placement: 'top-start', offset, onHide: () => (panel = null) }\"\n plugin-key=\"formatMenu\"\n >\n <div v-bind=\"scope\" class=\"me-popover me-toolbar\" @mousedown=\"panel !== 'link' && $event.preventDefault()\">\n <template v-if=\"!editable\">\n <button v-for=\"a in actions\" :key=\"a.id\" type=\"button\" class=\"me-tool-btn\" :title=\"actionTitle(a)\" @click=\"runAction(a)\">\n <component :is=\"a.icon\" /> {{ actionTitle(a) }}\n </button>\n </template>\n <template v-else>\n <template v-if=\"current\">\n <button type=\"button\" class=\"me-tool-btn\" @click=\"toggle('turn')\">\n {{ blockTitle(m, current) }} <ChevronDown class=\"me-chevron\" />\n </button>\n <span class=\"me-toolbar-divider\" />\n </template>\n\n <button\n v-for=\"mark in marks\"\n :key=\"mark.name\"\n type=\"button\"\n class=\"me-tool-btn\"\n :class=\"{ 'is-active': editor.isActive(mark.name) }\"\n :title=\"mark.title\"\n @click=\"mark.run\"\n >\n <component :is=\"mark.icon\" />\n </button>\n\n <span class=\"me-toolbar-divider\" />\n <button type=\"button\" class=\"me-tool-btn\" :class=\"{ 'is-active': editor.isActive('link') }\" :title=\"m.format.link\" @click=\"toggle('link')\">\n <Link />\n </button>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.format.color\" @click=\"toggle('color')\">\n <Baseline class=\"me-swatch--text\" :data-color=\"activeTextColor\" />\n <ChevronDown class=\"me-chevron\" />\n </button>\n\n <template v-if=\"actions.length\">\n <span class=\"me-toolbar-divider\" />\n <button v-for=\"a in actions\" :key=\"a.id\" type=\"button\" class=\"me-tool-btn\" :title=\"actionTitle(a)\" @click=\"runAction(a)\">\n <component :is=\"a.icon\" /> {{ actionTitle(a) }}\n </button>\n </template>\n\n <div v-if=\"panel === 'turn'\" class=\"me-popover me-toolbar-panel me-menu\">\n <button v-for=\"b in targets\" :key=\"b.id\" type=\"button\" class=\"me-menu-item\" @click=\"turnInto(b.id)\">\n <span class=\"me-menu-icon\"><component :is=\"b.icon\" /></span>\n <span class=\"me-menu-title me-menu-text\">{{ blockTitle(m, b) }}</span>\n <Check v-if=\"current?.id === b.id\" class=\"me-menu-check\" />\n </button>\n </div>\n\n <form v-if=\"panel === 'link'\" class=\"me-popover me-toolbar-panel me-link-form\" @submit.prevent=\"applyLink()\">\n <input ref=\"linkInput\" v-model=\"linkUrl\" class=\"me-input\" :placeholder=\"m.format.linkPlaceholder\" @keydown.esc=\"panel = null\">\n <button type=\"submit\" class=\"me-btn me-btn--primary\">\n {{ m.format.apply }}\n </button>\n <button v-if=\"editor.isActive('link')\" type=\"button\" class=\"me-btn\" :title=\"m.format.removeLink\" @click=\"applyLink('')\">\n <Unlink />\n </button>\n </form>\n\n <div v-if=\"panel === 'color'\" class=\"me-popover me-toolbar-panel me-toolbar-panel--end me-menu\">\n <ColorList :messages=\"m\" :recent=\"recent.colors\" :current=\"selectionColors\" @pick=\"setColor\" />\n </div>\n </template>\n </div>\n </BubbleMenu>\n</template>\n","<script setup lang=\"ts\">\nimport type { Editor as CoreEditor } from '@tiptap/core'\nimport type { Editor } from '@tiptap/vue-3'\nimport { BubbleMenu } from '@tiptap/vue-3/menus'\nimport { type EditorState, NodeSelection } from '@tiptap/pm/state'\nimport { CellSelection } from '@tiptap/pm/tables'\nimport { Baseline, Bold, Check, ChevronDown, Code, Italic, Link, Strikethrough, Underline, Unlink } from '@lucide/vue'\nimport { computed, nextTick, ref } from 'vue'\nimport { blockTitle, turnIntoBlocks } from '../block-items'\nimport type { ColorName } from '../colors'\nimport { useScope } from '../composables/useScope'\nimport { readTokenPx } from '../theme/read'\nimport { pushRecentColor, recent } from '../recent'\nimport { blocksIn, currentRange, isBlockSelection, rangeColors, turnBlocksInto } from '../block-ops'\nimport type { FormatAction } from '../define-block'\nimport ColorList from './ColorList.vue'\n\nconst props = defineProps<{ editor: Editor }>()\n\nconst panel = ref<'turn' | 'color' | 'link' | null>(null)\nconst linkUrl = ref('')\nconst linkInput = ref<HTMLInputElement | null>(null)\nconst m = computed(() => props.editor.storage.meiConfig.messages)\nconst scope = useScope(() => props.editor)\nconst offset = readTokenPx(props.editor.view.dom, 'popover.offset')\n\n/** Bubble-menu buttons from blocks (e.g. \"Comment\"); read-only editors show only `readOnly` ones. */\nconst actionsFor = (editor: CoreEditor) => (editor.storage.meiConfig?.formatActions ?? [])\n .filter(a => (editor.isEditable || a.readOnly) && (a.isVisible?.(editor) ?? true))\n\nconst shouldShow = ({ editor, state, from, to }: { editor: CoreEditor, state: EditorState, from: number, to: number }) => {\n if (from === to) return false\n if (!editor.isEditable && !actionsFor(editor).length) return false\n // Whole-block selections use the ⋮⋮ menu instead, like Notion.\n // Whole cells use the table toolbar.\n if (state.selection instanceof NodeSelection || state.selection instanceof CellSelection || isBlockSelection(state)) return false\n if (editor.isActive('codeBlock')) return false\n return state.doc.textBetween(from, to).length > 0\n}\n\n// `isEditable` isn't reactive; reading the (reactive) state re-evaluates it on each transaction.\nconst editable = computed(() => {\n void props.editor.state\n return props.editor.isEditable\n})\n// Re-read on every render of the menu (selection changes re-render it).\nconst actions = computed(() => {\n void props.editor.state.selection\n return actionsFor(props.editor as CoreEditor)\n})\nconst actionTitle = (a: FormatAction) => (typeof a.title === 'function' ? a.title(props.editor as CoreEditor) : a.title)\nfunction runAction(a: FormatAction) {\n panel.value = null\n a.run(props.editor as CoreEditor)\n}\n\nconst targets = computed(() => turnIntoBlocks(props.editor))\nconst current = computed(() => {\n const range = currentRange(props.editor.state)\n const first = range && blocksIn(props.editor.state.doc, range)[0]\n return first ? targets.value.find(b => b.matches?.(first.node)) : undefined\n})\n\nconst marks = computed(() => [\n { name: 'bold', icon: Bold, title: `${m.value.format.bold} (⌘B)`, run: () => props.editor.chain().focus().toggleBold().run() },\n { name: 'italic', icon: Italic, title: `${m.value.format.italic} (⌘I)`, run: () => props.editor.chain().focus().toggleItalic().run() },\n { name: 'underline', icon: Underline, title: `${m.value.format.underline} (⌘U)`, run: () => props.editor.chain().focus().toggleUnderline().run() },\n { name: 'strike', icon: Strikethrough, title: `${m.value.format.strike} (⌘⇧S)`, run: () => props.editor.chain().focus().toggleStrike().run() },\n { name: 'code', icon: Code, title: `${m.value.format.code} (⌘E)`, run: () => props.editor.chain().focus().toggleCode().run() },\n])\n\nfunction toggle(p: typeof panel.value) {\n panel.value = panel.value === p ? null : p\n if (p === 'link' && panel.value === 'link') {\n linkUrl.value = props.editor.getAttributes('link').href ?? ''\n nextTick(() => linkInput.value?.focus())\n }\n}\n\nfunction turnInto(id: string) {\n const range = currentRange(props.editor.state)\n const target = targets.value.find(b => b.id === id)\n if (range && target) turnBlocksInto(props.editor, range, target)\n panel.value = null\n}\n\nfunction applyLink(href = linkUrl.value.trim()) {\n const chain = props.editor.chain().focus().extendMarkRange('link')\n if (!href) chain.unsetLink().run()\n else chain.setLink({ href: /^[a-z]+:/i.test(href) ? href : `https://${href}` }).run()\n panel.value = null\n}\n\nfunction setColor(kind: 'text' | 'bg', color: ColorName) {\n if (color !== 'default') pushRecentColor({ kind, color })\n const chain = props.editor.chain().focus()\n ;(kind === 'text' ? chain.setTextColor(color) : chain.setBgColor(color)).run()\n panel.value = null\n}\n\n// Colors of the selected text, to tick them in the menu.\nconst selectionColors = computed(() => {\n const { from, to } = props.editor.state.selection\n return rangeColors(props.editor.state, { from, to, depth: 0 })\n})\nconst activeTextColor = computed(() => props.editor.getAttributes('textColor').color as string | undefined)\n</script>\n\n<template>\n <BubbleMenu\n :editor=\"editor\"\n :should-show=\"shouldShow\"\n :options=\"{ placement: 'top-start', offset, onHide: () => (panel = null) }\"\n plugin-key=\"formatMenu\"\n >\n <div v-bind=\"scope\" class=\"me-popover me-toolbar\" @mousedown=\"panel !== 'link' && $event.preventDefault()\">\n <template v-if=\"!editable\">\n <button v-for=\"a in actions\" :key=\"a.id\" type=\"button\" class=\"me-tool-btn\" :title=\"actionTitle(a)\" @click=\"runAction(a)\">\n <component :is=\"a.icon\" /> {{ actionTitle(a) }}\n </button>\n </template>\n <template v-else>\n <template v-if=\"current\">\n <button type=\"button\" class=\"me-tool-btn\" @click=\"toggle('turn')\">\n {{ blockTitle(m, current) }} <ChevronDown class=\"me-chevron\" />\n </button>\n <span class=\"me-toolbar-divider\" />\n </template>\n\n <button\n v-for=\"mark in marks\"\n :key=\"mark.name\"\n type=\"button\"\n class=\"me-tool-btn\"\n :class=\"{ 'is-active': editor.isActive(mark.name) }\"\n :title=\"mark.title\"\n @click=\"mark.run\"\n >\n <component :is=\"mark.icon\" />\n </button>\n\n <span class=\"me-toolbar-divider\" />\n <button type=\"button\" class=\"me-tool-btn\" :class=\"{ 'is-active': editor.isActive('link') }\" :title=\"m.format.link\" @click=\"toggle('link')\">\n <Link />\n </button>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.format.color\" @click=\"toggle('color')\">\n <Baseline class=\"me-swatch--text\" :data-color=\"activeTextColor\" />\n <ChevronDown class=\"me-chevron\" />\n </button>\n\n <template v-if=\"actions.length\">\n <span class=\"me-toolbar-divider\" />\n <button v-for=\"a in actions\" :key=\"a.id\" type=\"button\" class=\"me-tool-btn\" :title=\"actionTitle(a)\" @click=\"runAction(a)\">\n <component :is=\"a.icon\" /> {{ actionTitle(a) }}\n </button>\n </template>\n\n <div v-if=\"panel === 'turn'\" class=\"me-popover me-toolbar-panel me-menu\">\n <button v-for=\"b in targets\" :key=\"b.id\" type=\"button\" class=\"me-menu-item\" @click=\"turnInto(b.id)\">\n <span class=\"me-menu-icon\"><component :is=\"b.icon\" /></span>\n <span class=\"me-menu-title me-menu-text\">{{ blockTitle(m, b) }}</span>\n <Check v-if=\"current?.id === b.id\" class=\"me-menu-check\" />\n </button>\n </div>\n\n <form v-if=\"panel === 'link'\" class=\"me-popover me-toolbar-panel me-link-form\" @submit.prevent=\"applyLink()\">\n <input ref=\"linkInput\" v-model=\"linkUrl\" class=\"me-input\" :placeholder=\"m.format.linkPlaceholder\" @keydown.esc=\"panel = null\">\n <button type=\"submit\" class=\"me-btn me-btn--primary\">\n {{ m.format.apply }}\n </button>\n <button v-if=\"editor.isActive('link')\" type=\"button\" class=\"me-btn\" :title=\"m.format.removeLink\" @click=\"applyLink('')\">\n <Unlink />\n </button>\n </form>\n\n <div v-if=\"panel === 'color'\" class=\"me-popover me-toolbar-panel me-toolbar-panel--end me-menu\">\n <ColorList :messages=\"m\" :recent=\"recent.colors\" :current=\"selectionColors\" @pick=\"setColor\" />\n </div>\n </template>\n </div>\n </BubbleMenu>\n</template>\n","<script setup lang=\"ts\">\n/**\n * Notion-style floating outline: short bars on the right edge, one per heading\n * (longer for higher levels, darker for the section in view). Hover to see the full\n * table of contents; click an entry to scroll to it.\n */\nimport type { Editor } from '@tiptap/vue-3'\nimport { TextSelection } from '@tiptap/pm/state'\nimport { computed, onBeforeUnmount, onMounted, ref, shallowRef, watch } from 'vue'\nimport { useScope } from '../composables/useScope'\n\nconst props = defineProps<{ editor: Editor, minHeadings: number, root: HTMLElement | null }>()\nconst scope = useScope(() => props.editor)\n/** Only show while the editor is on screen (several editors on a page don't stack outlines). */\nconst onScreen = ref(true)\nlet observer: IntersectionObserver | null = null\nwatch(() => props.root, (root) => {\n observer?.disconnect()\n if (!root || typeof IntersectionObserver === 'undefined') return\n observer = new IntersectionObserver((list) => {\n onScreen.value = list.at(-1)?.isIntersecting ?? true\n })\n observer.observe(root)\n}, { immediate: true })\n\ninterface Entry { pos: number, level: number, text: string }\nconst entries = shallowRef<Entry[]>([])\nconst active = ref(-1)\nconst open = ref(false)\nconst m = computed(() => props.editor.storage.meiConfig.messages.toc)\n\nfunction collect() {\n const list: Entry[] = []\n props.editor.state.doc.forEach((node, offset) => {\n if (node.type.name === 'heading') list.push({ pos: offset, level: node.attrs.level, text: node.textContent })\n else if (node.type.name === 'details' && node.attrs.level) list.push({ pos: offset, level: node.attrs.level, text: node.firstChild?.textContent ?? '' })\n })\n entries.value = list\n updateActive()\n}\n\n// Recollect at most once per frame while typing.\nlet pending = 0\nfunction schedule() {\n if (pending) return\n pending = requestAnimationFrame(() => {\n pending = 0\n collect()\n })\n}\n\n/** The last heading whose top is above ~a quarter of the viewport. */\nfunction updateActive() {\n const { view } = props.editor\n const line = window.innerHeight * 0.25\n let current = entries.value.length ? 0 : -1\n entries.value.forEach((e, i) => {\n const dom = view.nodeDOM(e.pos)\n if (dom instanceof HTMLElement && dom.getBoundingClientRect().top <= line) current = i\n })\n active.value = current\n}\nlet scrollFrame = 0\nfunction onScroll() {\n cancelAnimationFrame(scrollFrame)\n scrollFrame = requestAnimationFrame(updateActive)\n}\n\nfunction go(e: Entry) {\n const { view } = props.editor\n ;(view.nodeDOM(e.pos) as HTMLElement | null)?.scrollIntoView({ behavior: 'smooth', block: 'start' })\n view.dispatch(view.state.tr.setSelection(TextSelection.near(view.state.doc.resolve(e.pos + 1))))\n view.focus()\n open.value = false\n}\n\nconst minLevel = computed(() => Math.min(...entries.value.map(e => e.level), 4))\nconst visible = computed(() => onScreen.value && entries.value.length >= props.minHeadings)\n\nlet closeTimer: ReturnType<typeof setTimeout> | undefined\nfunction enter() {\n clearTimeout(closeTimer)\n open.value = true\n}\nfunction leave() {\n clearTimeout(closeTimer)\n closeTimer = setTimeout(() => (open.value = false), 150)\n}\n\nonMounted(() => {\n collect()\n props.editor.on('update', schedule)\n window.addEventListener('scroll', onScroll, { passive: true, capture: true })\n window.addEventListener('resize', onScroll, { passive: true })\n})\nonBeforeUnmount(() => {\n observer?.disconnect()\n props.editor.off('update', schedule)\n window.removeEventListener('scroll', onScroll, { capture: true })\n window.removeEventListener('resize', onScroll)\n cancelAnimationFrame(pending)\n cancelAnimationFrame(scrollFrame)\n clearTimeout(closeTimer)\n})\n</script>\n\n<template>\n <!-- Fixed to the viewport's right edge (not the editor's), above full-width blocks. -->\n <Teleport to=\"body\">\n <nav v-if=\"visible\" v-bind=\"scope\" class=\"me-outline\" :aria-label=\"m.title\" @mouseenter=\"enter\" @mouseleave=\"leave\">\n <div class=\"me-outline-bars\" :class=\"{ 'is-hidden': open }\">\n <span\n v-for=\"(e, i) in entries\"\n :key=\"e.pos\"\n class=\"me-outline-bar\"\n :class=\"{ 'is-active': i === active }\"\n :data-depth=\"e.level - minLevel\"\n />\n </div>\n <div v-if=\"open\" class=\"me-popover me-outline-panel\">\n <button\n v-for=\"(e, i) in entries\"\n :key=\"e.pos\"\n type=\"button\"\n class=\"me-outline-item\"\n :class=\"{ 'is-active': i === active }\"\n :data-depth=\"e.level - minLevel\"\n @click=\"go(e)\"\n >\n {{ e.text || m.untitled }}\n </button>\n </div>\n </nav>\n </Teleport>\n</template>\n","<script setup lang=\"ts\">\n/**\n * Notion-style floating outline: short bars on the right edge, one per heading\n * (longer for higher levels, darker for the section in view). Hover to see the full\n * table of contents; click an entry to scroll to it.\n */\nimport type { Editor } from '@tiptap/vue-3'\nimport { TextSelection } from '@tiptap/pm/state'\nimport { computed, onBeforeUnmount, onMounted, ref, shallowRef, watch } from 'vue'\nimport { useScope } from '../composables/useScope'\n\nconst props = defineProps<{ editor: Editor, minHeadings: number, root: HTMLElement | null }>()\nconst scope = useScope(() => props.editor)\n/** Only show while the editor is on screen (several editors on a page don't stack outlines). */\nconst onScreen = ref(true)\nlet observer: IntersectionObserver | null = null\nwatch(() => props.root, (root) => {\n observer?.disconnect()\n if (!root || typeof IntersectionObserver === 'undefined') return\n observer = new IntersectionObserver((list) => {\n onScreen.value = list.at(-1)?.isIntersecting ?? true\n })\n observer.observe(root)\n}, { immediate: true })\n\ninterface Entry { pos: number, level: number, text: string }\nconst entries = shallowRef<Entry[]>([])\nconst active = ref(-1)\nconst open = ref(false)\nconst m = computed(() => props.editor.storage.meiConfig.messages.toc)\n\nfunction collect() {\n const list: Entry[] = []\n props.editor.state.doc.forEach((node, offset) => {\n if (node.type.name === 'heading') list.push({ pos: offset, level: node.attrs.level, text: node.textContent })\n else if (node.type.name === 'details' && node.attrs.level) list.push({ pos: offset, level: node.attrs.level, text: node.firstChild?.textContent ?? '' })\n })\n entries.value = list\n updateActive()\n}\n\n// Recollect at most once per frame while typing.\nlet pending = 0\nfunction schedule() {\n if (pending) return\n pending = requestAnimationFrame(() => {\n pending = 0\n collect()\n })\n}\n\n/** The last heading whose top is above ~a quarter of the viewport. */\nfunction updateActive() {\n const { view } = props.editor\n const line = window.innerHeight * 0.25\n let current = entries.value.length ? 0 : -1\n entries.value.forEach((e, i) => {\n const dom = view.nodeDOM(e.pos)\n if (dom instanceof HTMLElement && dom.getBoundingClientRect().top <= line) current = i\n })\n active.value = current\n}\nlet scrollFrame = 0\nfunction onScroll() {\n cancelAnimationFrame(scrollFrame)\n scrollFrame = requestAnimationFrame(updateActive)\n}\n\nfunction go(e: Entry) {\n const { view } = props.editor\n ;(view.nodeDOM(e.pos) as HTMLElement | null)?.scrollIntoView({ behavior: 'smooth', block: 'start' })\n view.dispatch(view.state.tr.setSelection(TextSelection.near(view.state.doc.resolve(e.pos + 1))))\n view.focus()\n open.value = false\n}\n\nconst minLevel = computed(() => Math.min(...entries.value.map(e => e.level), 4))\nconst visible = computed(() => onScreen.value && entries.value.length >= props.minHeadings)\n\nlet closeTimer: ReturnType<typeof setTimeout> | undefined\nfunction enter() {\n clearTimeout(closeTimer)\n open.value = true\n}\nfunction leave() {\n clearTimeout(closeTimer)\n closeTimer = setTimeout(() => (open.value = false), 150)\n}\n\nonMounted(() => {\n collect()\n props.editor.on('update', schedule)\n window.addEventListener('scroll', onScroll, { passive: true, capture: true })\n window.addEventListener('resize', onScroll, { passive: true })\n})\nonBeforeUnmount(() => {\n observer?.disconnect()\n props.editor.off('update', schedule)\n window.removeEventListener('scroll', onScroll, { capture: true })\n window.removeEventListener('resize', onScroll)\n cancelAnimationFrame(pending)\n cancelAnimationFrame(scrollFrame)\n clearTimeout(closeTimer)\n})\n</script>\n\n<template>\n <!-- Fixed to the viewport's right edge (not the editor's), above full-width blocks. -->\n <Teleport to=\"body\">\n <nav v-if=\"visible\" v-bind=\"scope\" class=\"me-outline\" :aria-label=\"m.title\" @mouseenter=\"enter\" @mouseleave=\"leave\">\n <div class=\"me-outline-bars\" :class=\"{ 'is-hidden': open }\">\n <span\n v-for=\"(e, i) in entries\"\n :key=\"e.pos\"\n class=\"me-outline-bar\"\n :class=\"{ 'is-active': i === active }\"\n :data-depth=\"e.level - minLevel\"\n />\n </div>\n <div v-if=\"open\" class=\"me-popover me-outline-panel\">\n <button\n v-for=\"(e, i) in entries\"\n :key=\"e.pos\"\n type=\"button\"\n class=\"me-outline-item\"\n :class=\"{ 'is-active': i === active }\"\n :data-depth=\"e.level - minLevel\"\n @click=\"go(e)\"\n >\n {{ e.text || m.untitled }}\n </button>\n </div>\n </nav>\n </Teleport>\n</template>\n","/**\n * Table operations used by the table controls (row/column handles, add buttons,\n * cell toolbar). Rows and columns are addressed by index within a table at `tablePos`.\n */\nimport type { Editor } from '@tiptap/core'\nimport type { Node as PMNode } from '@tiptap/pm/model'\nimport { TextSelection } from '@tiptap/pm/state'\nimport { CellSelection, moveTableColumn, moveTableRow, TableMap } from '@tiptap/pm/tables'\n\nexport interface TableRef { pos: number, node: PMNode, map: TableMap }\n\nexport function tableAt(editor: Editor, pos: number): TableRef | null {\n const node = editor.state.doc.nodeAt(pos)\n if (!node || node.type.name !== 'table') return null\n return { pos, node, map: TableMap.get(node) }\n}\n\n/** Document position of the cell at (row, col). */\nexport function cellPos(t: TableRef, row: number, col: number) {\n return t.pos + 1 + t.map.map[row * t.map.width + col]!\n}\n\n/** Puts the cursor in a cell so Tiptap's table commands act on it. */\nfunction focusCell(editor: Editor, t: TableRef, row: number, col: number) {\n const pos = cellPos(t, row, col)\n editor.view.dispatch(editor.state.tr.setSelection(TextSelection.near(editor.state.doc.resolve(pos + 1))))\n}\n\nexport function selectRow(editor: Editor, t: TableRef, row: number) {\n const $cell = editor.state.doc.resolve(cellPos(t, row, 0))\n editor.view.dispatch(editor.state.tr.setSelection(CellSelection.rowSelection($cell)))\n}\n\nexport function selectColumn(editor: Editor, t: TableRef, col: number) {\n const $cell = editor.state.doc.resolve(cellPos(t, 0, col))\n editor.view.dispatch(editor.state.tr.setSelection(CellSelection.colSelection($cell)))\n}\n\nexport function insertRow(editor: Editor, t: TableRef, row: number, where: 'before' | 'after') {\n focusCell(editor, t, row, 0)\n editor.chain().focus()[where === 'before' ? 'addRowBefore' : 'addRowAfter']().run()\n}\n\nexport function insertColumn(editor: Editor, t: TableRef, col: number, where: 'before' | 'after') {\n focusCell(editor, t, 0, col)\n editor.chain().focus()[where === 'before' ? 'addColumnBefore' : 'addColumnAfter']().run()\n}\n\nexport function deleteRow(editor: Editor, t: TableRef, row: number) {\n if (t.map.height <= 1) return editor.chain().focus().setNodeSelection(t.pos).deleteSelection().run()\n focusCell(editor, t, row, 0)\n editor.chain().focus().deleteRow().run()\n}\n\nexport function deleteColumn(editor: Editor, t: TableRef, col: number) {\n if (t.map.width <= 1) return editor.chain().focus().setNodeSelection(t.pos).deleteSelection().run()\n focusCell(editor, t, 0, col)\n editor.chain().focus().deleteColumn().run()\n}\n\nexport function moveRow(editor: Editor, t: TableRef, from: number, to: number) {\n if (to < 0 || to >= t.map.height) return\n moveTableRow({ from, to, select: true, pos: t.pos + 1 })(editor.state, editor.view.dispatch)\n}\n\nexport function moveColumn(editor: Editor, t: TableRef, from: number, to: number) {\n if (to < 0 || to >= t.map.width) return\n moveTableColumn({ from, to, select: true, pos: t.pos + 1 })(editor.state, editor.view.dispatch)\n}\n\nexport function duplicateRow(editor: Editor, t: TableRef, row: number) {\n const $row = editor.state.doc.resolve(cellPos(t, row, 0))\n const rowNode = $row.parent\n const after = $row.after()\n editor.view.dispatch(editor.state.tr.insert(after, rowNode.copy(rowNode.content)))\n}\n\n/** Copies a column to its right. Skips cells that span several columns. */\nexport function duplicateColumn(editor: Editor, t: TableRef, col: number) {\n const tr = editor.state.tr\n for (let row = t.map.height - 1; row >= 0; row--) {\n const pos = cellPos(t, row, col)\n const cell = editor.state.doc.nodeAt(pos)\n if (!cell || (cell.attrs.colspan ?? 1) > 1 || (row > 0 && cellPos(t, row - 1, col) === pos)) continue\n tr.insert(pos + cell.nodeSize, cell.type.create({ ...cell.attrs, colwidth: cell.attrs.colwidth }, cell.content))\n }\n editor.view.dispatch(tr)\n}\n\n/** Empties the cells of the current cell selection. */\nexport function clearSelectedCells(editor: Editor) {\n const sel = editor.state.selection\n if (!(sel instanceof CellSelection)) return\n const tr = editor.state.tr\n const paragraph = editor.schema.nodes.paragraph!\n sel.forEachCell((cell, pos) => {\n const from = tr.mapping.map(pos + 1)\n const to = tr.mapping.map(pos + cell.nodeSize - 1)\n tr.replaceWith(from, to, paragraph.create())\n })\n editor.view.dispatch(tr)\n}\n\nexport function colorSelectedCells(editor: Editor, color: string | null) {\n editor.chain().focus().setCellAttribute('color', color === 'default' ? null : color).run()\n}\n\nexport const hasHeaderRow = (t: TableRef) => {\n let header = true\n t.node.firstChild?.forEach((cell) => {\n if (cell.type.name !== 'tableHeader') header = false\n })\n return header\n}\n\nexport const hasHeaderColumn = (t: TableRef) => {\n let header = true\n t.node.forEach((row) => {\n if (row.firstChild?.type.name !== 'tableHeader') header = false\n })\n return header\n}\n\nexport function toggleHeader(editor: Editor, t: TableRef, kind: 'row' | 'column') {\n focusCell(editor, t, 0, 0)\n editor.chain().focus()[kind === 'row' ? 'toggleHeaderRow' : 'toggleHeaderColumn']().run()\n}\n","<script setup lang=\"ts\">\n/**\n * Notion-style table controls, drawn over the editor:\n * - grip handles on the hovered row (left) and column (top) → row/column menu\n * - \"+\" bars below and to the right of the table to add a row / column\n * - a small toolbar for multi-cell selections (merge, split, color, clear)\n */\nimport type { Editor } from '@tiptap/vue-3'\nimport type { Component } from 'vue'\nimport {\n ArrowDown, ArrowDownToLine, ArrowLeft, ArrowLeftToLine, ArrowRight, ArrowRightToLine, ArrowUp, ArrowUpToLine,\n Check, ChevronRight, Copy, Eraser, GripHorizontal, GripVertical, Palette, PanelLeft, PanelTop, Plus,\n TableCellsMerge, TableCellsSplit, Trash,\n} from '@lucide/vue'\nimport { CellSelection } from '@tiptap/pm/tables'\nimport { computed, onBeforeUnmount, onMounted, ref, shallowRef } from 'vue'\nimport { COLORS } from '../colors'\nimport { useClickOutside } from '../composables/useClickOutside'\nimport { useScope } from '../composables/useScope'\nimport {\n clearSelectedCells, colorSelectedCells, deleteColumn, deleteRow, duplicateColumn, duplicateRow, hasHeaderColumn,\n hasHeaderRow, insertColumn, insertRow, moveColumn, moveRow, selectColumn, selectRow, tableAt, type TableRef, toggleHeader,\n} from '../table-ops'\n\nconst props = defineProps<{ editor: Editor }>()\n\nconst scope = useScope(() => props.editor)\nconst m = computed(() => props.editor.storage.meiConfig.messages.table)\nconst colorNames = computed(() => props.editor.storage.meiConfig.messages.colors)\nconst layer = ref<HTMLElement | null>(null)\n\n// --- Hover tracking -----------------------------------------------------------\ninterface Hover { tablePos: number, row: number, col: number, table: DOMRect, visible: DOMRect, rowRect: DOMRect, colRect: DOMRect }\nconst hover = shallowRef<Hover | null>(null)\nlet hideTimer: ReturnType<typeof setTimeout> | undefined\nlet frame = 0\n\n/** Rect relative to the controls layer (which covers the editor root). */\nfunction local(r: DOMRect) {\n const base = layer.value!.getBoundingClientRect()\n return new DOMRect(r.left - base.left, r.top - base.top, r.width, r.height)\n}\n\nfunction locate(cell: HTMLElement): Hover | null {\n const { view } = props.editor\n const tableEl = cell.closest('table')\n const wrapper = cell.closest('.tableWrapper') ?? tableEl\n if (!tableEl || !wrapper || !layer.value) return null\n const $pos = view.state.doc.resolve(view.posAtDOM(cell, 0))\n let depth = $pos.depth\n while (depth > 0 && !['tableCell', 'tableHeader'].includes($pos.node(depth).type.name)) depth--\n if (depth < 2) return null\n const tablePos = $pos.before(depth - 2)\n const t = tableAt(props.editor, tablePos)\n if (!t) return null\n const rect = t.map.findCell($pos.before(depth) - tablePos - 1)\n const tableRect = tableEl.getBoundingClientRect()\n const wrapRect = wrapper.getBoundingClientRect()\n const visible = new DOMRect(tableRect.left, tableRect.top, Math.min(tableRect.right, wrapRect.right) - tableRect.left, tableRect.height)\n return {\n tablePos,\n row: rect.top,\n col: rect.left,\n table: local(tableRect),\n visible: local(visible),\n rowRect: local((cell.parentElement as HTMLElement).getBoundingClientRect()),\n colRect: local(cell.getBoundingClientRect()),\n }\n}\n\nfunction onMouseMove(e: MouseEvent) {\n if (menu.value || !props.editor.isEditable) return\n const target = e.target as HTMLElement | null\n if (target?.closest('.me-table-controls-ui')) {\n clearTimeout(hideTimer)\n return\n }\n cancelAnimationFrame(frame)\n frame = requestAnimationFrame(() => {\n const cell = target?.closest('td, th') as HTMLElement | null\n if (cell && props.editor.view.dom.contains(cell)) {\n clearTimeout(hideTimer)\n hover.value = locate(cell)\n }\n else if (hover.value) {\n clearTimeout(hideTimer)\n hideTimer = setTimeout(() => (hover.value = null), 250)\n }\n })\n}\n\nconst table = computed<TableRef | null>(() => {\n void tick.value\n return hover.value ? tableAt(props.editor, hover.value.tablePos) : null\n})\n\n// Re-read the table after edits (positions and sizes change).\nconst tick = ref(0)\nconst onUpdate = () => {\n tick.value++\n if (hover.value && !tableAt(props.editor, hover.value.tablePos)) hover.value = null\n}\n\n// --- Menus --------------------------------------------------------------------\ninterface Item { key: string, label: string, icon: Component, run?: () => void, checked?: boolean, danger?: boolean, disabled?: boolean, submenu?: boolean }\nconst menu = shallowRef<{ kind: 'row' | 'col', index: number, tablePos: number, x: number, y: number, above: boolean } | null>(null)\nconst colorOpen = ref(false)\nconst menuEl = ref<HTMLElement | null>(null)\nuseClickOutside(menuEl, computed(() => !!menu.value), () => closeMenu())\n\nfunction openMenu(kind: 'row' | 'col', e: MouseEvent) {\n const h = hover.value\n const t = table.value\n if (!h || !t) return\n if (kind === 'row') selectRow(props.editor, t, h.row)\n else selectColumn(props.editor, t, h.col)\n const screen = (e.currentTarget as HTMLElement).getBoundingClientRect()\n const r = local(screen)\n // Open upwards when the handle is in the lower part of the viewport (menu is ~360px tall).\n const above = screen.bottom + 360 > window.innerHeight\n menu.value = { kind, index: kind === 'row' ? h.row : h.col, tablePos: h.tablePos, x: r.left, y: r.bottom + 4, above }\n colorOpen.value = false\n}\n\nfunction closeMenu() {\n menu.value = null\n colorOpen.value = false\n}\n\nfunction run(fn: () => void) {\n fn()\n closeMenu()\n props.editor.commands.focus()\n}\n\nconst menuItems = computed<Item[]>(() => {\n const mn = menu.value\n void tick.value\n const t = mn && tableAt(props.editor, mn.tablePos)\n if (!mn || !t) return []\n const ed = props.editor\n const i = mn.index\n const t2 = m.value\n if (mn.kind === 'row') {\n return [\n ...(i === 0 ? [{ key: 'header', label: t2.headerRow, icon: PanelTop, checked: hasHeaderRow(t), run: () => toggleHeader(ed, t, 'row') }] : []),\n { key: 'above', label: t2.insertAbove, icon: ArrowUpToLine, run: () => insertRow(ed, t, i, 'before') },\n { key: 'below', label: t2.insertBelow, icon: ArrowDownToLine, run: () => insertRow(ed, t, i, 'after') },\n { key: 'dup', label: t2.duplicate, icon: Copy, run: () => duplicateRow(ed, t, i) },\n { key: 'up', label: t2.moveUp, icon: ArrowUp, disabled: i === 0, run: () => moveRow(ed, t, i, i - 1) },\n { key: 'down', label: t2.moveDown, icon: ArrowDown, disabled: i === t.map.height - 1, run: () => moveRow(ed, t, i, i + 1) },\n { key: 'clear', label: t2.clear, icon: Eraser, run: () => clearSelectedCells(ed) },\n { key: 'color', label: t2.color, icon: Palette, submenu: true },\n { key: 'delete', label: t2.deleteRow, icon: Trash, danger: true, run: () => deleteRow(ed, t, i) },\n ]\n }\n return [\n ...(i === 0 ? [{ key: 'header', label: t2.headerColumn, icon: PanelLeft, checked: hasHeaderColumn(t), run: () => toggleHeader(ed, t, 'column') }] : []),\n { key: 'left', label: t2.insertLeft, icon: ArrowLeftToLine, run: () => insertColumn(ed, t, i, 'before') },\n { key: 'right', label: t2.insertRight, icon: ArrowRightToLine, run: () => insertColumn(ed, t, i, 'after') },\n { key: 'dup', label: t2.duplicate, icon: Copy, run: () => duplicateColumn(ed, t, i) },\n { key: 'mleft', label: t2.moveLeft, icon: ArrowLeft, disabled: i === 0, run: () => moveColumn(ed, t, i, i - 1) },\n { key: 'mright', label: t2.moveRight, icon: ArrowRight, disabled: i === t.map.width - 1, run: () => moveColumn(ed, t, i, i + 1) },\n { key: 'clear', label: t2.clear, icon: Eraser, run: () => clearSelectedCells(ed) },\n { key: 'color', label: t2.color, icon: Palette, submenu: true },\n { key: 'delete', label: t2.deleteColumn, icon: Trash, danger: true, run: () => deleteColumn(ed, t, i) },\n ]\n})\n\nfunction onMenuKey(e: KeyboardEvent) {\n if (e.key === 'Escape') closeMenu()\n}\n\n// --- Add row / column -----------------------------------------------------------\nfunction addRow() {\n const t = table.value\n if (t) insertRow(props.editor, t, t.map.height - 1, 'after')\n}\nfunction addColumn() {\n const t = table.value\n if (t) insertColumn(props.editor, t, t.map.width - 1, 'after')\n}\n\n// --- Multi-cell toolbar -------------------------------------------------------------\nconst selection = shallowRef<{ x: number, y: number, canMerge: boolean, canSplit: boolean } | null>(null)\nconst cellColorOpen = ref(false)\nfunction onSelection() {\n const sel = props.editor.state.selection\n if (!(sel instanceof CellSelection) || menu.value || !layer.value) {\n selection.value = null\n cellColorOpen.value = false\n return\n }\n let top = Infinity\n let left = Infinity\n sel.forEachCell((_cell, pos) => {\n const dom = props.editor.view.nodeDOM(pos)\n if (dom instanceof HTMLElement) {\n const r = local(dom.getBoundingClientRect())\n top = Math.min(top, r.top)\n left = Math.min(left, r.left)\n }\n })\n if (!Number.isFinite(top)) return\n selection.value = { x: left, y: top, canMerge: props.editor.can().mergeCells(), canSplit: props.editor.can().splitCell() }\n}\n\nconst bgColors = COLORS\n\nonMounted(() => {\n document.addEventListener('mousemove', onMouseMove)\n props.editor.on('update', onUpdate)\n props.editor.on('selectionUpdate', onSelection)\n})\nonBeforeUnmount(() => {\n document.removeEventListener('mousemove', onMouseMove)\n props.editor.off('update', onUpdate)\n props.editor.off('selectionUpdate', onSelection)\n clearTimeout(hideTimer)\n cancelAnimationFrame(frame)\n})\n</script>\n\n<template>\n <div ref=\"layer\" class=\"me-table-controls\">\n <template v-if=\"hover && table && !menu\">\n <button\n type=\"button\"\n class=\"me-table-controls-ui me-table-grip me-table-grip--row\"\n :style=\"{ left: `${hover.table.left}px`, top: `${hover.rowRect.top}px`, height: `${hover.rowRect.height}px` }\"\n :title=\"m.rowMenu\"\n @mousedown.prevent\n @click=\"openMenu('row', $event)\"\n >\n <GripVertical />\n </button>\n <button\n type=\"button\"\n class=\"me-table-controls-ui me-table-grip me-table-grip--col\"\n :style=\"{ left: `${hover.colRect.left}px`, top: `${hover.table.top}px`, width: `${hover.colRect.width}px` }\"\n :title=\"m.columnMenu\"\n @mousedown.prevent\n @click=\"openMenu('col', $event)\"\n >\n <GripHorizontal />\n </button>\n <button\n type=\"button\"\n class=\"me-table-controls-ui me-table-add me-table-add--row\"\n :style=\"{ left: `${hover.visible.left}px`, top: `${hover.table.top + hover.table.height}px`, width: `${hover.visible.width}px` }\"\n :title=\"m.addRow\"\n @mousedown.prevent\n @click=\"addRow\"\n >\n <Plus />\n </button>\n <button\n type=\"button\"\n class=\"me-table-controls-ui me-table-add me-table-add--col\"\n :style=\"{ left: `${hover.visible.left + hover.visible.width}px`, top: `${hover.table.top}px`, height: `${hover.table.height}px` }\"\n :title=\"m.addColumn\"\n @mousedown.prevent\n @click=\"addColumn\"\n >\n <Plus />\n </button>\n </template>\n\n <div\n v-if=\"menu\"\n ref=\"menuEl\"\n v-bind=\"scope\"\n class=\"me-table-controls-ui me-popover me-block-menu me-table-menu\"\n :class=\"{ 'is-above': menu.above }\"\n :style=\"{ left: `${menu.x}px`, top: `${menu.y}px` }\"\n tabindex=\"-1\"\n @keydown=\"onMenuKey\"\n @mousedown.prevent\n >\n <div v-for=\"item in menuItems\" :key=\"item.key\" class=\"me-submenu-anchor\" @mouseenter=\"colorOpen = !!item.submenu\">\n <button\n type=\"button\"\n class=\"me-menu-item\"\n :class=\"{ 'is-danger': item.danger, 'is-active': item.submenu && colorOpen }\"\n :disabled=\"item.disabled\"\n @click=\"item.submenu ? (colorOpen = !colorOpen) : run(item.run!)\"\n >\n <span class=\"me-menu-icon\"><component :is=\"item.icon\" /></span>\n <span class=\"me-menu-title me-menu-text\">{{ item.label }}</span>\n <Check v-if=\"item.checked\" class=\"me-menu-check\" />\n <ChevronRight v-if=\"item.submenu\" class=\"me-menu-chevron\" />\n </button>\n <div v-if=\"item.submenu && colorOpen\" class=\"me-popover me-submenu\">\n <button v-for=\"c in bgColors\" :key=\"c\" type=\"button\" class=\"me-menu-item\" @click=\"run(() => colorSelectedCells(editor, c))\">\n <span class=\"me-menu-icon me-swatch--bg\" :data-color=\"c === 'default' ? undefined : c\">A</span>\n <span class=\"me-menu-title me-menu-text\">{{ colorNames[c] }}</span>\n </button>\n </div>\n </div>\n </div>\n\n <div\n v-if=\"selection && !menu\"\n v-bind=\"scope\"\n class=\"me-table-controls-ui me-popover me-toolbar me-table-toolbar\"\n :style=\"{ left: `${selection.x}px`, top: `${selection.y}px` }\"\n @mousedown.prevent\n >\n <button v-if=\"selection.canMerge\" type=\"button\" class=\"me-tool-btn\" :title=\"m.merge\" @click=\"editor.chain().focus().mergeCells().run()\">\n <TableCellsMerge /> {{ m.merge }}\n </button>\n <button v-if=\"selection.canSplit\" type=\"button\" class=\"me-tool-btn\" :title=\"m.split\" @click=\"editor.chain().focus().splitCell().run()\">\n <TableCellsSplit /> {{ m.split }}\n </button>\n <span class=\"me-submenu-anchor\">\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.color\" @click=\"cellColorOpen = !cellColorOpen\">\n <Palette />\n </button>\n <div v-if=\"cellColorOpen\" class=\"me-popover me-toolbar-panel me-menu\">\n <button v-for=\"c in bgColors\" :key=\"c\" type=\"button\" class=\"me-menu-item\" @click=\"colorSelectedCells(editor, c); cellColorOpen = false\">\n <span class=\"me-menu-icon me-swatch--bg\" :data-color=\"c === 'default' ? undefined : c\">A</span>\n <span class=\"me-menu-title me-menu-text\">{{ colorNames[c] }}</span>\n </button>\n </div>\n </span>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.clear\" @click=\"clearSelectedCells(editor)\">\n <Eraser />\n </button>\n </div>\n </div>\n</template>\n","<script setup lang=\"ts\">\n/**\n * Notion-style table controls, drawn over the editor:\n * - grip handles on the hovered row (left) and column (top) → row/column menu\n * - \"+\" bars below and to the right of the table to add a row / column\n * - a small toolbar for multi-cell selections (merge, split, color, clear)\n */\nimport type { Editor } from '@tiptap/vue-3'\nimport type { Component } from 'vue'\nimport {\n ArrowDown, ArrowDownToLine, ArrowLeft, ArrowLeftToLine, ArrowRight, ArrowRightToLine, ArrowUp, ArrowUpToLine,\n Check, ChevronRight, Copy, Eraser, GripHorizontal, GripVertical, Palette, PanelLeft, PanelTop, Plus,\n TableCellsMerge, TableCellsSplit, Trash,\n} from '@lucide/vue'\nimport { CellSelection } from '@tiptap/pm/tables'\nimport { computed, onBeforeUnmount, onMounted, ref, shallowRef } from 'vue'\nimport { COLORS } from '../colors'\nimport { useClickOutside } from '../composables/useClickOutside'\nimport { useScope } from '../composables/useScope'\nimport {\n clearSelectedCells, colorSelectedCells, deleteColumn, deleteRow, duplicateColumn, duplicateRow, hasHeaderColumn,\n hasHeaderRow, insertColumn, insertRow, moveColumn, moveRow, selectColumn, selectRow, tableAt, type TableRef, toggleHeader,\n} from '../table-ops'\n\nconst props = defineProps<{ editor: Editor }>()\n\nconst scope = useScope(() => props.editor)\nconst m = computed(() => props.editor.storage.meiConfig.messages.table)\nconst colorNames = computed(() => props.editor.storage.meiConfig.messages.colors)\nconst layer = ref<HTMLElement | null>(null)\n\n// --- Hover tracking -----------------------------------------------------------\ninterface Hover { tablePos: number, row: number, col: number, table: DOMRect, visible: DOMRect, rowRect: DOMRect, colRect: DOMRect }\nconst hover = shallowRef<Hover | null>(null)\nlet hideTimer: ReturnType<typeof setTimeout> | undefined\nlet frame = 0\n\n/** Rect relative to the controls layer (which covers the editor root). */\nfunction local(r: DOMRect) {\n const base = layer.value!.getBoundingClientRect()\n return new DOMRect(r.left - base.left, r.top - base.top, r.width, r.height)\n}\n\nfunction locate(cell: HTMLElement): Hover | null {\n const { view } = props.editor\n const tableEl = cell.closest('table')\n const wrapper = cell.closest('.tableWrapper') ?? tableEl\n if (!tableEl || !wrapper || !layer.value) return null\n const $pos = view.state.doc.resolve(view.posAtDOM(cell, 0))\n let depth = $pos.depth\n while (depth > 0 && !['tableCell', 'tableHeader'].includes($pos.node(depth).type.name)) depth--\n if (depth < 2) return null\n const tablePos = $pos.before(depth - 2)\n const t = tableAt(props.editor, tablePos)\n if (!t) return null\n const rect = t.map.findCell($pos.before(depth) - tablePos - 1)\n const tableRect = tableEl.getBoundingClientRect()\n const wrapRect = wrapper.getBoundingClientRect()\n const visible = new DOMRect(tableRect.left, tableRect.top, Math.min(tableRect.right, wrapRect.right) - tableRect.left, tableRect.height)\n return {\n tablePos,\n row: rect.top,\n col: rect.left,\n table: local(tableRect),\n visible: local(visible),\n rowRect: local((cell.parentElement as HTMLElement).getBoundingClientRect()),\n colRect: local(cell.getBoundingClientRect()),\n }\n}\n\nfunction onMouseMove(e: MouseEvent) {\n if (menu.value || !props.editor.isEditable) return\n const target = e.target as HTMLElement | null\n if (target?.closest('.me-table-controls-ui')) {\n clearTimeout(hideTimer)\n return\n }\n cancelAnimationFrame(frame)\n frame = requestAnimationFrame(() => {\n const cell = target?.closest('td, th') as HTMLElement | null\n if (cell && props.editor.view.dom.contains(cell)) {\n clearTimeout(hideTimer)\n hover.value = locate(cell)\n }\n else if (hover.value) {\n clearTimeout(hideTimer)\n hideTimer = setTimeout(() => (hover.value = null), 250)\n }\n })\n}\n\nconst table = computed<TableRef | null>(() => {\n void tick.value\n return hover.value ? tableAt(props.editor, hover.value.tablePos) : null\n})\n\n// Re-read the table after edits (positions and sizes change).\nconst tick = ref(0)\nconst onUpdate = () => {\n tick.value++\n if (hover.value && !tableAt(props.editor, hover.value.tablePos)) hover.value = null\n}\n\n// --- Menus --------------------------------------------------------------------\ninterface Item { key: string, label: string, icon: Component, run?: () => void, checked?: boolean, danger?: boolean, disabled?: boolean, submenu?: boolean }\nconst menu = shallowRef<{ kind: 'row' | 'col', index: number, tablePos: number, x: number, y: number, above: boolean } | null>(null)\nconst colorOpen = ref(false)\nconst menuEl = ref<HTMLElement | null>(null)\nuseClickOutside(menuEl, computed(() => !!menu.value), () => closeMenu())\n\nfunction openMenu(kind: 'row' | 'col', e: MouseEvent) {\n const h = hover.value\n const t = table.value\n if (!h || !t) return\n if (kind === 'row') selectRow(props.editor, t, h.row)\n else selectColumn(props.editor, t, h.col)\n const screen = (e.currentTarget as HTMLElement).getBoundingClientRect()\n const r = local(screen)\n // Open upwards when the handle is in the lower part of the viewport (menu is ~360px tall).\n const above = screen.bottom + 360 > window.innerHeight\n menu.value = { kind, index: kind === 'row' ? h.row : h.col, tablePos: h.tablePos, x: r.left, y: r.bottom + 4, above }\n colorOpen.value = false\n}\n\nfunction closeMenu() {\n menu.value = null\n colorOpen.value = false\n}\n\nfunction run(fn: () => void) {\n fn()\n closeMenu()\n props.editor.commands.focus()\n}\n\nconst menuItems = computed<Item[]>(() => {\n const mn = menu.value\n void tick.value\n const t = mn && tableAt(props.editor, mn.tablePos)\n if (!mn || !t) return []\n const ed = props.editor\n const i = mn.index\n const t2 = m.value\n if (mn.kind === 'row') {\n return [\n ...(i === 0 ? [{ key: 'header', label: t2.headerRow, icon: PanelTop, checked: hasHeaderRow(t), run: () => toggleHeader(ed, t, 'row') }] : []),\n { key: 'above', label: t2.insertAbove, icon: ArrowUpToLine, run: () => insertRow(ed, t, i, 'before') },\n { key: 'below', label: t2.insertBelow, icon: ArrowDownToLine, run: () => insertRow(ed, t, i, 'after') },\n { key: 'dup', label: t2.duplicate, icon: Copy, run: () => duplicateRow(ed, t, i) },\n { key: 'up', label: t2.moveUp, icon: ArrowUp, disabled: i === 0, run: () => moveRow(ed, t, i, i - 1) },\n { key: 'down', label: t2.moveDown, icon: ArrowDown, disabled: i === t.map.height - 1, run: () => moveRow(ed, t, i, i + 1) },\n { key: 'clear', label: t2.clear, icon: Eraser, run: () => clearSelectedCells(ed) },\n { key: 'color', label: t2.color, icon: Palette, submenu: true },\n { key: 'delete', label: t2.deleteRow, icon: Trash, danger: true, run: () => deleteRow(ed, t, i) },\n ]\n }\n return [\n ...(i === 0 ? [{ key: 'header', label: t2.headerColumn, icon: PanelLeft, checked: hasHeaderColumn(t), run: () => toggleHeader(ed, t, 'column') }] : []),\n { key: 'left', label: t2.insertLeft, icon: ArrowLeftToLine, run: () => insertColumn(ed, t, i, 'before') },\n { key: 'right', label: t2.insertRight, icon: ArrowRightToLine, run: () => insertColumn(ed, t, i, 'after') },\n { key: 'dup', label: t2.duplicate, icon: Copy, run: () => duplicateColumn(ed, t, i) },\n { key: 'mleft', label: t2.moveLeft, icon: ArrowLeft, disabled: i === 0, run: () => moveColumn(ed, t, i, i - 1) },\n { key: 'mright', label: t2.moveRight, icon: ArrowRight, disabled: i === t.map.width - 1, run: () => moveColumn(ed, t, i, i + 1) },\n { key: 'clear', label: t2.clear, icon: Eraser, run: () => clearSelectedCells(ed) },\n { key: 'color', label: t2.color, icon: Palette, submenu: true },\n { key: 'delete', label: t2.deleteColumn, icon: Trash, danger: true, run: () => deleteColumn(ed, t, i) },\n ]\n})\n\nfunction onMenuKey(e: KeyboardEvent) {\n if (e.key === 'Escape') closeMenu()\n}\n\n// --- Add row / column -----------------------------------------------------------\nfunction addRow() {\n const t = table.value\n if (t) insertRow(props.editor, t, t.map.height - 1, 'after')\n}\nfunction addColumn() {\n const t = table.value\n if (t) insertColumn(props.editor, t, t.map.width - 1, 'after')\n}\n\n// --- Multi-cell toolbar -------------------------------------------------------------\nconst selection = shallowRef<{ x: number, y: number, canMerge: boolean, canSplit: boolean } | null>(null)\nconst cellColorOpen = ref(false)\nfunction onSelection() {\n const sel = props.editor.state.selection\n if (!(sel instanceof CellSelection) || menu.value || !layer.value) {\n selection.value = null\n cellColorOpen.value = false\n return\n }\n let top = Infinity\n let left = Infinity\n sel.forEachCell((_cell, pos) => {\n const dom = props.editor.view.nodeDOM(pos)\n if (dom instanceof HTMLElement) {\n const r = local(dom.getBoundingClientRect())\n top = Math.min(top, r.top)\n left = Math.min(left, r.left)\n }\n })\n if (!Number.isFinite(top)) return\n selection.value = { x: left, y: top, canMerge: props.editor.can().mergeCells(), canSplit: props.editor.can().splitCell() }\n}\n\nconst bgColors = COLORS\n\nonMounted(() => {\n document.addEventListener('mousemove', onMouseMove)\n props.editor.on('update', onUpdate)\n props.editor.on('selectionUpdate', onSelection)\n})\nonBeforeUnmount(() => {\n document.removeEventListener('mousemove', onMouseMove)\n props.editor.off('update', onUpdate)\n props.editor.off('selectionUpdate', onSelection)\n clearTimeout(hideTimer)\n cancelAnimationFrame(frame)\n})\n</script>\n\n<template>\n <div ref=\"layer\" class=\"me-table-controls\">\n <template v-if=\"hover && table && !menu\">\n <button\n type=\"button\"\n class=\"me-table-controls-ui me-table-grip me-table-grip--row\"\n :style=\"{ left: `${hover.table.left}px`, top: `${hover.rowRect.top}px`, height: `${hover.rowRect.height}px` }\"\n :title=\"m.rowMenu\"\n @mousedown.prevent\n @click=\"openMenu('row', $event)\"\n >\n <GripVertical />\n </button>\n <button\n type=\"button\"\n class=\"me-table-controls-ui me-table-grip me-table-grip--col\"\n :style=\"{ left: `${hover.colRect.left}px`, top: `${hover.table.top}px`, width: `${hover.colRect.width}px` }\"\n :title=\"m.columnMenu\"\n @mousedown.prevent\n @click=\"openMenu('col', $event)\"\n >\n <GripHorizontal />\n </button>\n <button\n type=\"button\"\n class=\"me-table-controls-ui me-table-add me-table-add--row\"\n :style=\"{ left: `${hover.visible.left}px`, top: `${hover.table.top + hover.table.height}px`, width: `${hover.visible.width}px` }\"\n :title=\"m.addRow\"\n @mousedown.prevent\n @click=\"addRow\"\n >\n <Plus />\n </button>\n <button\n type=\"button\"\n class=\"me-table-controls-ui me-table-add me-table-add--col\"\n :style=\"{ left: `${hover.visible.left + hover.visible.width}px`, top: `${hover.table.top}px`, height: `${hover.table.height}px` }\"\n :title=\"m.addColumn\"\n @mousedown.prevent\n @click=\"addColumn\"\n >\n <Plus />\n </button>\n </template>\n\n <div\n v-if=\"menu\"\n ref=\"menuEl\"\n v-bind=\"scope\"\n class=\"me-table-controls-ui me-popover me-block-menu me-table-menu\"\n :class=\"{ 'is-above': menu.above }\"\n :style=\"{ left: `${menu.x}px`, top: `${menu.y}px` }\"\n tabindex=\"-1\"\n @keydown=\"onMenuKey\"\n @mousedown.prevent\n >\n <div v-for=\"item in menuItems\" :key=\"item.key\" class=\"me-submenu-anchor\" @mouseenter=\"colorOpen = !!item.submenu\">\n <button\n type=\"button\"\n class=\"me-menu-item\"\n :class=\"{ 'is-danger': item.danger, 'is-active': item.submenu && colorOpen }\"\n :disabled=\"item.disabled\"\n @click=\"item.submenu ? (colorOpen = !colorOpen) : run(item.run!)\"\n >\n <span class=\"me-menu-icon\"><component :is=\"item.icon\" /></span>\n <span class=\"me-menu-title me-menu-text\">{{ item.label }}</span>\n <Check v-if=\"item.checked\" class=\"me-menu-check\" />\n <ChevronRight v-if=\"item.submenu\" class=\"me-menu-chevron\" />\n </button>\n <div v-if=\"item.submenu && colorOpen\" class=\"me-popover me-submenu\">\n <button v-for=\"c in bgColors\" :key=\"c\" type=\"button\" class=\"me-menu-item\" @click=\"run(() => colorSelectedCells(editor, c))\">\n <span class=\"me-menu-icon me-swatch--bg\" :data-color=\"c === 'default' ? undefined : c\">A</span>\n <span class=\"me-menu-title me-menu-text\">{{ colorNames[c] }}</span>\n </button>\n </div>\n </div>\n </div>\n\n <div\n v-if=\"selection && !menu\"\n v-bind=\"scope\"\n class=\"me-table-controls-ui me-popover me-toolbar me-table-toolbar\"\n :style=\"{ left: `${selection.x}px`, top: `${selection.y}px` }\"\n @mousedown.prevent\n >\n <button v-if=\"selection.canMerge\" type=\"button\" class=\"me-tool-btn\" :title=\"m.merge\" @click=\"editor.chain().focus().mergeCells().run()\">\n <TableCellsMerge /> {{ m.merge }}\n </button>\n <button v-if=\"selection.canSplit\" type=\"button\" class=\"me-tool-btn\" :title=\"m.split\" @click=\"editor.chain().focus().splitCell().run()\">\n <TableCellsSplit /> {{ m.split }}\n </button>\n <span class=\"me-submenu-anchor\">\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.color\" @click=\"cellColorOpen = !cellColorOpen\">\n <Palette />\n </button>\n <div v-if=\"cellColorOpen\" class=\"me-popover me-toolbar-panel me-menu\">\n <button v-for=\"c in bgColors\" :key=\"c\" type=\"button\" class=\"me-menu-item\" @click=\"colorSelectedCells(editor, c); cellColorOpen = false\">\n <span class=\"me-menu-icon me-swatch--bg\" :data-color=\"c === 'default' ? undefined : c\">A</span>\n <span class=\"me-menu-title me-menu-text\">{{ colorNames[c] }}</span>\n </button>\n </div>\n </span>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.clear\" @click=\"clearSelectedCells(editor)\">\n <Eraser />\n </button>\n </div>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport type { AnyExtension } from '@tiptap/core'\nimport { Editor, EditorContent, type EditorOptions, type JSONContent } from '@tiptap/vue-3'\nimport { DragHandle } from '@tiptap/extension-drag-handle-vue-3'\nimport type { NestedOptions } from '@tiptap/extension-drag-handle'\nimport type { Node as PMNode } from '@tiptap/pm/model'\nimport type { ComputePositionConfig, Middleware } from '@floating-ui/dom'\nimport { GripVertical, Plus } from '@lucide/vue'\nimport { computed, inject, onBeforeUnmount, onMounted, ref, shallowRef, toRaw, useId, watch, watchEffect } from 'vue'\nimport type { ImageUploader } from '../config'\nimport { createExtensions } from '../extensions'\nimport type { MeiCollaboration } from '../collaboration'\nimport { type BlockRange, currentRange, isBlockSelection, rangeOfBlock, selectBlocks } from '../block-ops'\nimport { handleAnchorRect } from '../handle-anchor'\nimport { kbd } from '../keys'\nimport { type LocaleName, type PartialMessages, resolveMessages } from '../locale'\nimport { GLOBAL_BLOCKS_KEY, GLOBAL_TOKENS_KEY } from '../plugin-key'\nimport { defaultBlocks, text } from '../blocks'\nimport type { BlockDefinition } from '../define-block'\nimport { ContentError, type ContentIssue, sanitizeContent, unwrapUnknown } from '../content'\nimport { assignIds } from '../extensions/block-id'\nimport { injectStyle, installBaseTokens, overridesCss, type ThemeMode, type ThemeTokens } from '../theme'\nimport BlockMenu from './BlockMenu.vue'\nimport FormatMenu from './FormatMenu.vue'\nimport MeiOutline from './MeiOutline.vue'\nimport TableControls from './TableControls.vue'\n\nconst props = withDefaults(defineProps<{\n /** Document as Tiptap JSON. Use with `v-model`. */\n modelValue?: JSONContent | null\n editable?: boolean\n autofocus?: boolean | 'start' | 'end'\n /** Built-in UI language. */\n locale?: LocaleName\n /** Override any UI string, e.g. `{ placeholder: 'Write…' }`. */\n messages?: PartialMessages\n /**\n * Blocks to load (read once, at mount). Defaults to the app-wide list from the\n * Vue plugin / Nuxt module, else `defaultBlocks`.\n */\n blocks?: BlockDefinition[]\n /** Uploads an image and returns its URL. Without it images are stored as base64. */\n uploadImage?: ImageUploader\n /** Max image size in MB. */\n maxImageSize?: number\n /** Extra Tiptap extensions appended to the built-in ones. */\n extensions?: AnyExtension[]\n /** Light / dark mode. `auto` follows `<html class=\"dark\">`. */\n theme?: ThemeMode\n /** Design token overrides for this editor, e.g. `{ color: { accent: '#7c3aed' } }`. */\n tokens?: ThemeTokens\n /** URL for \"Copy link to block\". Default: current page URL + `#<block id>`. */\n blockLink?: (id: string) => string\n /**\n * Floating outline on the right edge (Notion-style). Shown once the page has\n * `minHeadings` headings (default 2). `false` turns it off.\n */\n outline?: boolean | { minHeadings?: number }\n /**\n * Edit a shared Yjs document (read once, at mount). The `Y.Doc` is the source of truth:\n * `modelValue` is ignored and `update:modelValue` is not emitted — listen to `change`\n * (cheap, no payload to serialize) and read the document yourself when needed.\n * Undo / redo become Yjs undo (only your own changes).\n */\n collaboration?: MeiCollaboration\n}>(), {\n outline: true,\n theme: 'auto',\n modelValue: null,\n editable: true,\n autofocus: false,\n locale: 'vi',\n maxImageSize: 5,\n})\n\nconst emit = defineEmits<{\n /** Document after each change (not emitted in collaboration mode). */\n 'update:modelValue': [content: JSONContent]\n /**\n * Fired on every document change, local or remote, without serializing it. Debounce\n * your own work (saving, title extraction…) and call `editor.getJSON()` when you need it.\n */\n 'change': [info: { editor: Editor }]\n 'ready': [editor: Editor]\n /**\n * Problems found while loading content. `fatal` means the input isn't a document:\n * the editor turns read-only and stops emitting updates so saved data isn't overwritten.\n */\n 'content-error': [info: { fatal: boolean, issues: ContentIssue[], error?: Error }]\n}>()\n\n/** Set when content couldn't be read at all; blocks editing and updates until fixed. */\nconst contentFailed = ref(false)\n\n// Paragraphs (`text`) are always available; other blocks come from props or app config.\nconst globalBlocks = inject(GLOBAL_BLOCKS_KEY, undefined)\nconst blocks = [text, ...(props.blocks ?? globalBlocks ?? defaultBlocks)]\n .filter((b, i, all) => all.findIndex(o => o.name === b.name) === i)\n\nconst rootEl = ref<HTMLElement | null>(null)\nconst outlineMin = computed(() => (typeof props.outline === 'object' ? props.outline.minHeadings ?? 2 : 2))\nconst hasTables = computed(() => !!editor.value?.schema.nodes.table)\n\nconst messages = computed(() => resolveMessages(props.locale, ...blocks.map(b => b.messages?.[props.locale]), props.messages))\n\n// --- Theme ----------------------------------------------------------------\n// Default tokens are injected once; per-editor overrides go in a <style> scoped by id,\n// and the same scope attrs are copied onto popovers rendered in <body>.\ninstallBaseTokens()\nconst instanceId = `me-${useId()}`\nconst globalTokens = inject(GLOBAL_TOKENS_KEY, undefined)\nconst scope = computed(() => ({\n 'class': ['me-scope', props.theme === 'light' ? 'me-light' : props.theme === 'dark' ? 'me-dark' : ''].filter(Boolean),\n 'data-me-id': instanceId,\n}))\nwatchEffect(() => {\n const css = [\n overridesCss(globalTokens?.value, `.me-scope[data-me-id=\"${instanceId}\"]`),\n overridesCss(props.tokens, `.me-scope[data-me-id=\"${instanceId}\"]`),\n ].filter(Boolean).join('\\n')\n injectStyle(`mei-editor-${instanceId}`, css)\n})\nonBeforeUnmount(() => injectStyle(`mei-editor-${instanceId}`, ''))\n\n/**\n * Validates content (repairing or quarantining broken blocks), wraps unknown block\n * types and assigns missing ids. Never yields a blank doc for bad input: on a fatal\n * error the editor goes read-only and keeps the previous content.\n */\nfunction prepare(doc: JSONContent | null | undefined, ed: { schema: Editor['schema'], extensionManager: Editor['extensionManager'] }): JSONContent | null | undefined {\n const types = ed.extensionManager.extensions.find(e => e.name === 'blockId')?.options.types ?? []\n const issues: ContentIssue[] = []\n try {\n const content = assignIds(sanitizeContent(doc, ed.schema, issues), types)\n contentFailed.value = false\n if (issues.some(i => i.kind !== 'unknown')) {\n console.warn('[MeiEditor] Some blocks were repaired or kept as invalid:', issues)\n emit('content-error', { fatal: false, issues })\n }\n return content\n }\n catch (error) {\n contentFailed.value = true\n console.error('[MeiEditor] Content could not be loaded:', error)\n emit('content-error', { fatal: true, issues, error: error instanceof Error ? error : new ContentError(String(error), doc) })\n return undefined\n }\n}\n\n/** Loads content unless it is unreadable (then the current doc stays, read-only). */\nfunction load(ed: Editor, doc: JSONContent | null | undefined) {\n const content = prepare(doc, ed)\n if (content !== undefined) ed.commands.setContent(content ?? '', { emitUpdate: false })\n ed.setEditable(props.editable && !contentFailed.value)\n}\n\n// The last value we emitted, so an echoed v-model update doesn't reset the doc.\nlet lastEmitted: JSONContent | null = null\n\n// Read once, like `blocks`. With it the Y.Doc owns the content: never setContent / v-model.\nconst collaboration = props.collaboration ? toRaw(props.collaboration) : undefined\n\nconst editor = shallowRef<Editor>()\nlet unmounted = false\n\nfunction createEditor(extra: AnyExtension[]) {\n const options: Partial<EditorOptions> = {\n extensions: [\n ...createExtensions({\n blocks,\n messages: messages.value,\n locale: props.locale,\n uploadImage: props.uploadImage ?? null,\n maxImageSize: props.maxImageSize,\n scope: scope.value,\n // Collaboration brings Yjs undo (Mod-z / Mod-Shift-z); two histories would fight.\n undoRedo: !collaboration,\n }),\n ...extra,\n ...(props.extensions ?? []),\n ],\n content: null,\n editable: props.editable,\n autofocus: props.autofocus,\n editorProps: {\n attributes: { class: 'me-content', spellcheck: 'false' },\n },\n onCreate: ({ editor }) => {\n // Load content after the schema exists, so unknown block types can be wrapped.\n if (!collaboration) load(editor as Editor, toRaw(props.modelValue))\n emit('ready', editor as Editor)\n },\n onUpdate: ({ editor }) => {\n if (contentFailed.value) return\n emit('change', { editor: editor as Editor })\n // getJSON() is O(document): skip it when nobody needs the JSON (collaboration).\n if (collaboration) return\n lastEmitted = unwrapUnknown(editor.getJSON())\n emit('update:modelValue', lastEmitted)\n },\n }\n editor.value = new Editor(options)\n}\n\nonMounted(() => {\n if (!collaboration) {\n createEditor([])\n return\n }\n // Yjs + the sync plugin load only for collaborative editors.\n import('../collaboration').then(({ collaborationExtensions }) => {\n if (!unmounted) createEditor(collaborationExtensions(collaboration))\n }).catch(error => console.error('[MeiEditor] Collaboration could not be loaded:', error))\n})\n\n// Only reload the document for real external changes. `v-model` on a `ref()` hands\n// back a reactive proxy of what we emitted, so compare the raw object, then content.\nwatch(() => props.modelValue, (value) => {\n const ed = editor.value\n const raw = value ? toRaw(value) : null\n if (!ed || collaboration || raw === lastEmitted) return\n if (raw && JSON.stringify(raw) === JSON.stringify(unwrapUnknown(ed.getJSON()))) return\n load(ed, raw)\n})\nwatch(() => props.editable, value => editor.value?.setEditable(value && !contentFailed.value))\nwatch([messages, () => props.locale, () => props.uploadImage, () => props.maxImageSize, scope], () => {\n const config = editor.value?.storage.meiConfig\n if (!config) return\n config.messages = messages.value\n config.locale = props.locale\n config.uploadImage = props.uploadImage ?? null\n config.maxImageSize = props.maxImageSize\n config.scope = scope.value\n})\n\ndefineExpose({ editor })\n\n// --- Drag handle + block menu -------------------------------------------\n// Show the handle for top-level blocks and for blocks directly inside a column\n// (not for list items, table cells, callout children...). On ties the deeper\n// node wins, so inside a column you grab the block, not the whole columns row.\nconst nestedOptions: NestedOptions = {\n defaultRules: false,\n edgeDetection: 'none',\n rules: [{\n id: 'blockLevelOnly',\n evaluate: ({ node, parent }) => {\n if (!parent || node.type.name === 'column') return 1000\n return ['doc', 'column'].includes(parent.type.name) ? 0 : 1000\n },\n }],\n}\n\ninterface HoveredBlock { node: PMNode, pos: number }\nconst hovered = shallowRef<HoveredBlock | null>(null)\nconst menu = shallowRef<{ range: BlockRange, anchor: DOMRect } | null>(null)\n\n// Block under the pointer, for placing the handle (tracked even while a menu is open).\nlet handlePos: number | null = null\n\nfunction onNodeChange({ node, pos }: { node: PMNode | null, pos: number }) {\n handlePos = node ? pos : null\n if (menu.value) return\n hovered.value = node ? { node, pos } : null\n}\n\n/**\n * Centers the handle on the block's anchor line (first text line, header bar, divider…)\n * instead of aligning tops, so it lines up the same way for every block type.\n */\nconst alignHandleToLine: Middleware = {\n name: 'meAlignToLine',\n fn({ y, rects }) {\n const ed = editor.value\n const dom = ed && handlePos !== null ? ed.view.nodeDOM(handlePos) : null\n if (!(dom instanceof HTMLElement)) return {}\n const anchor = handleAnchorRect(dom)\n // Work in the reference's own coordinates: shift by the anchor's offset from the block's top.\n const offset = anchor.top + anchor.height / 2 - dom.getBoundingClientRect().top\n return { y: Number.isFinite(offset) ? rects.reference.y + offset - rects.floating.height / 2 : y }\n },\n}\nconst handlePosition: Partial<ComputePositionConfig> = { placement: 'left-start', strategy: 'absolute', middleware: [alignHandleToLine] }\n\n// Lets the BlockDrop extension take over the drop (see block-drop.ts).\nfunction onDragStart() {\n const config = editor.value?.storage.blockDrop\n if (config) config.active = true\n}\n\nfunction setHandleLocked(locked: boolean) {\n const ed = editor.value\n if (ed && !ed.isDestroyed) ed.view.dispatch(ed.state.tr.setMeta('lockDragHandle', locked))\n}\n\nfunction showMenu(range: BlockRange, anchor: DOMRect) {\n const ed = editor.value\n if (!ed) return\n hideTooltip()\n selectBlocks(ed, range)\n menu.value = { range, anchor }\n setHandleLocked(true)\n}\n\n/** ⋮⋮ click: act on the whole block selection if the block is part of it, else select just this block. */\nfunction openMenu(e: MouseEvent) {\n const ed = editor.value\n if (!ed || !hovered.value) return\n const own = rangeOfBlock({ ...hovered.value, depth: ed.state.doc.resolve(hovered.value.pos).depth })\n const sel = isBlockSelection(ed.state) ? currentRange(ed.state) : null\n const range = sel && own.from >= sel.from && own.to <= sel.to ? sel : own\n showMenu(range, (e.currentTarget as HTMLElement).getBoundingClientRect())\n}\n\n/** ⌘/: open the menu next to the first selected block. */\nfunction openMenuAt(range: BlockRange) {\n const dom = editor.value?.view.nodeDOM(range.from)\n if (!(dom instanceof HTMLElement)) return\n const r = dom.getBoundingClientRect()\n showMenu(range, new DOMRect(r.left, r.top, 0, Math.min(r.height, 24)))\n}\n\n/** Closing keeps the blocks selected (like Notion) so shortcuts keep working. */\nfunction closeMenu() {\n menu.value = null\n setHandleLocked(false)\n editor.value?.view.focus()\n}\n\n// --- Copy link to block ---------------------------------------------------\nconst toast = ref('')\nlet toastTimer: ReturnType<typeof setTimeout> | undefined\nfunction showToast(text: string) {\n toast.value = text\n clearTimeout(toastTimer)\n toastTimer = setTimeout(() => (toast.value = ''), 1800)\n}\nasync function copyLink(id: string) {\n const url = props.blockLink?.(id) ?? `${location.href.split('#')[0]}#${id}`\n try {\n await navigator.clipboard.writeText(url)\n }\n catch {}\n showToast(messages.value.blockMenu.linkCopied)\n}\n\n/** Scroll to and select the block named in the URL hash (target of a copied link). */\nfunction revealHashBlock() {\n const ed = editor.value\n const id = decodeURIComponent(location.hash.slice(1))\n if (!ed || !id) return\n let found: BlockRange | null = null\n ed.state.doc.descendants((node, pos) => {\n if (found) return false\n if (node.attrs.id === id) found = { from: pos, to: pos + node.nodeSize, depth: ed.state.doc.resolve(pos).depth }\n })\n if (!found) return\n selectBlocks(ed, found)\n ;(ed.view.nodeDOM((found as BlockRange).from) as HTMLElement | null)?.scrollIntoView({ block: 'center' })\n}\n\n// --- Handle tooltips --------------------------------------------------------\nconst tooltip = shallowRef<{ lines: [string, string][], hint?: string, rect: DOMRect } | null>(null)\nlet tooltipTimer: ReturnType<typeof setTimeout> | undefined\nfunction showTooltip(e: MouseEvent, kind: 'add' | 'grip') {\n const rect = (e.currentTarget as HTMLElement).getBoundingClientRect()\n const h = messages.value.handle\n const lines: [string, string][] = kind === 'add'\n ? [[h.clickVerb, h.add], [h.altClickVerb, h.addAbove]]\n : [[h.dragVerb, h.drag], [h.clickVerb, h.menu]]\n clearTimeout(tooltipTimer)\n tooltipTimer = setTimeout(() => (tooltip.value = { lines, hint: kind === 'grip' ? kbd('Mod-/') : undefined, rect }), 500)\n}\nfunction hideTooltip() {\n clearTimeout(tooltipTimer)\n tooltip.value = null\n}\n\n/** \"+\" button: add an empty line below the hovered block and open the slash menu. */\nfunction addBlock(e: MouseEvent) {\n const ed = editor.value\n if (!ed || !hovered.value) return\n const { node, pos } = hovered.value\n if (node.type.name === 'paragraph' && node.content.size === 0) {\n ed.chain().focus().setTextSelection(pos + 1).insertContent('/').run()\n return\n }\n // Alt-click inserts above, like Notion.\n const at = e.altKey ? pos : pos + node.nodeSize\n ed.chain()\n .insertContentAt(at, { type: 'paragraph', content: [{ type: 'text', text: '/' }] })\n .setTextSelection(at + 2)\n .focus()\n .run()\n}\n\nfunction focusEnd() {\n const ed = editor.value\n if (!ed || !ed.isEditable) return\n const last = ed.state.doc.lastChild\n if (last?.type.name === 'paragraph' && last.content.size === 0) ed.commands.focus('end')\n else ed.chain().insertContentAt(ed.state.doc.content.size, { type: 'paragraph' }).focus('end').run()\n}\n\nwatch(editor, (ed) => {\n if (!ed) return\n ed.storage.blockSelection.openMenu = openMenuAt\n revealHashBlock()\n}, { immediate: true })\nonMounted(() => window.addEventListener('hashchange', revealHashBlock))\nonBeforeUnmount(() => {\n unmounted = true\n window.removeEventListener('hashchange', revealHashBlock)\n clearTimeout(toastTimer)\n clearTimeout(tooltipTimer)\n editor.value?.destroy()\n})\n</script>\n\n<template>\n <div v-if=\"editor\" ref=\"rootEl\" v-bind=\"scope\" class=\"me-root\">\n <DragHandle\n :editor=\"editor\"\n :nested=\"nestedOptions\"\n :on-node-change=\"onNodeChange\"\n :on-element-drag-start=\"onDragStart\"\n :compute-position-config=\"handlePosition\"\n class=\"me-drag-handle\"\n >\n <div class=\"me-handle\">\n <button type=\"button\" class=\"me-handle-btn\" @click=\"addBlock\" @mouseenter=\"showTooltip($event, 'add')\" @mouseleave=\"hideTooltip\" @mousedown=\"hideTooltip\">\n <Plus />\n </button>\n <button\n type=\"button\"\n class=\"me-handle-btn me-handle-btn--grab\"\n @click=\"openMenu\"\n @mouseenter=\"showTooltip($event, 'grip')\"\n @mouseleave=\"hideTooltip\"\n @mousedown=\"hideTooltip\"\n >\n <GripVertical />\n </button>\n </div>\n </DragHandle>\n\n <!-- Static wrapper: the drag handle plugin moves its own DOM, so conditional siblings need a fixed anchor. -->\n <div class=\"me-content-error-slot\">\n <div v-if=\"contentFailed\" class=\"me-content-error\" role=\"alert\">\n {{ messages.contentError }}\n </div>\n </div>\n <FormatMenu :editor=\"editor\" />\n <EditorContent :editor=\"editor\" />\n <TableControls v-if=\"hasTables && editable\" :editor=\"editor\" />\n <MeiOutline v-if=\"outline\" :editor=\"editor\" :min-headings=\"outlineMin\" :root=\"rootEl\" />\n <div v-if=\"editable\" class=\"me-editor-tail\" @click=\"focusEnd\" />\n\n <BlockMenu\n v-if=\"menu\"\n :editor=\"editor\"\n :range=\"menu.range\"\n :anchor=\"menu.anchor\"\n @close=\"closeMenu\"\n @copy-link=\"copyLink\"\n />\n\n <Teleport to=\"body\">\n <div\n v-if=\"tooltip\"\n v-bind=\"scope\"\n class=\"me-tooltip\"\n :style=\"{ left: `${tooltip.rect.left + tooltip.rect.width / 2}px`, top: `${tooltip.rect.top}px` }\"\n >\n <div v-for=\"[verb, text] in tooltip.lines\" :key=\"verb\">\n <strong class=\"me-tooltip-verb\">{{ verb }}</strong> {{ text }}\n </div>\n <div v-if=\"tooltip.hint\" class=\"me-tooltip-hint\">\n {{ tooltip.hint }}\n </div>\n </div>\n <div v-if=\"toast\" v-bind=\"scope\" class=\"me-toast\">\n {{ toast }}\n </div>\n </Teleport>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport type { AnyExtension } from '@tiptap/core'\nimport { Editor, EditorContent, type EditorOptions, type JSONContent } from '@tiptap/vue-3'\nimport { DragHandle } from '@tiptap/extension-drag-handle-vue-3'\nimport type { NestedOptions } from '@tiptap/extension-drag-handle'\nimport type { Node as PMNode } from '@tiptap/pm/model'\nimport type { ComputePositionConfig, Middleware } from '@floating-ui/dom'\nimport { GripVertical, Plus } from '@lucide/vue'\nimport { computed, inject, onBeforeUnmount, onMounted, ref, shallowRef, toRaw, useId, watch, watchEffect } from 'vue'\nimport type { ImageUploader } from '../config'\nimport { createExtensions } from '../extensions'\nimport type { MeiCollaboration } from '../collaboration'\nimport { type BlockRange, currentRange, isBlockSelection, rangeOfBlock, selectBlocks } from '../block-ops'\nimport { handleAnchorRect } from '../handle-anchor'\nimport { kbd } from '../keys'\nimport { type LocaleName, type PartialMessages, resolveMessages } from '../locale'\nimport { GLOBAL_BLOCKS_KEY, GLOBAL_TOKENS_KEY } from '../plugin-key'\nimport { defaultBlocks, text } from '../blocks'\nimport type { BlockDefinition } from '../define-block'\nimport { ContentError, type ContentIssue, sanitizeContent, unwrapUnknown } from '../content'\nimport { assignIds } from '../extensions/block-id'\nimport { injectStyle, installBaseTokens, overridesCss, type ThemeMode, type ThemeTokens } from '../theme'\nimport BlockMenu from './BlockMenu.vue'\nimport FormatMenu from './FormatMenu.vue'\nimport MeiOutline from './MeiOutline.vue'\nimport TableControls from './TableControls.vue'\n\nconst props = withDefaults(defineProps<{\n /** Document as Tiptap JSON. Use with `v-model`. */\n modelValue?: JSONContent | null\n editable?: boolean\n autofocus?: boolean | 'start' | 'end'\n /** Built-in UI language. */\n locale?: LocaleName\n /** Override any UI string, e.g. `{ placeholder: 'Write…' }`. */\n messages?: PartialMessages\n /**\n * Blocks to load (read once, at mount). Defaults to the app-wide list from the\n * Vue plugin / Nuxt module, else `defaultBlocks`.\n */\n blocks?: BlockDefinition[]\n /** Uploads an image and returns its URL. Without it images are stored as base64. */\n uploadImage?: ImageUploader\n /** Max image size in MB. */\n maxImageSize?: number\n /** Extra Tiptap extensions appended to the built-in ones. */\n extensions?: AnyExtension[]\n /** Light / dark mode. `auto` follows `<html class=\"dark\">`. */\n theme?: ThemeMode\n /** Design token overrides for this editor, e.g. `{ color: { accent: '#7c3aed' } }`. */\n tokens?: ThemeTokens\n /** URL for \"Copy link to block\". Default: current page URL + `#<block id>`. */\n blockLink?: (id: string) => string\n /**\n * Floating outline on the right edge (Notion-style). Shown once the page has\n * `minHeadings` headings (default 2). `false` turns it off.\n */\n outline?: boolean | { minHeadings?: number }\n /**\n * Edit a shared Yjs document (read once, at mount). The `Y.Doc` is the source of truth:\n * `modelValue` is ignored and `update:modelValue` is not emitted — listen to `change`\n * (cheap, no payload to serialize) and read the document yourself when needed.\n * Undo / redo become Yjs undo (only your own changes).\n */\n collaboration?: MeiCollaboration\n}>(), {\n outline: true,\n theme: 'auto',\n modelValue: null,\n editable: true,\n autofocus: false,\n locale: 'vi',\n maxImageSize: 5,\n})\n\nconst emit = defineEmits<{\n /** Document after each change (not emitted in collaboration mode). */\n 'update:modelValue': [content: JSONContent]\n /**\n * Fired on every document change, local or remote, without serializing it. Debounce\n * your own work (saving, title extraction…) and call `editor.getJSON()` when you need it.\n */\n 'change': [info: { editor: Editor }]\n 'ready': [editor: Editor]\n /**\n * Problems found while loading content. `fatal` means the input isn't a document:\n * the editor turns read-only and stops emitting updates so saved data isn't overwritten.\n */\n 'content-error': [info: { fatal: boolean, issues: ContentIssue[], error?: Error }]\n}>()\n\n/** Set when content couldn't be read at all; blocks editing and updates until fixed. */\nconst contentFailed = ref(false)\n\n// Paragraphs (`text`) are always available; other blocks come from props or app config.\nconst globalBlocks = inject(GLOBAL_BLOCKS_KEY, undefined)\nconst blocks = [text, ...(props.blocks ?? globalBlocks ?? defaultBlocks)]\n .filter((b, i, all) => all.findIndex(o => o.name === b.name) === i)\n\nconst rootEl = ref<HTMLElement | null>(null)\nconst outlineMin = computed(() => (typeof props.outline === 'object' ? props.outline.minHeadings ?? 2 : 2))\nconst hasTables = computed(() => !!editor.value?.schema.nodes.table)\n\nconst messages = computed(() => resolveMessages(props.locale, ...blocks.map(b => b.messages?.[props.locale]), props.messages))\n\n// --- Theme ----------------------------------------------------------------\n// Default tokens are injected once; per-editor overrides go in a <style> scoped by id,\n// and the same scope attrs are copied onto popovers rendered in <body>.\ninstallBaseTokens()\nconst instanceId = `me-${useId()}`\nconst globalTokens = inject(GLOBAL_TOKENS_KEY, undefined)\nconst scope = computed(() => ({\n 'class': ['me-scope', props.theme === 'light' ? 'me-light' : props.theme === 'dark' ? 'me-dark' : ''].filter(Boolean),\n 'data-me-id': instanceId,\n}))\nwatchEffect(() => {\n const css = [\n overridesCss(globalTokens?.value, `.me-scope[data-me-id=\"${instanceId}\"]`),\n overridesCss(props.tokens, `.me-scope[data-me-id=\"${instanceId}\"]`),\n ].filter(Boolean).join('\\n')\n injectStyle(`mei-editor-${instanceId}`, css)\n})\nonBeforeUnmount(() => injectStyle(`mei-editor-${instanceId}`, ''))\n\n/**\n * Validates content (repairing or quarantining broken blocks), wraps unknown block\n * types and assigns missing ids. Never yields a blank doc for bad input: on a fatal\n * error the editor goes read-only and keeps the previous content.\n */\nfunction prepare(doc: JSONContent | null | undefined, ed: { schema: Editor['schema'], extensionManager: Editor['extensionManager'] }): JSONContent | null | undefined {\n const types = ed.extensionManager.extensions.find(e => e.name === 'blockId')?.options.types ?? []\n const issues: ContentIssue[] = []\n try {\n const content = assignIds(sanitizeContent(doc, ed.schema, issues), types)\n contentFailed.value = false\n if (issues.some(i => i.kind !== 'unknown')) {\n console.warn('[MeiEditor] Some blocks were repaired or kept as invalid:', issues)\n emit('content-error', { fatal: false, issues })\n }\n return content\n }\n catch (error) {\n contentFailed.value = true\n console.error('[MeiEditor] Content could not be loaded:', error)\n emit('content-error', { fatal: true, issues, error: error instanceof Error ? error : new ContentError(String(error), doc) })\n return undefined\n }\n}\n\n/** Loads content unless it is unreadable (then the current doc stays, read-only). */\nfunction load(ed: Editor, doc: JSONContent | null | undefined) {\n const content = prepare(doc, ed)\n if (content !== undefined) ed.commands.setContent(content ?? '', { emitUpdate: false })\n ed.setEditable(props.editable && !contentFailed.value)\n}\n\n// The last value we emitted, so an echoed v-model update doesn't reset the doc.\nlet lastEmitted: JSONContent | null = null\n\n// Read once, like `blocks`. With it the Y.Doc owns the content: never setContent / v-model.\nconst collaboration = props.collaboration ? toRaw(props.collaboration) : undefined\n\nconst editor = shallowRef<Editor>()\nlet unmounted = false\n\nfunction createEditor(extra: AnyExtension[]) {\n const options: Partial<EditorOptions> = {\n extensions: [\n ...createExtensions({\n blocks,\n messages: messages.value,\n locale: props.locale,\n uploadImage: props.uploadImage ?? null,\n maxImageSize: props.maxImageSize,\n scope: scope.value,\n // Collaboration brings Yjs undo (Mod-z / Mod-Shift-z); two histories would fight.\n undoRedo: !collaboration,\n }),\n ...extra,\n ...(props.extensions ?? []),\n ],\n content: null,\n editable: props.editable,\n autofocus: props.autofocus,\n editorProps: {\n attributes: { class: 'me-content', spellcheck: 'false' },\n },\n onCreate: ({ editor }) => {\n // Load content after the schema exists, so unknown block types can be wrapped.\n if (!collaboration) load(editor as Editor, toRaw(props.modelValue))\n emit('ready', editor as Editor)\n },\n onUpdate: ({ editor }) => {\n if (contentFailed.value) return\n emit('change', { editor: editor as Editor })\n // getJSON() is O(document): skip it when nobody needs the JSON (collaboration).\n if (collaboration) return\n lastEmitted = unwrapUnknown(editor.getJSON())\n emit('update:modelValue', lastEmitted)\n },\n }\n editor.value = new Editor(options)\n}\n\nonMounted(() => {\n if (!collaboration) {\n createEditor([])\n return\n }\n // Yjs + the sync plugin load only for collaborative editors.\n import('../collaboration').then(({ collaborationExtensions }) => {\n if (!unmounted) createEditor(collaborationExtensions(collaboration))\n }).catch(error => console.error('[MeiEditor] Collaboration could not be loaded:', error))\n})\n\n// Only reload the document for real external changes. `v-model` on a `ref()` hands\n// back a reactive proxy of what we emitted, so compare the raw object, then content.\nwatch(() => props.modelValue, (value) => {\n const ed = editor.value\n const raw = value ? toRaw(value) : null\n if (!ed || collaboration || raw === lastEmitted) return\n if (raw && JSON.stringify(raw) === JSON.stringify(unwrapUnknown(ed.getJSON()))) return\n load(ed, raw)\n})\nwatch(() => props.editable, value => editor.value?.setEditable(value && !contentFailed.value))\nwatch([messages, () => props.locale, () => props.uploadImage, () => props.maxImageSize, scope], () => {\n const config = editor.value?.storage.meiConfig\n if (!config) return\n config.messages = messages.value\n config.locale = props.locale\n config.uploadImage = props.uploadImage ?? null\n config.maxImageSize = props.maxImageSize\n config.scope = scope.value\n})\n\ndefineExpose({ editor })\n\n// --- Drag handle + block menu -------------------------------------------\n// Show the handle for top-level blocks and for blocks directly inside a column\n// (not for list items, table cells, callout children...). On ties the deeper\n// node wins, so inside a column you grab the block, not the whole columns row.\nconst nestedOptions: NestedOptions = {\n defaultRules: false,\n edgeDetection: 'none',\n rules: [{\n id: 'blockLevelOnly',\n evaluate: ({ node, parent }) => {\n if (!parent || node.type.name === 'column') return 1000\n return ['doc', 'column'].includes(parent.type.name) ? 0 : 1000\n },\n }],\n}\n\ninterface HoveredBlock { node: PMNode, pos: number }\nconst hovered = shallowRef<HoveredBlock | null>(null)\nconst menu = shallowRef<{ range: BlockRange, anchor: DOMRect } | null>(null)\n\n// Block under the pointer, for placing the handle (tracked even while a menu is open).\nlet handlePos: number | null = null\n\nfunction onNodeChange({ node, pos }: { node: PMNode | null, pos: number }) {\n handlePos = node ? pos : null\n if (menu.value) return\n hovered.value = node ? { node, pos } : null\n}\n\n/**\n * Centers the handle on the block's anchor line (first text line, header bar, divider…)\n * instead of aligning tops, so it lines up the same way for every block type.\n */\nconst alignHandleToLine: Middleware = {\n name: 'meAlignToLine',\n fn({ y, rects }) {\n const ed = editor.value\n const dom = ed && handlePos !== null ? ed.view.nodeDOM(handlePos) : null\n if (!(dom instanceof HTMLElement)) return {}\n const anchor = handleAnchorRect(dom)\n // Work in the reference's own coordinates: shift by the anchor's offset from the block's top.\n const offset = anchor.top + anchor.height / 2 - dom.getBoundingClientRect().top\n return { y: Number.isFinite(offset) ? rects.reference.y + offset - rects.floating.height / 2 : y }\n },\n}\nconst handlePosition: Partial<ComputePositionConfig> = { placement: 'left-start', strategy: 'absolute', middleware: [alignHandleToLine] }\n\n// Lets the BlockDrop extension take over the drop (see block-drop.ts).\nfunction onDragStart() {\n const config = editor.value?.storage.blockDrop\n if (config) config.active = true\n}\n\nfunction setHandleLocked(locked: boolean) {\n const ed = editor.value\n if (ed && !ed.isDestroyed) ed.view.dispatch(ed.state.tr.setMeta('lockDragHandle', locked))\n}\n\nfunction showMenu(range: BlockRange, anchor: DOMRect) {\n const ed = editor.value\n if (!ed) return\n hideTooltip()\n selectBlocks(ed, range)\n menu.value = { range, anchor }\n setHandleLocked(true)\n}\n\n/** ⋮⋮ click: act on the whole block selection if the block is part of it, else select just this block. */\nfunction openMenu(e: MouseEvent) {\n const ed = editor.value\n if (!ed || !hovered.value) return\n const own = rangeOfBlock({ ...hovered.value, depth: ed.state.doc.resolve(hovered.value.pos).depth })\n const sel = isBlockSelection(ed.state) ? currentRange(ed.state) : null\n const range = sel && own.from >= sel.from && own.to <= sel.to ? sel : own\n showMenu(range, (e.currentTarget as HTMLElement).getBoundingClientRect())\n}\n\n/** ⌘/: open the menu next to the first selected block. */\nfunction openMenuAt(range: BlockRange) {\n const dom = editor.value?.view.nodeDOM(range.from)\n if (!(dom instanceof HTMLElement)) return\n const r = dom.getBoundingClientRect()\n showMenu(range, new DOMRect(r.left, r.top, 0, Math.min(r.height, 24)))\n}\n\n/** Closing keeps the blocks selected (like Notion) so shortcuts keep working. */\nfunction closeMenu() {\n menu.value = null\n setHandleLocked(false)\n editor.value?.view.focus()\n}\n\n// --- Copy link to block ---------------------------------------------------\nconst toast = ref('')\nlet toastTimer: ReturnType<typeof setTimeout> | undefined\nfunction showToast(text: string) {\n toast.value = text\n clearTimeout(toastTimer)\n toastTimer = setTimeout(() => (toast.value = ''), 1800)\n}\nasync function copyLink(id: string) {\n const url = props.blockLink?.(id) ?? `${location.href.split('#')[0]}#${id}`\n try {\n await navigator.clipboard.writeText(url)\n }\n catch {}\n showToast(messages.value.blockMenu.linkCopied)\n}\n\n/** Scroll to and select the block named in the URL hash (target of a copied link). */\nfunction revealHashBlock() {\n const ed = editor.value\n const id = decodeURIComponent(location.hash.slice(1))\n if (!ed || !id) return\n let found: BlockRange | null = null\n ed.state.doc.descendants((node, pos) => {\n if (found) return false\n if (node.attrs.id === id) found = { from: pos, to: pos + node.nodeSize, depth: ed.state.doc.resolve(pos).depth }\n })\n if (!found) return\n selectBlocks(ed, found)\n ;(ed.view.nodeDOM((found as BlockRange).from) as HTMLElement | null)?.scrollIntoView({ block: 'center' })\n}\n\n// --- Handle tooltips --------------------------------------------------------\nconst tooltip = shallowRef<{ lines: [string, string][], hint?: string, rect: DOMRect } | null>(null)\nlet tooltipTimer: ReturnType<typeof setTimeout> | undefined\nfunction showTooltip(e: MouseEvent, kind: 'add' | 'grip') {\n const rect = (e.currentTarget as HTMLElement).getBoundingClientRect()\n const h = messages.value.handle\n const lines: [string, string][] = kind === 'add'\n ? [[h.clickVerb, h.add], [h.altClickVerb, h.addAbove]]\n : [[h.dragVerb, h.drag], [h.clickVerb, h.menu]]\n clearTimeout(tooltipTimer)\n tooltipTimer = setTimeout(() => (tooltip.value = { lines, hint: kind === 'grip' ? kbd('Mod-/') : undefined, rect }), 500)\n}\nfunction hideTooltip() {\n clearTimeout(tooltipTimer)\n tooltip.value = null\n}\n\n/** \"+\" button: add an empty line below the hovered block and open the slash menu. */\nfunction addBlock(e: MouseEvent) {\n const ed = editor.value\n if (!ed || !hovered.value) return\n const { node, pos } = hovered.value\n if (node.type.name === 'paragraph' && node.content.size === 0) {\n ed.chain().focus().setTextSelection(pos + 1).insertContent('/').run()\n return\n }\n // Alt-click inserts above, like Notion.\n const at = e.altKey ? pos : pos + node.nodeSize\n ed.chain()\n .insertContentAt(at, { type: 'paragraph', content: [{ type: 'text', text: '/' }] })\n .setTextSelection(at + 2)\n .focus()\n .run()\n}\n\nfunction focusEnd() {\n const ed = editor.value\n if (!ed || !ed.isEditable) return\n const last = ed.state.doc.lastChild\n if (last?.type.name === 'paragraph' && last.content.size === 0) ed.commands.focus('end')\n else ed.chain().insertContentAt(ed.state.doc.content.size, { type: 'paragraph' }).focus('end').run()\n}\n\nwatch(editor, (ed) => {\n if (!ed) return\n ed.storage.blockSelection.openMenu = openMenuAt\n revealHashBlock()\n}, { immediate: true })\nonMounted(() => window.addEventListener('hashchange', revealHashBlock))\nonBeforeUnmount(() => {\n unmounted = true\n window.removeEventListener('hashchange', revealHashBlock)\n clearTimeout(toastTimer)\n clearTimeout(tooltipTimer)\n editor.value?.destroy()\n})\n</script>\n\n<template>\n <div v-if=\"editor\" ref=\"rootEl\" v-bind=\"scope\" class=\"me-root\">\n <DragHandle\n :editor=\"editor\"\n :nested=\"nestedOptions\"\n :on-node-change=\"onNodeChange\"\n :on-element-drag-start=\"onDragStart\"\n :compute-position-config=\"handlePosition\"\n class=\"me-drag-handle\"\n >\n <div class=\"me-handle\">\n <button type=\"button\" class=\"me-handle-btn\" @click=\"addBlock\" @mouseenter=\"showTooltip($event, 'add')\" @mouseleave=\"hideTooltip\" @mousedown=\"hideTooltip\">\n <Plus />\n </button>\n <button\n type=\"button\"\n class=\"me-handle-btn me-handle-btn--grab\"\n @click=\"openMenu\"\n @mouseenter=\"showTooltip($event, 'grip')\"\n @mouseleave=\"hideTooltip\"\n @mousedown=\"hideTooltip\"\n >\n <GripVertical />\n </button>\n </div>\n </DragHandle>\n\n <!-- Static wrapper: the drag handle plugin moves its own DOM, so conditional siblings need a fixed anchor. -->\n <div class=\"me-content-error-slot\">\n <div v-if=\"contentFailed\" class=\"me-content-error\" role=\"alert\">\n {{ messages.contentError }}\n </div>\n </div>\n <FormatMenu :editor=\"editor\" />\n <EditorContent :editor=\"editor\" />\n <TableControls v-if=\"hasTables && editable\" :editor=\"editor\" />\n <MeiOutline v-if=\"outline\" :editor=\"editor\" :min-headings=\"outlineMin\" :root=\"rootEl\" />\n <div v-if=\"editable\" class=\"me-editor-tail\" @click=\"focusEnd\" />\n\n <BlockMenu\n v-if=\"menu\"\n :editor=\"editor\"\n :range=\"menu.range\"\n :anchor=\"menu.anchor\"\n @close=\"closeMenu\"\n @copy-link=\"copyLink\"\n />\n\n <Teleport to=\"body\">\n <div\n v-if=\"tooltip\"\n v-bind=\"scope\"\n class=\"me-tooltip\"\n :style=\"{ left: `${tooltip.rect.left + tooltip.rect.width / 2}px`, top: `${tooltip.rect.top}px` }\"\n >\n <div v-for=\"[verb, text] in tooltip.lines\" :key=\"verb\">\n <strong class=\"me-tooltip-verb\">{{ verb }}</strong> {{ text }}\n </div>\n <div v-if=\"tooltip.hint\" class=\"me-tooltip-hint\">\n {{ tooltip.hint }}\n </div>\n </div>\n <div v-if=\"toast\" v-bind=\"scope\" class=\"me-toast\">\n {{ toast }}\n </div>\n </Teleport>\n </div>\n</template>\n","import { type App, type Plugin, ref } from 'vue'\nimport MeiEditor from './components/MeiEditor.vue'\nimport type { BlockDefinition } from './define-block'\nimport { GLOBAL_BLOCKS_KEY, GLOBAL_TOKENS_KEY } from './plugin-key'\nimport type { ThemeTokens } from './theme/tokens'\n\nexport interface MeiEditorPluginOptions {\n /** Global component name. */\n componentName?: string\n /** Token overrides applied to every editor in the app. */\n tokens?: ThemeTokens\n /** Blocks loaded by every editor that has no `blocks` prop. */\n blocks?: BlockDefinition[]\n /** Register <MeiEditor> globally (set false when the Nuxt module already does). */\n component?: boolean\n}\n\n/**\n * Vue plugin that registers <MeiEditor> globally and sets app-wide tokens.\n *\n * @example\n * app.use(MeiEditorPlugin, { tokens: { color: { accent: '#7c3aed' } } })\n */\nexport const MeiEditorPlugin: Plugin<[MeiEditorPluginOptions?]> = {\n install(app: App, options: MeiEditorPluginOptions = {}) {\n if (options.component !== false) app.component(options.componentName ?? 'MeiEditor', MeiEditor)\n app.provide(GLOBAL_TOKENS_KEY, ref(options.tokens))\n if (options.blocks) app.provide(GLOBAL_BLOCKS_KEY, options.blocks)\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,IAAagmB,KAAYC,GAAU,OAAoD;CACrF,MAAM;CAGN,aAAa;EACX,OAAOC,GAAgB;GACrB,UAAU,KAAK,QAAQ,YAAYvC;GACnC,QAAQ,KAAK,QAAQ,UAAU;GAC/B,OAAO,KAAK,QAAQ,SAAS,CAAC;GAC9B,eAAe,KAAK,QAAQ,iBAAiB,CAAC;GAC9C,aAAa,KAAK,QAAQ,eAAe;GACzC,cAAc,KAAK,QAAQ,gBAAgB;GAC3C,OAAO,KAAK,QAAQ,SAAS;IAAEwC,OAAS,CAAC,UAAU;IAAG,cAAc;GAAG;EACzE,CAAC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AQ,KAAK,OAAOA,GAAA,MAAQ,KAAK,QAAK,EAAA;KAAA,KAAA,GAAkBA,GAAA,MAAQ,KAAK,IAAG;IAAA;G,MAE3FnyC,EAAA,EAAA,GAAAC,EAEMc,GAAA,MAAAC,EAFsBmxC,GAAA,MAAQ,QAAK,CAA5BO,GAAMp/B,QAAnBtT,EAAA,GAAAC,EAEM,OAAA,EAFsC,KAAKyyC,EAAI,GAAA,CACnDpyC,EAAmD,UAAnDqvC,IAAmDpvC,EAAhBmyC,CAAI,GAAA,CAAA,GAAYzxC,EAAA,MAACV,EAAG+S,CAAI,GAAA,CAAA,C,aAElD6+B,GAAA,MAAQ,QAAnBnyC,EAAA,GAAAC,EAEM,OAFN2vC,IAEMrvC,EADD4xC,GAAA,MAAQ,IAAI,GAAA,CAAA,K,8BAGRJ,GAAA,SAAX/xC,EAAA,GAAAC,EAEM,OAFNC,EAEM,EAAA,KAAA,EAAA,GAFoBoK,EAAA,OAAK,EAAE,OAAM,WAAU,CAAA,GAAA/J,EAC5CwxC,GAAA,KAAK,GAAA,EAAA,K;;;A,IE3cHY,KAAqD,EAChE,QAAQ,GAAU,IAAkC,CAAC,GAAG;CAGtD,AAFIzuC,EAAQ,cAAc,MAAO0uC,EAAI,UAAU1uC,EAAQ,iBAAiB,aAAa/C,EAAS,GAC9FyxC,EAAI,QAAQ7zB,IAAmB1F,EAAInV,EAAQ,MAAM,CAAC,GAC9CA,EAAQ,UAAQ0uC,EAAI,QAAQ5zB,IAAmB9a,EAAQ,MAAM;AACnE,EACF"}
1
+ {"version":3,"file":"index.js","names":["Fragment","normalize","Fragment","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","_hoisted_9","_openBlock","_createElementBlock","_mergeProps","_unref","_Fragment","_renderList","_createElementVNode","_toDisplayString","_normalizeClass","_withModifiers","_createBlock","_resolveDynamicComponent","_createCommentVNode","_sfc_main","MAX","normalize","SlashMenu","node","updateAttributes","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","_openBlock","_createBlock","_unref","_withCtx","_createElementVNode","_normalizeStyle","_toDisplayString","_createElementBlock","_Fragment","_renderList","_normalizeClass","_createCommentVNode","_createVNode","_sfc_main","CalloutView","_hoisted_1","_hoisted_2","_hoisted_3","_openBlock","_createElementBlock","_createCommentVNode","_toDisplayString","_sfc_main","node","updateAttributes","editor","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_openBlock","_createBlock","_unref","_withCtx","_createElementVNode","_createElementBlock","_Fragment","_renderList","_toDisplayString","_createVNode","_resolveDynamicComponent","_createTextVNode","_normalizeClass","MermaidDiagram","_createCommentVNode","_sfc_main","ALIASES","CodeBlockView","selected","node","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_openBlock","_createBlock","_unref","_normalizeClass","_withCtx","_createElementBlock","_withModifiers","_createElementVNode","_toDisplayString","_withDirectives","_vModelText","_createCommentVNode","_sfc_main","EmbedView","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","MIN","_openBlock","_createElementBlock","_createElementVNode","_normalizeStyle","_Fragment","_renderList","_toDisplayString","_sfc_main","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_openBlock","_createBlock","_Teleport","_createElementVNode","_mergeProps","_withModifiers","_normalizeClass","_normalizeStyle","_createVNode","_unref","_toDisplayString","_sfc_main","node","deleteNode","editor","selected","updateAttributes","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","_hoisted_9","_hoisted_10","_hoisted_11","_hoisted_12","_hoisted_13","_hoisted_14","_hoisted_15","_hoisted_16","_hoisted_17","_hoisted_18","_hoisted_19","_hoisted_20","_hoisted_21","_hoisted_22","_hoisted_23","_hoisted_24","_hoisted_25","_hoisted_26","_hoisted_27","_hoisted_28","_hoisted_29","_hoisted_30","_openBlock","_createBlock","_unref","_normalizeClass","_withCtx","_createElementBlock","_createCommentVNode","_createElementVNode","_Fragment","_toDisplayString","_createVNode","_createTextVNode","_normalizeStyle","_withModifiers","_renderList","_resolveDynamicComponent","LinkIcon","ImageIcon","_withDirectives","_vModelText","ImageCropper","ImageLightbox","_sfc_main","Image","ImageView","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_openBlock","_createElementBlock","_mergeProps","_unref","_createElementVNode","_Fragment","_renderList","_normalizeClass","_withModifiers","_toDisplayString","_sfc_main","EmojiMenu","node","selected","deleteNode","editor","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","_hoisted_9","_hoisted_10","_hoisted_11","_hoisted_12","_hoisted_13","_hoisted_14","_hoisted_15","_hoisted_16","_hoisted_17","_hoisted_18","_hoisted_19","_hoisted_20","_hoisted_21","FileIcon","_openBlock","_createBlock","_unref","_normalizeClass","_withCtx","_createElementBlock","_createElementVNode","_resolveDynamicComponent","_toDisplayString","_createCommentVNode","_Fragment","_createVNode","_createTextVNode","_normalizeStyle","_withModifiers","_renderList","LinkIcon","_withDirectives","_vModelText","_sfc_main","FileView","selected","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","_hoisted_9","_hoisted_10","_hoisted_11","_hoisted_12","_hoisted_13","_hoisted_14","_hoisted_15","_hoisted_16","_hoisted_17","_hoisted_18","_hoisted_19","_hoisted_20","_openBlock","_createBlock","_unref","_normalizeClass","_withCtx","_createElementVNode","_createVNode","_toDisplayString","_createElementBlock","_createTextVNode","_createCommentVNode","_normalizeStyle","_withDirectives","_vModelText","_Teleport","_mergeProps","_withModifiers","_sfc_main","HtmlView","selected","node","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_openBlock","_createBlock","_unref","_normalizeClass","_withCtx","_createElementBlock","_toDisplayString","_createCommentVNode","_withDirectives","_createElementVNode","_vModelText","_sfc_main","MathView","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","_openBlock","_createElementBlock","_mergeProps","_unref","_Fragment","_renderList","_createElementVNode","_toDisplayString","_normalizeClass","_withModifiers","_createBlock","_resolveDynamicComponent","_createCommentVNode","_sfc_main","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","_hoisted_9","_hoisted_10","_hoisted_11","_hoisted_12","_hoisted_13","_hoisted_14","_hoisted_15","_hoisted_16","_hoisted_17","_hoisted_18","_hoisted_19","_hoisted_20","_hoisted_21","_openBlock","_createElementBlock","_createElementVNode","_normalizeClass","_withDirectives","_withKeys","_withModifiers","_vModelText","_createCommentVNode","_toDisplayString","_createVNode","_unref","_Fragment","_renderList","_createBlock","_sfc_main","selected","node","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","_hoisted_9","_hoisted_10","_hoisted_11","_hoisted_12","_hoisted_13","_hoisted_14","_openBlock","_createBlock","_unref","_withCtx","_createElementVNode","_normalizeClass","_createElementBlock","_createCommentVNode","_toDisplayString","_Teleport","_mergeProps","_withModifiers","DatePicker","_Fragment","_withDirectives","_vModelText","_renderList","_resolveDynamicComponent","_createVNode","_sfc_main","MentionView","MentionMenu","selected","_hoisted_1","_hoisted_2","_openBlock","_createBlock","_unref","_normalizeClass","_withCtx","_createElementBlock","_Fragment","_renderList","_toDisplayString","_createCommentVNode","_sfc_main","TocView","TocNode","TableOfContents","$emit","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_openBlock","_createElementBlock","_Fragment","_renderList","_toDisplayString","_createCommentVNode","_createElementVNode","_normalizeClass","_createBlock","_unref","_sfc_main","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","_hoisted_9","_hoisted_10","_hoisted_11","_hoisted_12","_hoisted_13","_hoisted_14","_hoisted_15","_openBlock","_createBlock","_Teleport","_createElementVNode","_mergeProps","_unref","_createVNode","_withDirectives","_vModelText","_createElementBlock","_toDisplayString","_createCommentVNode","_normalizeClass","_Fragment","_renderList","_withModifiers","_resolveDynamicComponent","ColorList","_sfc_main","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_hoisted_6","_hoisted_7","_hoisted_8","_hoisted_9","_hoisted_10","_hoisted_11","_hoisted_12","_hoisted_13","_openBlock","_createBlock","_unref","_withCtx","_createElementVNode","_mergeProps","_createElementBlock","_Fragment","_renderList","_resolveDynamicComponent","_createTextVNode","_toDisplayString","_createVNode","_createCommentVNode","_normalizeClass","_withModifiers","_withDirectives","_withKeys","_vModelText","ColorList","_sfc_main","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_openBlock","_createBlock","_Teleport","_createElementBlock","_mergeProps","_unref","_createElementVNode","_normalizeClass","_Fragment","_renderList","_toDisplayString","_createCommentVNode","_sfc_main","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","_openBlock","_createElementBlock","_Fragment","_createElementVNode","_normalizeStyle","_withModifiers","_createVNode","_unref","_createCommentVNode","_mergeProps","_renderList","_normalizeClass","_createBlock","_resolveDynamicComponent","_toDisplayString","_createTextVNode","_sfc_main","_openBlock","_createElementBlock","_mergeProps","_createVNode","_unref","_withCtx","_createElementVNode","_toDisplayString","_createCommentVNode","FormatMenu","_createBlock","TableControls","MeiOutline","BlockMenu","_Teleport","_Fragment","_renderList","_createTextVNode","_sfc_main","MeiEditor","en","formatDateValue","vi","parseDateInput","reminderTime","HTML_MAX_HEIGHT","LANGUAGE_ALIASES","toEmbedUrl","formatDate","htmlBlockDocument","REMINDERS_DATE","formatTime","REMINDERS_TIME","isoDate","DATE_FORMATS","parseTimeInput","zh","resolveMessages","overridesCss","component","semanticLight","cssVar","installBaseTokens","primitive","baseTokensCss","injectStyle","PALETTE_NAMES","semanticDark","BLOCK_NAMES","TableOfContents$1","StarterKit","Fragment$1","Suggestion","CodeBlockLowlight","Heading","Blockquote","HorizontalRule","Image$1","Mention","MeiConfig","Extension","shallowReactive","\"class\"","defineBlock","build","spec","options","overrides","collectExtensions","seen","blocks","b","ext","CONTAINERS","blockAt","d","$pos","node","after","rangeOfBlock","block","rangeBetween","ba","doc","a","bb","top","$p","pos","ta","tb","isBlockSelection","state","NodeRangeSelection","currentRange","sel","blocksIn","out","range","setBlockSelection","tr","selectBlocks","editor","dissolveEmptyColumn","columnDepth","column","columns","columnsPos","rest","c","replacement","reselect","wasBlocks","next","TextSelection","caret","oldFrom","deleteBlocks","duplicateBlocks","slice","moveBlocks","$from","parent","startIndex","endIndex","insertAt","dir","selectText","from","to","turnBlocksInto","chain","summary","content","paragraph","fragment","colorBlocks","attr","kind","mark","value","color","end","rangeColors","found","any","add","fromBlocks","marks","m","single","s","SIDE_ZONE","LEFT_ZONE","LEFT_INTENT","NEST_INDENT","SCROLL_ZONE","SCROLL_SPEED","NESTABLE","blockDropKey","PluginKey","rectOf","dom","view","blockAtPoint","container","containerPos","start","containers","x","y","hit","last","offset","rect","child","blockGapAtPoint","at","BlockDrop","storage","indicator","hide","show","scope","indicatorClass","line","draggingColumns","n","dragStartX","findDropTarget","isSelf","selection","rightZone","leftIntent","side","vertical","edgeX","r","colRect","maxColumns","before","isNearEditor","e","moveBlock","target","schema","dragged","existing","moved","NodeSelection","scrollFrame","scrollSpeed","scroller","el","overflowY","stopScroll","updateScroll","bounds","fromTop","fromBottom","step","Plugin","onDragOver","onDrop","onDragEnd","BULK_THRESHOLD","uuid","assignIds","typeSet","types","visit","id","generate","rebuild","children","ids","attrs","BlockId","name","transactions","transform","combineTransactionSteps","oldState","candidates","getChangedRanges","newRange","needsCheck","counts","newState","inCandidates","updates","kept","usedElsewhere","repeated","anchor","Selection","enabledBlocks","isNode","turnIntoBlocks","blockTitle","messages","groupLabel","group","normalize$2","filterBlocks","q","query","score","terms","t","w","TURN_INTO_SHORTCUTS","blockSelectionKey","BlockSelection","suggestionOpen","st","p","withRange","fn","shortcuts","\"Escape\"","key","dragging","DecorationSet","Decoration","event","up","head","$edge","sibling","siblingPos","onMouseUp","DISPLAYABLE_IMAGES","MB","UPLOAD_STALE_MS","uploadState","pendingUpload","now","uploadStaleAt","started","firstSeen","readAsDataUrl","reader","resolve","reject","file","kindOf","mime","fileBlockOptions","findUpload","uploadId","adrift","collaborationFragment","UPLOAD_ORIGIN","writeToDocument","isUpload","element","apply","setUploadAttrs","dropEntry","uploads","entry","docRuns","docOf","uploadsSettled","runs","run","runUpload","running","current","onDoc","upload","finish","isImage","config","fileOptions","maxMb","onProgress","fraction","src","placeholders","nodes","files","type","preview","reactive","startAll","filesOf","data","i","f","htmlHasContent","html","img","LOCAL_IMG","insertsUpload","steps","ReplaceStep","ReplaceAroundStep","isSyncTransaction","meta","isAccepted","FileDrop","wordImages","insert","Slice","dropPoint","trs","images","nonce","marked","prefix","swap","placeholder","coords","safeUrl","url","scheme","isSameOrigin","base","isWebUrl","MAX_DEPTH","isSpace","isDigit","indentOf","indent","headingText","hashes","listItem","ordered","digits","task","text","classify","info","space","level","only","item","splitLines","closesFence","open","looksLikeMarkdown","openFence","previousList","raw","OPEN_AFTER","CLOSE_BEFORE","ESCAPABLE","isWs","isWord","EMPHASIS","finder","cached","needle","valid","urlEnd","parseInline","buf","flush","closer","len","inLink","close","paren","inside","title","href","depth","delimiter","inner","j","buildList","root","stack","items","list","unquote","all","markdownToBlocks","lines","markdown","kinds","body","quoted","flatten","l","following","k","fitToSchema","map","textOf","parts","MarkdownPaste","input","error","placeholderPluginKey","Placeholder","$anchor","isDefault","TextColor","Mark","mergeAttributes","HTMLAttributes","commands","BgColor","COLORABLE_BLOCKS","BlockColor","useScope","computed","usePointerMoved","_hoisted_1$21","_hoisted_2$21","_hoisted_3$20","_hoisted_4$19","_hoisted_5$15","_hoisted_6$12","_hoisted_7$11","_hoisted_8$10","_hoisted_9$8","SlashMenu_default","defineComponent","__expose","props","__props","selected","ref","listEl","groups","watch","nextTick","select","index","onKeyDown","pointerMoved","openBlock","createElementBlock","mergeProps","unref","Fragment","renderList","entries","createElementVNode","toDisplayString","normalizeClass","$event","withModifiers","createBlock","resolveDynamicComponent","createCommentVNode","KEY","MAX$1","load","recent","save","pushRecentColor","pushRecentBlock","normalize$1","blockItem","ed","listItemRange","colorItems","slashItems","recentItems","rank","readTokenPx","fallback","probe","path","px","suggestionRenderer","renderer","cleanup","position","reference","gap","autoUpdate","flip","shift","hooks","VueRenderer","exitSuggestion","pluginKey","slashPluginKey","SlashCommand","lastMatch","Node","inline","UnknownBlock","UnknownInline","createExtensions","undoRedo","handleAnchorRect","box","lineHeight","lineHeightOf","center","bar","firstTextRect","padTop","inUi","ui","findTextRect","walker","accept","style","lh","isMac","MAC","PC","kbd","shortcut","isMod","GLOBAL_TOKENS_KEY","GLOBAL_BLOCKS_KEY","blockNodeView","render","VueNodeViewRenderer","stop","original","fast","useEditable","editable","sync","onBeforeUnmount","readonly","useClickOutside","listener","active","handler","onMounted","_hoisted_1$20","_hoisted_2$20","_hoisted_3$19","_hoisted_4$18","_hoisted_5$14","_hoisted_6$11","_hoisted_7$10","_hoisted_8$9","CalloutView_default","nodeViewProps","ICONS","pickerEl","iconEl","iconOffset","alignIcon","first","observer","NodeViewWrapper","_ctx","withCtx","normalizeStyle","_cache","icon","createVNode","NodeViewContent","Callout","katexPromise","loadKatex","mermaidPromise","loadMermaid","_hoisted_1$19","_hoisted_2$19","_hoisted_3$18","counter","nextId","MermaidDiagram_default","svg","timer","latest","mermaid","result","leftover","label","_hoisted_1$18","_hoisted_2$18","_hoisted_3$17","_hoisted_4$17","CodeBlockView_default","hasMermaid","languages","CODE_LANGUAGES","copied","showDiagram","isDark","copy","lang","ChevronDown","Check","Copy","createTextVNode","lowlight","createLowlight","LOADERS","pending","loadLanguage","language","mod","refresh","indentCode","$to","empty","direction","lead","CodeBlock","\"Tab\"","requested","check","added","v","prev","Column","Columns","count","colorAttr","ColoredCell","TableCell","ColoredHeader","TableHeader","tableExtensions","TableKit","ToggleDetails","Details","upstreamUpdate","openPending","ok","toggleExtensions","DetailsSummary","DetailsContent","codeBlock","Code","callout","Lightbulb","toggle","ListCollapse","setToggleLevel","TOGGLE_HEADING_ICONS","Heading1","Heading2","Heading3","toggleHeading","table","Table","COLUMN_ICONS","Columns2","Columns3","Columns4","Type","wrapper","HEADING_ICONS","Heading4","heading","o","bulletList","BulletList","ListItem","ListKeymap","List","orderedList","OrderedList","ListOrdered","taskList","TaskList","TaskItem","ListTodo","quote","Quote","divider","Minus","_hoisted_1$17","_hoisted_2$17","_hoisted_3$16","_hoisted_4$16","_hoisted_5$13","_hoisted_6$10","_hoisted_7$9","EmbedView_default","link","resizing","safeSrc","submit","startResize","startY","startH","move","ev","withDirectives","vModelText","Embed","_hoisted_1$16","_hoisted_2$16","_hoisted_3$15","_hoisted_4$15","_hoisted_5$12","MIN$1","ImageCropper_default","__emit","emit","stage","HANDLES","clamp","hi","lo","sx","sy","dx","dy","handle","done","full","h","natural","ratio","reset","onKey","pct","_hoisted_1$15","_hoisted_2$15","_hoisted_3$14","_hoisted_4$14","_hoisted_5$11","_hoisted_6$9","MIN","MAX","ImageLightbox_default","zoom","pan","percent","setZoom","zoomIn","zoomOut","onWheel","drag","onPointerDown","onPointerMove","onPointerUp","Teleport","Plus","Download","X","useUploadState","watchEffect","_hoisted_1$14","_hoisted_2$14","_hoisted_3$13","_hoisted_4$13","_hoisted_5$10","_hoisted_6$8","_hoisted_7$8","_hoisted_8$8","_hoisted_9$7","_hoisted_10$7","_hoisted_11$7","_hoisted_12$7","_hoisted_13$7","_hoisted_14$6","_hoisted_15$5","_hoisted_16$4","_hoisted_17$4","_hoisted_18$4","_hoisted_19$4","_hoisted_20$4","_hoisted_21$3","_hoisted_22$1","_hoisted_23$1","_hoisted_24$1","_hoisted_25$1","_hoisted_26$1","_hoisted_27$1","_hoisted_28$1","_hoisted_29$1","_hoisted_30$1","_hoisted_31","_hoisted_32","_hoisted_33","_hoisted_34","_hoisted_35","_hoisted_36","_hoisted_37","ImageView_default","tab","uploading","fileInput","figure","uploadError","isPending","progress","uploadErrorText","handleFile","onFileChange","submitLink","startX","startWidth","total","factor","align","delta","ALIGN_ICONS","AlignLeft","AlignCenter","AlignRight","crop","captionShown","isWeb","isRemote","menu","toolbar","captionInput","cropping","viewing","setAlign","toggleCaption","finishCrop","download","blob","objectUrl","copyLink","replace","openOriginal","remove","cropStyle","Trash","RefreshCw","Captions","Crop","ZoomIn","Ellipsis","ExternalLink","Upload","Link","Image","uploadAttributes","ImageBlock","image","embed","Video","_hoisted_1$13","_hoisted_2$13","_hoisted_3$12","_hoisted_4$12","COLS","EmojiMenu_default","normalize","LOCALES","cache","cachedLocale","loadEmojis","locale","shortcodes","local","localByHex","codes","loc","sc","searchEmojis","limit","starts","contains","emojiPluginKey","EmojiSuggestion","_hoisted_1$12","_hoisted_2$12","_hoisted_3$11","_hoisted_4$11","_hoisted_5$9","_hoisted_6$7","_hoisted_7$7","_hoisted_8$7","_hoisted_9$6","_hoisted_10$6","_hoisted_11$6","_hoisted_12$6","_hoisted_13$6","_hoisted_14$5","_hoisted_15$4","_hoisted_16$3","_hoisted_17$3","_hoisted_18$3","_hoisted_19$3","_hoisted_20$3","_hoisted_21$2","FileView_default","File","AudioLines","Film","sizeLabel","bytes","units","FileBlock","_hoisted_1$11","_hoisted_2$11","_hoisted_3$10","_hoisted_4$10","_hoisted_5$8","_hoisted_6$6","_hoisted_7$6","_hoisted_8$6","_hoisted_9$5","_hoisted_10$5","_hoisted_11$5","_hoisted_12$5","_hoisted_13$5","_hoisted_14$4","_hoisted_15$3","_hoisted_16$2","_hoisted_17$2","_hoisted_18$2","_hoisted_19$2","_hoisted_20$2","SANDBOX","HtmlView_default","code","height","srcdoc","mode","interacting","fullscreen","showCode","textarea","showPreview","commit","draft","highlightEl","onInput","onKeydown","syncScroll","grammarReady","escapeHtml","toHtml","highlighted","onFile","onFullscreenKey","CodeXml","Eye","Maximize2","Pointer","HtmlBlock","_hoisted_1$10","_hoisted_2$10","_hoisted_3$9","_hoisted_4$9","_hoisted_5$7","MathView_default","rendered","editing","latex","katex","latexAttr","MathBlock","InputRule","MathInline","match","_hoisted_1$9","_hoisted_2$9","_hoisted_3$8","_hoisted_4$8","_hoisted_5$6","_hoisted_6$5","_hoisted_7$5","_hoisted_8$5","MentionMenu_default","User","FileText","Calendar","order","g","_hoisted_1$8","_hoisted_2$8","_hoisted_3$7","_hoisted_4$7","_hoisted_5$5","_hoisted_6$4","_hoisted_7$4","_hoisted_8$4","_hoisted_9$4","_hoisted_10$4","_hoisted_11$4","_hoisted_12$4","_hoisted_13$4","_hoisted_14$3","_hoisted_15$2","_hoisted_16$1","_hoisted_17$1","_hoisted_18$1","_hoisted_19$1","_hoisted_20$1","_hoisted_21$1","_hoisted_22","_hoisted_23","_hoisted_24","_hoisted_25","_hoisted_26","_hoisted_27","_hoisted_28","_hoisted_29","_hoisted_30","DatePicker_default","update","patch","inputFmt","val","commitDate","parsed","which","monthOf","commitTime","parseIsoDate","today","monthLabel","month","weekdays","fmt","days","inRange","pick","goToday","submenu","reminders","formatLabel","toggleEnd","toggleTime","remind","setFormat","setTimeFormat","setRemind","withKeys","ChevronLeft","ChevronRight","CircleQuestionMark","_hoisted_1$7","_hoisted_2$7","_hoisted_3$6","_hoisted_4$6","_hoisted_5$4","_hoisted_6$3","_hoisted_7$3","_hoisted_8$3","_hoisted_9$3","_hoisted_10$3","_hoisted_11$3","_hoisted_12$3","_hoisted_13$3","_hoisted_14$2","MentionView_default","dateValue","chip","panel","onDocPointer","avatar","onClick","searchInput","changeDate","fireAt","clearDate","results","shallowRef","searchToken","token","pickItem","mentionPluginKey","iso","dateItems","day","make","labels","typed","norm","MentionNode","mentionSuggestion","search","MermaidPreview","SAMPLE_MERMAID","_hoisted_1$6","_hoisted_2$6","TocView_default","collect","minLevel","go","TableOfContents","toc","math","Sigma","Radical","Workflow","emoji","FILE_ICONS","mention","AtSign","defaultBlocks","ContentError","message","wrapUnknown","issues","repair","sanitizeContent","wrapped","json","fixed","unwrapUnknown","defineTokens","tokens","COLORS","_hoisted_1$5","_hoisted_2$5","_hoisted_3$5","_hoisted_4$5","colorRows","ColorList_default","rows","isCurrent","row","_hoisted_1$4","_hoisted_2$4","_hoisted_3$4","_hoisted_4$4","_hoisted_5$3","_hoisted_6$2","_hoisted_7$2","_hoisted_8$2","_hoisted_9$2","_hoisted_10$2","_hoisted_11$2","_hoisted_12$2","_hoisted_13$2","_hoisted_14$1","_hoisted_15$1","BlockMenu_default","targets","canTurnInto","hasText","colors","blockId","shortcutFor","turnInto","pickColor","actions","Link2","ArrowUp","ArrowDown","Repeat2","Palette","turnRows","colorRowList","colorMatches","subActive","subCount","scrollActive","openSubmenu","focusFirst","runRow","runSubmenuItem","inSub","hoverRow","keepSubmenu","flipSubmenu","width","Search","ti","_hoisted_1$3","_hoisted_2$3","_hoisted_3$3","_hoisted_4$3","_hoisted_5$2","_hoisted_6$1","_hoisted_7$1","_hoisted_8$1","_hoisted_9$1","_hoisted_10$1","_hoisted_11$1","_hoisted_12$1","_hoisted_13$1","FormatMenu_default","linkUrl","linkInput","actionsFor","shouldShow","CellSelection","actionTitle","runAction","Bold","Italic","Underline","Strikethrough","applyLink","setColor","selectionColors","activeTextColor","BubbleMenu","Baseline","Unlink","_hoisted_1$2","_hoisted_2$2","_hoisted_3$2","_hoisted_4$2","MeiOutline_default","onScreen","updateActive","schedule","onScroll","visible","closeTimer","enter","leave","tableAt","TableMap","cellPos","col","focusCell","selectRow","$cell","selectColumn","insertRow","where","insertColumn","deleteRow","deleteColumn","moveRow","moveTableRow","moveColumn","moveTableColumn","duplicateRow","$row","rowNode","duplicateColumn","cell","clearSelectedCells","colorSelectedCells","hasHeaderRow","header","hasHeaderColumn","toggleHeader","_hoisted_1$1","_hoisted_2$1","_hoisted_3$1","_hoisted_4$1","_hoisted_5$1","_hoisted_6","_hoisted_7","_hoisted_8","_hoisted_9","_hoisted_10","_hoisted_11","_hoisted_12","_hoisted_13","_hoisted_14","_hoisted_15","_hoisted_16","_hoisted_17","_hoisted_18","_hoisted_19","_hoisted_20","_hoisted_21","TableControls_default","colorNames","layer","hover","hideTimer","frame","locate","tableEl","tablePos","tableRect","wrapRect","onMouseMove","tick","onUpdate","colorOpen","menuEl","closeMenu","openMenu","screen","above","menuItems","mn","t2","PanelTop","ArrowUpToLine","ArrowDownToLine","Eraser","PanelLeft","ArrowLeftToLine","ArrowRightToLine","ArrowLeft","ArrowRight","onMenuKey","addRow","addColumn","cellColorOpen","onSelection","left","bgColors","GripVertical","GripHorizontal","TableCellsMerge","TableCellsSplit","_hoisted_1","_hoisted_2","_hoisted_3","_hoisted_4","_hoisted_5","MeiEditor_default","contentFailed","globalBlocks","inject","rootEl","outlineMin","hasTables","instanceId","useId","globalTokens","css","prepare","lastEmitted","collaboration","toRaw","unmounted","createEditor","extra","Editor","collaborationExtensions","nestedOptions","hovered","handlePos","onNodeChange","handlePosition","rects","onDragStart","setHandleLocked","locked","showMenu","hideTooltip","own","openMenuAt","toast","toastTimer","showToast","revealHashBlock","tooltip","tooltipTimer","showTooltip","addBlock","focusEnd","DragHandle","EditorContent","verb","MeiEditorPlugin","app","htmlBlockCsp","locales"],"sources":["../src/config.ts","../src/define-block.ts","../src/block-ops.ts","../src/extensions/block-drop.ts","../src/extensions/block-id.ts","../src/block-items.ts","../src/extensions/block-selection.ts","../src/extensions/file-drop.ts","../src/safe-url.ts","../src/extensions/markdown-paste.ts","../src/extensions/placeholder.ts","../src/extensions/color-marks.ts","../src/composables/useScope.ts","../src/composables/usePointerMoved.ts","../src/components/SlashMenu.vue","../src/components/SlashMenu.vue","../src/recent.ts","../src/slash-items.ts","../src/theme/read.ts","../src/extensions/suggestion-renderer.ts","../src/extensions/slash-command.ts","../src/extensions/unknown.ts","../src/extensions/index.ts","../src/handle-anchor.ts","../src/keys.ts","../src/plugin-key.ts","../src/nodeviews/renderer.ts","../src/composables/useEditable.ts","../src/composables/useClickOutside.ts","../src/nodeviews/CalloutView.vue","../src/nodeviews/CalloutView.vue","../src/extensions/callout.ts","../src/lazy.ts","../src/components/MermaidDiagram.vue","../src/components/MermaidDiagram.vue","../src/nodeviews/CodeBlockView.vue","../src/nodeviews/CodeBlockView.vue","../src/extensions/code-block.ts","../src/extensions/columns.ts","../src/extensions/table.ts","../src/extensions/toggle.ts","../src/blocks/advanced.ts","../src/blocks/basic.ts","../src/nodeviews/EmbedView.vue","../src/nodeviews/EmbedView.vue","../src/extensions/embed.ts","../src/components/ImageCropper.vue","../src/components/ImageCropper.vue","../src/components/ImageLightbox.vue","../src/components/ImageLightbox.vue","../src/composables/useUploadState.ts","../src/nodeviews/ImageView.vue","../src/nodeviews/ImageView.vue","../src/extensions/upload-attrs.ts","../src/extensions/image-block.ts","../src/blocks/media.ts","../src/components/EmojiMenu.vue","../src/components/EmojiMenu.vue","../src/emoji-data.ts","../src/extensions/emoji.ts","../src/nodeviews/FileView.vue","../src/nodeviews/FileView.vue","../src/extensions/file-block.ts","../src/nodeviews/HtmlView.vue","../src/nodeviews/HtmlView.vue","../src/extensions/html-block.ts","../src/nodeviews/MathView.vue","../src/nodeviews/MathView.vue","../src/extensions/math.ts","../src/components/MentionMenu.vue","../src/components/MentionMenu.vue","../src/components/DatePicker.vue","../src/components/DatePicker.vue","../src/nodeviews/MentionView.vue","../src/nodeviews/MentionView.vue","../src/extensions/mention.ts","../src/extensions/mermaid.ts","../src/nodeviews/TocView.vue","../src/nodeviews/TocView.vue","../src/extensions/toc.ts","../src/blocks/extras.ts","../src/blocks/index.ts","../src/content.ts","../src/theme/index.ts","../src/colors.ts","../src/components/ColorList.vue","../src/components/ColorList.vue","../src/components/BlockMenu.vue","../src/components/BlockMenu.vue","../src/components/FormatMenu.vue","../src/components/FormatMenu.vue","../src/components/MeiOutline.vue","../src/components/MeiOutline.vue","../src/table-ops.ts","../src/components/TableControls.vue","../src/components/TableControls.vue","../src/components/MeiEditor.vue","../src/components/MeiEditor.vue","../src/plugin.ts"],"sourcesContent":["import { Extension } from '@tiptap/core'\nimport { shallowReactive } from 'vue'\nimport type { BlockType } from './block-items'\nimport type { FormatAction } from './define-block'\nimport { type EditorMessages, type LocaleName, vi } from './locale'\n\n/**\n * Uploads an image file and resolves to its public URL. `onProgress` (0..1) is optional to call:\n * the image block shows it while the upload runs.\n */\nexport type ImageUploader = (file: File, onProgress?: (fraction: number) => void) => Promise<string>\n\nexport interface MeiConfigStorage {\n messages: EditorMessages\n locale: LocaleName\n /** Menu entries of the loaded blocks (slash menu, \"Turn into\"). */\n items: BlockType[]\n /** Extra bubble-menu buttons of the loaded blocks (e.g. \"Comment\"). */\n formatActions: FormatAction[]\n /** Custom uploader. Without it, images are inlined as base64 data URLs. */\n uploadImage: ImageUploader | null\n /** Max image size in MB. */\n maxImageSize: number\n /**\n * Attributes for every element that carries theme tokens: the editor root and\n * popovers teleported to <body> (so they get the same mode and overrides).\n */\n scope: { class: string[], 'data-me-id': string }\n}\n\ndeclare module '@tiptap/core' {\n interface Storage {\n meiConfig: MeiConfigStorage\n }\n}\n\n/** Holds editor-wide settings that menus and node views read at runtime. */\nexport const MeiConfig = Extension.create<Partial<MeiConfigStorage>, MeiConfigStorage>({\n name: 'meiConfig',\n\n // Reactive so menus and node views re-render when the locale or options change.\n addStorage() {\n return shallowReactive({\n messages: this.options.messages ?? vi,\n locale: this.options.locale ?? 'vi',\n items: this.options.items ?? [],\n formatActions: this.options.formatActions ?? [],\n uploadImage: this.options.uploadImage ?? null,\n maxImageSize: this.options.maxImageSize ?? 5,\n scope: this.options.scope ?? { 'class': ['me-scope'], 'data-me-id': '' },\n })\n },\n})\n","import type { AnyExtension, Editor } from '@tiptap/core'\nimport type { Component } from 'vue'\nimport type { BlockType } from './block-items'\nimport type { LocaleName, PartialMessages } from './locale'\nimport type { BlockRenderers } from './render/types'\n\n/**\n * A button a block adds to the selection bubble menu (after the built-in marks),\n * e.g. \"Comment\". `readOnly: true` also shows it in read-only editors.\n */\nexport interface FormatAction {\n id: string\n icon: Component\n title: string | ((editor: Editor) => string)\n run: (editor: Editor) => void\n /** Show in read-only editors too (the menu then shows only these actions). */\n readOnly?: boolean\n /** Hide the action for this editor / selection. */\n isVisible?: (editor: Editor) => boolean\n}\n\nexport interface BlockSpec<O extends object = Record<string, never>> {\n /** Unique name, e.g. `'heading'`, `'math'`. */\n name: string\n /** Default options, overridable with `.configure()`. */\n defaults?: O\n /** Tiptap extensions the block needs. Extensions shared by blocks are de-duplicated by name. */\n extensions?: (options: O) => AnyExtension[]\n /** Slash menu / \"Turn into\" entries. */\n items?: (options: O) => BlockType[]\n /** ProseMirror node types this block creates (they get stable ids). */\n nodes?: string[]\n /** UI strings per locale, merged into the editor messages (for custom blocks). */\n messages?: Partial<Record<LocaleName, PartialMessages>>\n /** Bubble-menu buttons for a text selection. */\n formatActions?: (options: O) => FormatAction[]\n /**\n * Server-side HTML for the block's nodes / marks, used by `renderHTML` from\n * `@toantranmei/editor/render`. Must not touch the DOM.\n */\n render?: (options: O) => BlockRenderers\n}\n\n/** A block ready to pass to `<MeiEditor :blocks>`. */\nexport interface BlockDefinition<O extends object = any> {\n name: string\n options: O\n extensions: AnyExtension[]\n items: BlockType[]\n nodes: string[]\n messages?: Partial<Record<LocaleName, PartialMessages>>\n formatActions?: FormatAction[]\n /** Static HTML renderers (see `renderHTML`). */\n render?: BlockRenderers\n /** Returns a copy with different options: `file.configure({ upload })`. */\n configure: (options: Partial<O>) => BlockDefinition<O>\n}\n\n/**\n * Declares a block: its Tiptap extensions, menu entries and strings, in one place.\n *\n * @example\n * export const invoice = defineBlock({\n * name: 'invoice',\n * nodes: ['invoice'],\n * extensions: () => [InvoiceNode],\n * items: () => [{ id: 'invoice', icon: Receipt, group: 'advanced', keywords: ['bill'], insert: c => c.insertInvoice() }],\n * messages: { vi: { blocks: { invoice: { title: 'Hoá đơn', description: 'Chèn hoá đơn' } } } },\n * })\n */\nexport function defineBlock<O extends object = Record<string, never>>(spec: BlockSpec<O>): BlockDefinition<O> {\n const build = (options: O): BlockDefinition<O> => ({\n name: spec.name,\n options,\n extensions: spec.extensions?.(options) ?? [],\n items: spec.items?.(options) ?? [],\n nodes: spec.nodes ?? [],\n messages: spec.messages,\n formatActions: spec.formatActions?.(options),\n render: spec.render?.(options),\n configure: overrides => build({ ...options, ...overrides }),\n })\n return build({ ...(spec.defaults ?? {}) } as O)\n}\n\n/** Flattens block definitions into one extension list (first extension per name wins). */\nexport function collectExtensions(blocks: BlockDefinition[]): AnyExtension[] {\n const seen = new Set<string>()\n return blocks.flatMap(b => b.extensions).filter((ext) => {\n if (seen.has(ext.name)) return false\n seen.add(ext.name)\n return true\n })\n}\n","/**\n * Operations on a range of sibling blocks. Shared by the ⋮⋮ menu, keyboard shortcuts,\n * block selection and drag & drop, so each behavior has exactly one implementation.\n *\n * A \"block\" is a direct child of the doc or of a column.\n */\nimport type { Editor } from '@tiptap/core'\nimport { Fragment, type Node as PMNode, type ResolvedPos } from '@tiptap/pm/model'\nimport { type EditorState, TextSelection, type Transaction } from '@tiptap/pm/state'\nimport { NodeRangeSelection } from '@tiptap/extension-node-range'\nimport type { BlockType } from './block-items'\nimport type { ColorName } from './colors'\n\n/** `[from, to)` covers whole sibling blocks; `depth` is their parent's depth. */\nexport interface BlockRange { from: number, to: number, depth: number }\n\nconst CONTAINERS = ['doc', 'column']\n\n/** The block owning `$pos`: deepest ancestor whose parent is the doc or a column. */\nexport function blockAt($pos: ResolvedPos): { node: PMNode, pos: number, depth: number } | null {\n for (let d = $pos.depth; d >= 1; d--) {\n const node = $pos.node(d)\n if (CONTAINERS.includes($pos.node(d - 1).type.name) && !['column', 'columns'].includes(node.type.name)) {\n return { node, pos: $pos.before(d), depth: d - 1 }\n }\n }\n // Atom blocks (image, divider…) selected as nodes.\n const after = $pos.nodeAfter\n if (after?.isBlock && CONTAINERS.includes($pos.parent.type.name)) return { node: after, pos: $pos.pos, depth: $pos.depth }\n return null\n}\n\nexport const rangeOfBlock = (block: { node: PMNode, pos: number, depth: number }): BlockRange =>\n ({ from: block.pos, to: block.pos + block.node.nodeSize, depth: block.depth })\n\n/** Range spanning the blocks of `a` and `b` (falls back to their shared container level). */\nexport function rangeBetween(doc: PMNode, a: number, b: number): BlockRange | null {\n const ba = blockAt(doc.resolve(a))\n const bb = blockAt(doc.resolve(b))\n if (!ba || !bb) return null\n if (ba.depth === bb.depth && doc.resolve(ba.pos).parent === doc.resolve(bb.pos).parent) {\n return { from: Math.min(ba.pos, bb.pos), to: Math.max(ba.pos + ba.node.nodeSize, bb.pos + bb.node.nodeSize), depth: ba.depth }\n }\n // Different containers (e.g. inside vs. outside columns): select whole top-level blocks.\n const top = (pos: number) => {\n const $p = doc.resolve(pos)\n return { from: $p.before(1), to: $p.after(1) }\n }\n const ta = top(ba.pos + 1)\n const tb = top(bb.pos + 1)\n return { from: Math.min(ta.from, tb.from), to: Math.max(ta.to, tb.to), depth: 0 }\n}\n\nexport const isBlockSelection = (state: EditorState) => state.selection instanceof NodeRangeSelection\n\n/** Blocks the next command acts on: the block selection, or the block(s) holding the cursor. */\nexport function currentRange(state: EditorState): BlockRange | null {\n const sel = state.selection\n if (sel instanceof NodeRangeSelection) return { from: sel.from, to: sel.to, depth: sel.depth ?? 0 }\n return rangeBetween(state.doc, sel.from, sel.to)\n}\n\n/** Nodes in a range, in order. */\nexport function blocksIn(doc: PMNode, range: BlockRange): { node: PMNode, pos: number }[] {\n const out: { node: PMNode, pos: number }[] = []\n for (let pos = range.from; pos < range.to;) {\n const node = doc.nodeAt(pos)\n if (!node) break\n out.push({ node, pos })\n pos += node.nodeSize\n }\n return out\n}\n\nexport function setBlockSelection(tr: Transaction, range: BlockRange) {\n return tr.setSelection(NodeRangeSelection.create(tr.doc, range.from + 1, range.to - 1, range.depth))\n}\n\nexport function selectBlocks(editor: Editor, range: BlockRange) {\n editor.view.dispatch(setBlockSelection(editor.state.tr, range))\n}\n\n/**\n * Called after removing content from inside a column: drops the column if it became\n * empty and unwraps the columns block when a single column is left (Notion behavior).\n */\nexport function dissolveEmptyColumn(tr: Transaction, pos: number) {\n const $pos = tr.doc.resolve(Math.min(pos, tr.doc.content.size))\n let columnDepth = -1\n for (let d = $pos.depth; d >= 1; d--) {\n if ($pos.node(d).type.name === 'column') {\n columnDepth = d\n break\n }\n }\n if (columnDepth < 1) return\n const column = $pos.node(columnDepth)\n const isEmpty = column.childCount === 1 && column.firstChild!.isTextblock && column.firstChild!.content.size === 0\n if (!isEmpty) return\n\n const columns = $pos.node(columnDepth - 1)\n const columnsPos = $pos.before(columnDepth - 1)\n const rest: PMNode[] = []\n columns.forEach(c => c !== column && rest.push(c))\n const replacement = rest.length >= 2\n ? Fragment.from(columns.copy(Fragment.from(rest)))\n : rest.length === 1 ? rest[0]!.content : Fragment.empty\n tr.replaceWith(columnsPos, columnsPos + columns.nodeSize, replacement)\n}\n\n/** Restores a block or text selection over `range` after it moved to `next`. */\nfunction reselect(tr: Transaction, wasBlocks: boolean, oldFrom: number, caret: number, next: BlockRange) {\n if (wasBlocks) return setBlockSelection(tr, next)\n return tr.setSelection(TextSelection.near(tr.doc.resolve(Math.min(next.from + (caret - oldFrom), tr.doc.content.size))))\n}\n\nexport function deleteBlocks(editor: Editor, range: BlockRange) {\n const tr = editor.state.tr.delete(range.from, range.to)\n dissolveEmptyColumn(tr, tr.mapping.map(range.from))\n tr.setSelection(TextSelection.near(tr.doc.resolve(Math.min(tr.mapping.map(range.from), tr.doc.content.size))))\n editor.view.dispatch(tr.scrollIntoView())\n editor.view.focus()\n}\n\nexport function duplicateBlocks(editor: Editor, range: BlockRange) {\n const { state } = editor\n const slice = state.doc.slice(range.from, range.to)\n const tr = state.tr.insert(range.to, slice.content)\n const next = { from: range.to, to: range.to + slice.content.size, depth: range.depth }\n reselect(tr, isBlockSelection(state), range.from, state.selection.from, next)\n editor.view.dispatch(tr.scrollIntoView())\n}\n\n/** Swaps the range with its previous/next sibling. Returns false at the edge. */\nexport function moveBlocks(editor: Editor, range: BlockRange, dir: 'up' | 'down') {\n const { state } = editor\n const $from = state.doc.resolve(range.from)\n const parent = $from.parent\n const startIndex = $from.index()\n const endIndex = state.doc.resolve(range.to).index()\n const slice = state.doc.slice(range.from, range.to)\n const tr = state.tr\n\n let insertAt: number\n if (dir === 'up') {\n if (startIndex === 0) return false\n insertAt = range.from - parent.child(startIndex - 1).nodeSize\n tr.delete(range.from, range.to)\n }\n else {\n if (endIndex >= parent.childCount) return false\n const after = range.to + parent.child(endIndex).nodeSize\n tr.delete(range.from, range.to)\n insertAt = tr.mapping.map(after)\n }\n tr.insert(insertAt, slice.content)\n reselect(tr, isBlockSelection(state), range.from, state.selection.from, { from: insertAt, to: insertAt + slice.content.size, depth: range.depth })\n editor.view.dispatch(tr.scrollIntoView())\n return true\n}\n\n/** Selects the text of every block in the range (for marks / turn into). */\nfunction selectText(tr: Transaction, from: number, to: number) {\n return tr.setSelection(TextSelection.between(tr.doc.resolve(from + 1), tr.doc.resolve(Math.max(from + 1, to - 1))))\n}\n\n/**\n * Converts every block in the range, keeping text. Toggles are unwrapped first, then\n * lists/quotes/callouts are cleared to paragraphs and the new type is applied.\n */\nexport function turnBlocksInto(editor: Editor, range: BlockRange, block: BlockType) {\n if (!block.turnInto) return\n const wasBlocks = isBlockSelection(editor.state)\n let to = range.to\n\n const chain = editor.chain().focus().command(({ tr }) => {\n // Unwrap toggles from last to first so earlier positions stay valid.\n for (const { node, pos } of blocksIn(tr.doc, range).reverse()) {\n if (node.type.name !== 'details') continue\n const [summary, content] = [node.child(0), node.child(1)]\n const paragraph = tr.doc.type.schema.nodes.paragraph!.create(null, summary.content)\n const fragment = Fragment.from(paragraph).append(content.content)\n tr.replaceWith(pos, pos + node.nodeSize, fragment)\n }\n to = tr.mapping.map(range.to)\n selectText(tr, range.from, to)\n return true\n }).clearNodes()\n block.turnInto(chain).run()\n\n if (wasBlocks) {\n const { from: a, to: b } = editor.state.selection\n const next = rangeBetween(editor.state.doc, a, b)\n if (next) selectBlocks(editor, next)\n }\n}\n\n/**\n * Colors whole blocks, like Notion: blocks that support it get a block color (the\n * background fills the block, and empty blocks color what's typed later); others\n * (callouts, code…) get the color on their text. Inline colors of the same kind are\n * cleared so the block color shows.\n */\nexport function colorBlocks(editor: Editor, range: BlockRange, kind: 'text' | 'bg', color: ColorName) {\n const attr = kind === 'text' ? 'blockColor' : 'blockBg'\n const mark = editor.schema.marks[kind === 'text' ? 'textColor' : 'bgColor']\n const value = color === 'default' ? null : color\n const wasBlocks = isBlockSelection(editor.state)\n editor.chain().focus().command(({ tr }) => {\n for (const { node, pos } of blocksIn(tr.doc, range)) {\n const end = pos + node.nodeSize\n if (kind === 'bg' && node.type.name === 'callout') {\n // A callout's background is its own color.\n tr.setNodeAttribute(pos, 'color', value ?? 'gray')\n }\n else if (node.type.spec.attrs?.[attr]) {\n tr.setNodeAttribute(pos, attr, value)\n if (mark) tr.removeMark(pos, end, mark)\n }\n else if (mark) {\n tr.removeMark(pos, end, mark)\n if (value) tr.addMark(pos, end, mark.create({ color: value }))\n }\n }\n return true\n }).run()\n if (wasBlocks) selectBlocks(editor, range)\n}\n\n/** Text/background color shared by all text in the range, if uniform. */\nexport function rangeColors(state: EditorState, range: BlockRange) {\n const found = { text: new Set<string>(), bg: new Set<string>() }\n let any = false\n // Inline mark wins, else the nearest colored block around the text.\n const add = (pos: number, marks: readonly { type: { name: string }, attrs: Record<string, any> }[]) => {\n const $pos = state.doc.resolve(pos)\n const fromBlocks = (attr: string) => {\n for (let d = $pos.depth; d > 0; d--) if ($pos.node(d).attrs[attr]) return $pos.node(d).attrs[attr] as string\n return 'default'\n }\n any = true\n found.text.add(marks.find(m => m.type.name === 'textColor')?.attrs.color ?? fromBlocks('blockColor'))\n found.bg.add(marks.find(m => m.type.name === 'bgColor')?.attrs.color ?? fromBlocks('blockBg'))\n }\n state.doc.nodesBetween(range.from, range.to, (node, pos) => {\n if (node.isText) add(pos, node.marks)\n // An empty colored line still shows (and ticks) its color.\n else if (node.isTextblock && !node.content.size) add(pos + 1, [])\n })\n const single = (s: Set<string>): string | null => (any && s.size === 1 ? [...s][0]! : null)\n return { text: single(found.text), bg: single(found.bg) }\n}\n","import { Extension } from '@tiptap/core'\nimport type { Node as PMNode, Slice } from '@tiptap/pm/model'\nimport { NodeSelection, Plugin, PluginKey, TextSelection } from '@tiptap/pm/state'\nimport type { EditorView } from '@tiptap/pm/view'\nimport { dissolveEmptyColumn } from '../block-ops'\n\nexport interface BlockDropOptions {\n /** Node types whose direct children are \"blocks\" you can drop between. */\n containers: string[]\n /** Class of the drop indicator line. */\n indicatorClass: string\n /** Max columns when dropping beside a block. */\n maxColumns: number\n}\n\nexport interface BlockDropStorage {\n /** True while a block is being dragged from the drag handle. */\n active: boolean\n}\n\ndeclare module '@tiptap/core' {\n interface Storage {\n blockDrop: BlockDropStorage\n }\n}\n\ninterface Line { left: number, top: number, width: number, height?: number, vertical?: boolean }\n\n/** Where a dragged block lands. */\ntype DropTarget =\n /** Between blocks (or appended inside a list/toggle/callout when nested). */\n | { kind: 'insert', pos: number, line: Line }\n /** Beside a block: wraps it into two columns. */\n | { kind: 'wrap', blockPos: number, side: 'left' | 'right', line: Line }\n /** Beside a column: adds a new column. */\n | { kind: 'column', pos: number, line: Line }\n\n// Interaction thresholds (behavior, not visuals).\nconst SIDE_ZONE = 48 // px from a block's right edge that means \"make columns\"\n// Left edge: narrower, and only after a clear sideways move. Dragging straight down from\n// the handle keeps the pointer near blocks' left edges, which must not create columns.\nconst LEFT_ZONE = 24\nconst LEFT_INTENT = 60 // px of horizontal travel from the drag start\nconst NEST_INDENT = 32 // px right of a block's left edge that means \"nest inside\"\nconst SCROLL_ZONE = 64 // px from the viewport edge that starts auto-scroll\nconst SCROLL_SPEED = 18 // max px per frame\n\n/** Blocks that can take children at their end when you drop with an indent. */\nconst NESTABLE = ['bulletList', 'orderedList', 'taskList', 'details', 'callout']\n\nexport const blockDropKey = new PluginKey('blockDrop')\n\nconst rectOf = (view: EditorView, pos: number) => {\n const dom = view.nodeDOM(pos)\n return dom instanceof HTMLElement ? dom.getBoundingClientRect() : null\n}\n\n/** A block under (or nearest to) a point: its container, and whether the point is in the block's top half. */\nexport interface BlockAtPoint {\n container: PMNode\n /** -1 for the doc. */\n containerPos: number\n block: { node: PMNode, pos: number, rect: DOMRect }\n /** False when the point is below every block (`block` is then the last one). */\n hit: boolean\n before: boolean\n}\n\n/**\n * Geometry-only lookup (`posAtCoords` fails over node views, gaps and the gutter): the container under the point\n * (a column or the doc), then its child block at the point's height, or the last one.\n */\nexport function blockAtPoint(view: EditorView, x: number, y: number, containers: string[] = ['doc', 'column']): BlockAtPoint | null {\n const { doc } = view.state\n let container: PMNode = doc\n let containerPos = -1\n let start = 0\n doc.descendants((node, pos) => {\n if (containers.includes(node.type.name) && node.type.name !== 'doc') {\n const r = rectOf(view, pos)\n if (r && x >= r.left && x <= r.right && y >= r.top && y <= r.bottom) {\n container = node\n containerPos = pos\n start = pos + 1\n }\n return false\n }\n // Only walk into wrappers that hold containers (e.g. `columns`).\n return node.type.name === 'columns'\n })\n type Hit = BlockAtPoint['block']\n let hit = null as Hit | null\n let last = null as Hit | null\n container.forEach((child, offset) => {\n if (hit) return\n const pos = start + offset\n const rect = rectOf(view, pos)\n if (!rect) return\n if (y < rect.bottom) hit = { node: child, pos, rect }\n last = { node: child, pos, rect }\n })\n const block = hit ?? last\n if (!block) return null\n return { container, containerPos, block, hit: !!hit, before: !!hit && y < block.rect.top + block.rect.height / 2 }\n}\n\n/** Position between blocks nearest to a point (before / after the block at its height). */\nexport function blockGapAtPoint(view: EditorView, x: number, y: number, containers?: string[]): number | null {\n const at = blockAtPoint(view, x, y, containers)\n if (!at) return null\n return at.before ? at.block.pos : at.block.pos + at.block.node.nodeSize\n}\n\n/**\n * Notion-style drop for blocks dragged from the drag handle:\n * - between blocks (top level or in a column), never inside a list item by accident;\n * - beside a block (left/right edge) to create or extend columns;\n * - with an indent below a list/toggle/callout to nest inside it;\n * - auto-scrolls near the viewport edges.\n */\nexport const BlockDrop = Extension.create<BlockDropOptions, BlockDropStorage>({\n name: 'blockDrop',\n\n addOptions() {\n return { containers: ['doc', 'column'], indicatorClass: 'me-drop-indicator', maxColumns: 5 }\n },\n\n addStorage() {\n return { active: false }\n },\n\n addProseMirrorPlugins() {\n const { containers, indicatorClass, maxColumns } = this.options\n const storage = this.storage\n const editor = this.editor\n let indicator: HTMLElement | null = null\n\n const hide = () => {\n indicator?.remove()\n indicator = null\n }\n const show = (line: Line) => {\n if (!indicator) {\n indicator = document.createElement('div')\n // Lives in <body>, so copy the editor's theme scope (mode class + overrides id).\n const scope = editor.storage.meiConfig?.scope\n indicator.className = [...(scope?.class ?? ['me-scope']), indicatorClass].join(' ')\n if (scope?.['data-me-id']) indicator.dataset.meId = scope['data-me-id']\n document.body.appendChild(indicator)\n }\n indicator.classList.toggle('is-vertical', !!line.vertical)\n Object.assign(indicator.style, {\n left: `${line.left}px`,\n top: `${line.top}px`,\n width: line.vertical ? '' : `${line.width}px`,\n height: line.vertical ? `${line.height}px` : '',\n })\n }\n\n /** True if the dragged slice contains columns (no columns inside columns). */\n const draggingColumns = (view: EditorView) => {\n let found = false\n view.dragging?.slice.content.descendants((n) => {\n if (n.type.name === 'columns') found = true\n return !found\n })\n return found\n }\n\n /**\n * Picks the drop target from geometry (posAtCoords fails over node views and gaps):\n * the container under the pointer (a column or the doc), the child block at the\n * pointer's height, then side/indent zones of that block.\n */\n let dragStartX: number | null = null\n const findDropTarget = (view: EditorView, x: number, y: number): DropTarget | null => {\n const { doc, selection } = view.state\n const at = blockAtPoint(view, x, y, containers)\n if (!at) return null\n const { container, containerPos, block } = at\n const { rect } = block\n const isSelf = block.pos >= selection.from && block.pos < selection.to\n\n // Beside a block → columns.\n const rightZone = Math.min(SIDE_ZONE, rect.width * 0.2)\n const leftIntent = dragStartX !== null && Math.abs(x - dragStartX) >= LEFT_INTENT\n const side = x > rect.right - rightZone ? 'right' : leftIntent && x < rect.left + LEFT_ZONE ? 'left' : null\n if (side && !isSelf && !draggingColumns(view)) {\n const vertical = (edgeX: number, r: DOMRect): Line => ({ left: edgeX, top: r.top, width: 0, height: r.height, vertical: true })\n if (container.type.name === 'column') {\n // Add a column next to the hovered column.\n const columns = doc.resolve(containerPos).parent\n const colRect = rectOf(view, containerPos)\n if (columns.childCount < maxColumns && colRect) {\n return {\n kind: 'column',\n pos: side === 'left' ? containerPos : containerPos + container.nodeSize,\n line: vertical(side === 'left' ? colRect.left : colRect.right, colRect),\n }\n }\n }\n else if (block.node.type.name === 'columns') {\n if (block.node.childCount < maxColumns) {\n return { kind: 'column', pos: side === 'left' ? block.pos + 1 : block.pos + block.node.nodeSize - 1, line: vertical(side === 'left' ? rect.left : rect.right, rect) }\n }\n }\n else {\n return { kind: 'wrap', blockPos: block.pos, side, line: vertical(side === 'left' ? rect.left : rect.right, rect) }\n }\n }\n\n const { before } = at\n // Indented drop below a list/toggle/callout → nest at its end.\n if (!before && !isSelf && NESTABLE.includes(block.node.type.name) && x > rect.left + NEST_INDENT && !draggingColumns(view)) {\n const end = block.pos + block.node.nodeSize\n // Lists: inside the last item; toggle: inside its content; callout: inside it.\n const pos = block.node.type.name === 'callout' ? end - 1 : end - 2\n return { kind: 'insert', pos, line: { left: rect.left + NEST_INDENT, top: rect.bottom, width: rect.width - NEST_INDENT } }\n }\n\n return {\n kind: 'insert',\n pos: before ? block.pos : block.pos + block.node.nodeSize,\n line: { left: rect.left, top: before ? rect.top : rect.bottom, width: rect.width },\n }\n }\n\n /** Generous hit area around the editor, so drops in the gutter still count. */\n const isNearEditor = (view: EditorView, e: DragEvent) => {\n const r = view.dom.getBoundingClientRect()\n return e.clientY > r.top - 24 && e.clientY < r.bottom + 120 && e.clientX > r.left - 120 && e.clientX < r.right + 60\n }\n\n const moveBlock = (view: EditorView, target: DropTarget) => {\n const slice = view.dragging?.slice\n const { from, to } = view.state.selection\n view.dragging = null\n if (!slice || slice.size === 0) return\n if (target.kind === 'insert' && target.pos >= from && target.pos <= to) return\n\n const { schema } = view.state\n const tr = view.state.tr\n tr.delete(from, to)\n dissolveEmptyColumn(tr, tr.mapping.map(from))\n\n let insertAt: number\n if (target.kind === 'wrap') {\n const pos = tr.mapping.map(target.blockPos)\n const node = tr.doc.nodeAt(pos)\n if (!node) return\n const column = schema.nodes.column!\n const dragged = column.create(null, slice.content)\n const existing = column.create(null, node)\n tr.replaceWith(pos, pos + node.nodeSize, schema.nodes.columns!.create(null, target.side === 'left' ? [dragged, existing] : [existing, dragged]))\n insertAt = target.side === 'left' ? pos + 2 : pos + 2 + existing.nodeSize\n }\n else if (target.kind === 'column' && tr.doc.resolve(tr.mapping.map(target.pos)).parent.type.name === 'columns') {\n insertAt = tr.mapping.map(target.pos)\n tr.insert(insertAt, schema.nodes.column!.create(null, slice.content))\n insertAt += 1\n }\n else {\n // Plain insert (also the fallback if removing the block dissolved the target columns).\n insertAt = tr.mapping.map(target.pos)\n tr.replaceRange(insertAt, insertAt, slice as Slice)\n }\n\n // Select the moved block (atoms) or put the cursor in it, like Notion.\n const moved = tr.doc.resolve(insertAt).nodeAfter\n if (moved?.isAtom && NodeSelection.isSelectable(moved)) tr.setSelection(NodeSelection.create(tr.doc, insertAt))\n else tr.setSelection(TextSelection.near(tr.doc.resolve(Math.min(insertAt + 1, tr.doc.content.size))))\n\n view.dispatch(tr.scrollIntoView())\n view.focus()\n }\n\n // Auto-scroll the nearest scrollable ancestor (or the window) near the viewport edges.\n let scrollFrame = 0\n let scrollSpeed = 0\n const scroller = (view: EditorView): Element | Window => {\n for (let el = view.dom.parentElement; el; el = el.parentElement) {\n const { overflowY } = getComputedStyle(el)\n if (/(auto|scroll)/.test(overflowY) && el.scrollHeight > el.clientHeight) return el\n }\n return window\n }\n const stopScroll = () => {\n cancelAnimationFrame(scrollFrame)\n scrollFrame = 0\n scrollSpeed = 0\n }\n const updateScroll = (view: EditorView, y: number) => {\n const target = scroller(view)\n const bounds = target === window ? { top: 0, bottom: window.innerHeight } : (target as Element).getBoundingClientRect()\n const fromTop = y - bounds.top\n const fromBottom = bounds.bottom - y\n scrollSpeed = fromTop < SCROLL_ZONE\n ? -SCROLL_SPEED * (1 - fromTop / SCROLL_ZONE)\n : fromBottom < SCROLL_ZONE ? SCROLL_SPEED * (1 - fromBottom / SCROLL_ZONE) : 0\n if (!scrollSpeed) return stopScroll()\n if (scrollFrame) return\n const step = () => {\n if (!scrollSpeed) return\n target.scrollBy({ top: scrollSpeed })\n scrollFrame = requestAnimationFrame(step)\n }\n scrollFrame = requestAnimationFrame(step)\n }\n\n return [\n new Plugin({\n key: blockDropKey,\n // Listen on the document in the capture phase: ProseMirror ignores drag events\n // over node views (callout, image, columns...), and drops in the gutter should work too.\n view: (view) => {\n const onDragOver = (e: DragEvent) => {\n if (!storage.active || !view.dragging) return\n dragStartX ??= e.clientX\n updateScroll(view, e.clientY)\n if (!isNearEditor(view, e)) return hide()\n e.preventDefault()\n e.stopPropagation()\n if (e.dataTransfer) e.dataTransfer.dropEffect = 'move'\n const target = findDropTarget(view, e.clientX, e.clientY)\n if (target) show(target.line)\n else hide()\n }\n const onDrop = (e: DragEvent) => {\n if (!storage.active) return\n storage.active = false\n const target = isNearEditor(view, e) ? findDropTarget(view, e.clientX, e.clientY) : null\n dragStartX = null\n hide()\n stopScroll()\n if (!target) return\n e.preventDefault()\n e.stopPropagation()\n moveBlock(view, target)\n }\n const onDragEnd = () => {\n storage.active = false\n dragStartX = null\n hide()\n stopScroll()\n }\n document.addEventListener('dragover', onDragOver, true)\n document.addEventListener('drop', onDrop, true)\n document.addEventListener('dragend', onDragEnd, true)\n return {\n destroy() {\n document.removeEventListener('dragover', onDragOver, true)\n document.removeEventListener('drop', onDrop, true)\n document.removeEventListener('dragend', onDragEnd, true)\n hide()\n stopScroll()\n },\n }\n },\n }),\n ]\n },\n})\n\n","import { combineTransactionSteps, Extension, getChangedRanges, type JSONContent } from '@tiptap/core'\nimport type { Node as PMNode } from '@tiptap/pm/model'\nimport { Plugin, PluginKey, Selection } from '@tiptap/pm/state'\n\nexport interface BlockIdOptions {\n /** Node types that get an id. */\n types: string[]\n /** Attribute name (rendered as `data-<name>`). */\n attributeName: string\n generate: () => string\n}\n\n/** Above this many id changes, rebuild the doc in one step instead of one step per node. */\nconst BULK_THRESHOLD = 300\n\nexport const uuid = () => (globalThis.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`)\n\n/**\n * Gives every block in a JSON document a unique id before it's loaded — one O(n) pass,\n * so opening large documents doesn't need thousands of id-setting steps.\n */\nexport function assignIds(doc: JSONContent | null, types: string[], generate: () => string = uuid, attr = 'id'): JSONContent | null {\n if (!doc) return doc\n const typeSet = new Set(types)\n const seen = new Set<string>()\n const visit = (node: JSONContent): JSONContent => {\n let out = node\n if (node.type && typeSet.has(node.type)) {\n const id = node.attrs?.[attr]\n if (!id || seen.has(id)) out = { ...node, attrs: { ...node.attrs, [attr]: generate() } }\n seen.add(out.attrs![attr])\n }\n return out.content ? { ...out, content: out.content.map(visit) } : out\n }\n return visit(doc)\n}\n\n/** Rebuilds a node tree with new ids at the given positions (single-step bulk update). */\nfunction rebuild(doc: PMNode, ids: Map<number, string>, attr: string): PMNode {\n const visit = (node: PMNode, pos: number): PMNode => {\n if (node.isText) return node\n const children: PMNode[] = []\n node.forEach((child, offset) => children.push(visit(child, pos + 1 + offset)))\n const id = ids.get(pos)\n const attrs = id ? { ...node.attrs, [attr]: id } : node.attrs\n return node.type.create(attrs, children.length ? children : node.content, node.marks)\n }\n // The doc node itself has no position; its children start at 0.\n const children: PMNode[] = []\n doc.forEach((child, offset) => children.push(visit(child, offset)))\n return doc.type.create(doc.attrs, children)\n}\n\n/**\n * Stable block ids, linear-time. Replaces Tiptap's UniqueID, which is O(n²) on large\n * documents (indexOf-based duplicate search over every id, and position-shifting\n * setNodeMarkup steps). Here: only nodes inserted by the transaction are checked,\n * duplicates use a Set, and ids are written with setNodeAttribute (no position shifts).\n */\nexport const BlockId = Extension.create<BlockIdOptions>({\n name: 'blockId',\n\n addOptions: () => ({ types: [], attributeName: 'id', generate: uuid }),\n\n addGlobalAttributes() {\n const name = this.options.attributeName\n return [{\n types: this.options.types,\n attributes: {\n [name]: {\n default: null,\n keepOnSplit: false,\n parseHTML: (el: HTMLElement) => el.getAttribute(`data-${name}`),\n renderHTML: (attrs: Record<string, any>) => (attrs[name] ? { [`data-${name}`]: attrs[name] } : {}),\n },\n },\n }]\n },\n\n addProseMirrorPlugins() {\n const { types, attributeName: attr, generate } = this.options\n const typeSet = new Set(types)\n\n return [new Plugin({\n key: new PluginKey('blockId'),\n appendTransaction(transactions, oldState, newState) {\n if (!transactions.some(tr => tr.docChanged) || transactions.some(tr => tr.getMeta('blockId:skip'))) return null\n\n // Nodes that start inside a changed range were inserted or rebuilt by this change.\n const transform = combineTransactionSteps(oldState.doc, [...transactions])\n const candidates: { pos: number, id: string | null }[] = []\n for (const { newRange } of getChangedRanges(transform)) {\n newState.doc.nodesBetween(newRange.from, newRange.to, (node, pos) => {\n if (pos >= newRange.from && typeSet.has(node.type.name)) candidates.push({ pos, id: node.attrs[attr] ?? null })\n })\n }\n if (!candidates.length) return null\n\n // Ids already used outside the candidates (built only when a candidate has an id).\n const needsCheck = candidates.some(c => c.id)\n const counts = new Map<string, number>()\n if (needsCheck) {\n newState.doc.descendants((node) => {\n const id = node.attrs[attr]\n if (id && typeSet.has(node.type.name)) counts.set(id, (counts.get(id) ?? 0) + 1)\n })\n }\n\n const inCandidates = new Map<string, number>()\n for (const c of candidates) if (c.id) inCandidates.set(c.id, (inCandidates.get(c.id) ?? 0) + 1)\n\n const updates = new Map<number, string>()\n const kept = new Set<string>()\n for (const c of candidates) {\n // An id already used by an untouched node (e.g. the original of a paste or a\n // duplicate) is replaced; among inserted nodes the first occurrence keeps it.\n const usedElsewhere = !!c.id && (counts.get(c.id) ?? 0) > (inCandidates.get(c.id) ?? 0)\n const repeated = !!c.id && kept.has(c.id)\n if (!c.id || usedElsewhere || repeated) updates.set(c.pos, generate())\n else kept.add(c.id)\n }\n if (!updates.size) return null\n\n const tr = newState.tr\n if (updates.size > BULK_THRESHOLD) {\n // Each attribute step re-validates the parent's whole content, so thousands of\n // them on top-level blocks are O(n²). Rebuild once instead.\n const anchor = newState.selection.from\n tr.replaceWith(0, newState.doc.content.size, rebuild(newState.doc, updates, attr).content)\n tr.setSelection(Selection.near(tr.doc.resolve(Math.min(anchor, tr.doc.content.size))))\n }\n else {\n for (const [pos, id] of updates) tr.setNodeAttribute(pos, attr, id)\n }\n return tr.setMeta('addToHistory', false)\n },\n })]\n },\n})\n","import type { ChainedCommands, Editor } from '@tiptap/core'\nimport type { Node as PMNode } from '@tiptap/pm/model'\nimport type { Component } from 'vue'\nimport type { BlockGroup, EditorMessages } from './locale'\n\n/** A menu entry (slash menu, \"Turn into\") contributed by a block definition. */\nexport interface BlockType {\n /** Stable id, also the key in `messages.blocks`. */\n id: string\n icon: Component\n /** Menu section: a built-in group or any custom label key. */\n group: BlockGroup | (string & {})\n /** Extra search terms (any language). Title and id are searched too. */\n keywords: string[]\n /** Markdown shortcut hint shown on the right of the menu row. */\n shortcut?: string\n /** Applies the block to the current (empty) line — used by the slash menu. */\n insert: (chain: ChainedCommands) => ChainedCommands\n /**\n * Converts a block (already cleared to paragraphs) into this type — used by \"Turn into\".\n * Blocks without it are not offered as a turn-into target.\n */\n turnInto?: (chain: ChainedCommands) => ChainedCommands\n /** Whether `node` is this block type, to mark the current type in menus. */\n matches?: (node: PMNode) => boolean\n}\n\n/** Menu items of the blocks loaded in this editor (see the `blocks` prop). */\nexport function enabledBlocks(editor: Editor): BlockType[] {\n return editor.storage.meiConfig?.items ?? []\n}\n\n/** Helper for `matches`: true when the node has this type name. */\nexport const isNode = (name: string) => (node: PMNode) => node.type.name === name\n\nexport function turnIntoBlocks(editor: Editor): BlockType[] {\n return enabledBlocks(editor).filter(b => b.turnInto)\n}\n\nexport const blockTitle = (messages: EditorMessages, block: BlockType) => messages.blocks[block.id]?.title ?? block.id\n\n/** Label of a menu section (custom groups fall back to their key). */\nexport const groupLabel = (messages: EditorMessages, group: string) => (messages.groups as Record<string, string>)[group] ?? group\n\nconst normalize = (s: string) => s.normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/đ/g, 'd').toLowerCase()\n\n/**\n * Filters blocks by query, best matches first:\n * exact term > a word starting with the query > substring anywhere.\n */\nexport function filterBlocks(blocks: BlockType[], query: string, messages: EditorMessages): BlockType[] {\n const q = normalize(query.trim())\n if (!q) return blocks\n\n const score = (b: BlockType) => {\n const terms = [blockTitle(messages, b), b.id, ...b.keywords].map(normalize)\n if (terms.includes(q)) return 3\n if (terms.some(t => t.split(/\\s+/).some(w => w.startsWith(q)))) return 2\n if (terms.some(t => t.includes(q))) return 1\n return 0\n }\n\n return blocks\n .map((b, i) => ({ b, i, s: score(b) }))\n .filter(x => x.s > 0)\n .sort((a, b) => b.s - a.s || a.i - b.i)\n .map(x => x.b)\n}\n","import { Extension } from '@tiptap/core'\nimport { Plugin, PluginKey, TextSelection } from '@tiptap/pm/state'\nimport { Decoration, DecorationSet } from '@tiptap/pm/view'\nimport { NodeRangeSelection } from '@tiptap/extension-node-range'\nimport { enabledBlocks } from '../block-items'\nimport {\n blockAt, type BlockRange, blocksIn, currentRange, deleteBlocks, duplicateBlocks,\n moveBlocks, rangeBetween, selectBlocks, turnBlocksInto,\n} from '../block-ops'\n\nexport interface BlockSelectionStorage {\n /** Set by the editor UI: opens the ⋮⋮ menu for a range (⌘/). */\n openMenu: ((range: BlockRange) => void) | null\n}\n\ndeclare module '@tiptap/core' {\n interface Storage {\n blockSelection: BlockSelectionStorage\n }\n}\n\n/** ⌘⌥0–8 → block type, like Notion. */\nexport const TURN_INTO_SHORTCUTS: Record<string, string> = {\n 0: 'paragraph',\n 1: 'heading1',\n 2: 'heading2',\n 3: 'heading3',\n 4: 'taskList',\n 5: 'bulletList',\n 6: 'orderedList',\n 7: 'toggle',\n 8: 'codeBlock',\n}\n\nexport const blockSelectionKey = new PluginKey('blockSelection')\n\n/**\n * Notion-style block selection and block shortcuts:\n * - Esc selects the current block; Esc again clears.\n * - Shift+click or dragging a text selection across blocks selects whole blocks.\n * - With blocks selected: ↑/↓ move the selection, Shift+↑/↓ extend it, Enter edits,\n * Backspace/Delete removes them, typing is ignored; ⌘C/⌘X copy/cut blocks.\n * - Anywhere: ⌘⇧↑/↓ move, ⌘D duplicate, ⌘⌥0–8 turn into, ⌘/ open the block menu.\n */\nexport const BlockSelection = Extension.create<object, BlockSelectionStorage>({\n name: 'blockSelection',\n priority: 1000,\n\n addStorage() {\n return { openMenu: null }\n },\n\n addKeyboardShortcuts() {\n const editor = this.editor\n const range = () => currentRange(editor.state)\n // Any open suggestion popup (slash, emoji, mention…) gets Esc first.\n const suggestionOpen = () => editor.state.plugins.some((p) => {\n const st = p.getState(editor.state) as { active?: boolean, query?: unknown } | undefined\n return !!st && typeof st === 'object' && st.active === true && 'query' in st\n })\n const withRange = (fn: (r: BlockRange) => unknown) => () => {\n const r = range()\n if (!r) return false\n fn(r)\n return true\n }\n\n const shortcuts: Record<string, () => boolean> = {\n 'Escape': () => {\n if (suggestionOpen()) return false\n const sel = editor.state.selection\n if (sel instanceof NodeRangeSelection) {\n // Second Esc: leave block mode.\n editor.view.dispatch(editor.state.tr.setSelection(TextSelection.near(editor.state.doc.resolve(sel.to - 1), -1)))\n editor.view.dom.blur()\n return true\n }\n const r = range()\n if (!r) return false\n selectBlocks(editor, r)\n return true\n },\n 'Mod-Shift-ArrowUp': () => !!range() && moveBlocks(editor, range()!, 'up'),\n 'Mod-Shift-ArrowDown': () => !!range() && moveBlocks(editor, range()!, 'down'),\n 'Mod-d': withRange(r => duplicateBlocks(editor, r)),\n 'Mod-/': withRange(r => this.storage.openMenu?.(r)),\n }\n for (const [key, id] of Object.entries(TURN_INTO_SHORTCUTS)) {\n shortcuts[`Mod-Alt-${key}`] = withRange((r) => {\n const block = enabledBlocks(editor).find(b => b.id === id)\n if (block) turnBlocksInto(editor, r, block)\n })\n }\n return shortcuts\n },\n\n addProseMirrorPlugins() {\n const editor = this.editor\n let dragging = false\n\n return [\n new Plugin({\n key: blockSelectionKey,\n props: {\n attributes: (state): Record<string, string> =>\n state.selection instanceof NodeRangeSelection ? { class: 'me-has-block-selection' } : {},\n\n decorations(state) {\n const sel = state.selection\n if (!(sel instanceof NodeRangeSelection)) return null\n const range = { from: sel.from, to: sel.to, depth: sel.depth ?? 0 }\n return DecorationSet.create(state.doc, blocksIn(state.doc, range).map(({ node, pos }) =>\n Decoration.node(pos, pos + node.nodeSize, { class: 'me-block-selected' })))\n },\n\n // Keys while blocks are selected.\n handleKeyDown(view, event) {\n const sel = view.state.selection\n if (!(sel instanceof NodeRangeSelection) || event.metaKey || event.ctrlKey || event.altKey) return false\n const range: BlockRange = { from: sel.from, to: sel.to, depth: sel.depth ?? 0 }\n const { doc } = view.state\n\n if (event.key === 'Backspace' || event.key === 'Delete') {\n deleteBlocks(editor, range)\n return true\n }\n if (event.key === 'Enter') {\n view.dispatch(view.state.tr.setSelection(TextSelection.near(doc.resolve(range.to - 1), -1)))\n return true\n }\n if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {\n const up = event.key === 'ArrowUp'\n // Shift moves the \"head\" block and keeps the anchor; plain arrows move a single block.\n const head = blockAt(doc.resolve(event.shiftKey ? sel.head : up ? sel.from + 1 : sel.to - 1))\n if (!head) return true\n const $edge = doc.resolve(up ? head.pos : head.pos + head.node.nodeSize)\n const sibling = up ? $edge.nodeBefore : $edge.nodeAfter\n if (!sibling) return true\n const siblingPos = up ? head.pos - sibling.nodeSize : head.pos + head.node.nodeSize\n if (!event.shiftKey) {\n selectBlocks(editor, { from: siblingPos, to: siblingPos + sibling.nodeSize, depth: range.depth })\n }\n else {\n view.dispatch(view.state.tr.setSelection(NodeRangeSelection.create(doc, sel.anchor, siblingPos + 1, range.depth)))\n }\n return true\n }\n // Printable keys would replace the blocks; Notion ignores them.\n return event.key.length === 1\n },\n\n handleTextInput: view => view.state.selection instanceof NodeRangeSelection,\n\n handleDOMEvents: {\n // Shift+click extends a block selection (or the cursor's block) to the clicked block.\n mousedown(view, event) {\n dragging = !event.shiftKey\n if (!event.shiftKey) return false\n const hit = view.posAtCoords({ left: event.clientX, top: event.clientY })\n if (!hit) return false\n const sel = view.state.selection\n const range = rangeBetween(view.state.doc, sel instanceof NodeRangeSelection ? sel.from + 1 : sel.anchor, hit.pos)\n if (!range || blocksIn(view.state.doc, range).length < 2) return false\n event.preventDefault()\n selectBlocks(editor, range)\n return true\n },\n },\n },\n\n // A text selection dragged across blocks becomes a block selection on mouseup.\n view: () => {\n const onMouseUp = () => {\n if (!dragging) return\n dragging = false\n const { state } = editor\n const sel = state.selection\n if (!(sel instanceof TextSelection) || sel.empty) return\n const a = blockAt(sel.$from)\n const b = blockAt(sel.$to)\n if (!a || !b || a.pos === b.pos) return\n const range = rangeBetween(state.doc, sel.anchor, sel.head)\n if (range) selectBlocks(editor, range)\n }\n document.addEventListener('mouseup', onMouseUp)\n return { destroy: () => document.removeEventListener('mouseup', onMouseUp) }\n },\n }),\n ]\n },\n})\n\n","import { Extension, type Editor } from '@tiptap/core'\nimport { Fragment, type Node as PMNode, Slice } from '@tiptap/pm/model'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\nimport { dropPoint, ReplaceAroundStep, ReplaceStep } from '@tiptap/pm/transform'\nimport type { EditorView } from '@tiptap/pm/view'\nimport { reactive, shallowReactive } from 'vue'\nimport type { FileBlockOptions, FileKind } from './file-block'\nimport { uuid } from './block-id'\nimport { blockGapAtPoint } from './block-drop'\n\n/** Why an upload placeholder could not become a real image / file. */\nexport type UploadError = 'tooLarge' | 'badType' | 'failed'\n\n/** Local state of a pasted / dropped file while it uploads (never in the document). */\nexport interface PendingUpload {\n /** Kept so \"Retry\" can send it again. */\n file: File\n /** `blob:` URL of an image, shown until the upload resolves. */\n preview: string | null\n /** 0..1, when the uploader reports progress. */\n progress: number\n}\n\nexport interface FileDropStorage {\n /** Pending uploads by the node's `uploadId` attribute. */\n uploads: Map<string, PendingUpload>\n /** Uploads still running, by `uploadId`: settled once their result is written ({@link uploadsSettled}). */\n running: Map<string, Promise<void>>\n /** Local time each other-tab upload (`uploadId`) was first seen here, for `uploadStaleAt` (not reactive). */\n firstSeen: Map<string, number>\n}\n\ndeclare module '@tiptap/core' {\n interface Storage {\n fileDrop: FileDropStorage\n }\n}\n\n/** Formats every browser shows in `<img>`; other `image/*` (HEIC, TIFF…) are refused as `badType`. */\nconst DISPLAYABLE_IMAGES = /^image\\/(png|jpe?g|gif|webp|avif|svg\\+xml|bmp|x-icon|vnd\\.microsoft\\.icon|apng)$/i\n\nconst MB = 1024 * 1024\n\n/** An `uploading` node without a local upload and older than this is shown as interrupted (its tab closed). */\nexport const UPLOAD_STALE_MS = 2 * 60_000\n\n/**\n * How a node's upload looks in this tab:\n * - `local`: this tab owns the file (progress, Delete, Retry on error);\n * - `remote`: another tab is uploading it (message only);\n * - `interrupted`: `uploading` for longer than `UPLOAD_STALE_MS` with nobody here owning it (Delete for editors);\n * - null: no upload.\n */\nexport type UploadState = 'local' | 'remote' | 'interrupted' | null\n\nexport function uploadState(editor: Editor, attrs: Record<string, unknown>, now = Date.now()): UploadState {\n if (pendingUpload(editor, attrs.uploadId)) return 'local'\n if (!attrs.uploading) return null\n return now > uploadStaleAt(editor, attrs, now) ? 'interrupted' : 'remote'\n}\n\n/**\n * When an `uploading` node without a local file becomes interrupted (ms, local clock). `uploadStartedAt` comes from\n * another machine whose clock may differ, so the countdown never starts before this tab first saw the upload:\n * `max(firstSeenHere, min(uploadStartedAt, firstSeenHere)) + UPLOAD_STALE_MS`, i.e. 2 minutes after first seen, fixed. Nodes without an `uploadId` (duplicates,\n * older documents) only use `uploadStartedAt`.\n */\nexport function uploadStaleAt(editor: Editor, attrs: Record<string, unknown>, now = Date.now()): number {\n const started = typeof attrs.uploadStartedAt === 'number' ? attrs.uploadStartedAt : 0\n const id = attrs.uploadId\n const seen = editor.storage.fileDrop?.firstSeen\n if (typeof id !== 'string' || !seen) return Math.min(started, now) + UPLOAD_STALE_MS\n const firstSeen = seen.get(id) ?? now\n if (!seen.has(id)) seen.set(id, firstSeen)\n // max(firstSeen, min(started, firstSeen)): fixed once seen, even when the uploader's clock is ahead.\n return Math.max(firstSeen, Math.min(started, firstSeen)) + UPLOAD_STALE_MS\n}\n\nconst readAsDataUrl = (file: File) => new Promise<string>((resolve, reject) => {\n const reader = new FileReader()\n reader.onload = () => resolve(reader.result as string)\n reader.onerror = () => reject(reader.error)\n reader.readAsDataURL(file)\n})\n\nconst kindOf = (mime: string): FileKind => (mime.startsWith('audio/') ? 'audio' : mime.startsWith('video/') ? 'video' : 'file')\n\nfunction fileBlockOptions(editor: Editor): FileBlockOptions | null {\n return (editor.extensionManager.extensions.find(e => e.name === 'fileBlock')?.options as FileBlockOptions | undefined) ?? null\n}\n\n/** The node carrying `uploadId`, with its position. */\nfunction findUpload(doc: PMNode, uploadId: string): { node: PMNode, pos: number } | null {\n let found: { node: PMNode, pos: number } | null = null\n doc.descendants((node, pos) => {\n if (found) return false\n if (node.attrs.uploadId === uploadId) found = { node, pos }\n return !node.isAtom\n })\n return found as { node: PMNode, pos: number } | null\n}\n\n/**\n * Uploads that outlived their editor (destroyed while uploading: the page was left): still shown as this tab's by\n * an editor opened again on the same document ({@link pendingUpload}), until they settle.\n */\nconst adrift = shallowReactive(new Map<string, PendingUpload>())\n\n/** The parts of a Yjs XML fragment / element used here (Yjs itself stays out of the main chunk). */\ninterface YElementLike {\n getAttribute: (name: string) => unknown\n setAttribute: (name: string, value: unknown) => void\n removeAttribute: (name: string) => void\n}\ninterface YFragmentLike {\n doc: { transact: (fn: () => void, origin?: unknown) => void } | null\n createTreeWalker: (filter: (node: unknown) => boolean) => Iterable<unknown>\n}\n\n/** The Yjs fragment a collaborative editor is bound to (`collaborationExtensions`), or null. */\nfunction collaborationFragment(editor: Editor): YFragmentLike | null {\n const options = editor.extensionManager?.extensions.find(e => e.name === 'collaboration')?.options as\n | { document?: { getXmlFragment: (name: string) => YFragmentLike } | null, field?: string, fragment?: YFragmentLike | null }\n | undefined\n try {\n return options?.fragment ?? options?.document?.getXmlFragment(options.field ?? 'default') ?? null\n }\n catch {\n return null\n }\n}\n\n/** Origin of the writes below: not a y-tiptap origin, so the Yjs undo manager does not track them. */\nconst UPLOAD_ORIGIN = 'meiFileDrop'\n\n/**\n * Writes the upload's result straight into the Yjs document, for an editor destroyed meanwhile: the document\n * outlives the view (an app keeps it open until {@link uploadsSettled}), every editor on it gets the change. A null\n * value removes the attribute (its default then applies). False when the node is gone.\n */\nfunction writeToDocument(fragment: YFragmentLike, uploadId: string, attrs: Record<string, unknown>): boolean {\n const isUpload = (node: unknown) => typeof (node as YElementLike).getAttribute === 'function' && (node as YElementLike).getAttribute('uploadId') === uploadId\n for (const node of fragment.createTreeWalker(isUpload)) {\n const element = node as YElementLike\n const apply = () => {\n for (const [key, value] of Object.entries(attrs)) {\n if (value === null || value === undefined) element.removeAttribute(key)\n else element.setAttribute(key, value)\n }\n }\n if (fragment.doc) fragment.doc.transact(apply, UPLOAD_ORIGIN)\n else apply()\n return true\n }\n return false\n}\n\n/** Updates the upload node's attributes, outside the undo history (the insertion is the undo step). */\nfunction setUploadAttrs(editor: Editor, uploadId: string, attrs: Record<string, unknown>): boolean {\n if (editor.isDestroyed) return false\n const hit = findUpload(editor.state.doc, uploadId)\n if (!hit) return false\n const tr = editor.state.tr.setNodeMarkup(hit.pos, undefined, { ...hit.node.attrs, ...attrs })\n editor.view.dispatch(tr.setMeta('addToHistory', false))\n return true\n}\n\nfunction dropEntry(editor: Editor, uploadId: string) {\n const uploads = editor.storage.fileDrop?.uploads\n const entry = uploads?.get(uploadId) ?? adrift.get(uploadId)\n if (!entry) return\n uploads?.delete(uploadId)\n adrift.delete(uploadId)\n // The final URL may still be loading: keep the preview a little longer.\n if (entry.preview) setTimeout(() => URL.revokeObjectURL(entry.preview!), 30_000)\n}\n\n/** The pending upload of a node (reactive), or null (another tab's upload, or none). Also one started by an earlier\n * editor of this page, destroyed while it uploads. */\nexport function pendingUpload(editor: Editor, uploadId: unknown): PendingUpload | null {\n if (typeof uploadId !== 'string') return null\n return editor.storage.fileDrop?.uploads.get(uploadId) ?? adrift.get(uploadId) ?? null\n}\n\n/**\n * Uploads running per Yjs document (the collaboration `Y.Doc`), whichever editor started them: an editor opened again\n * on that document (a remount, a page left and opened again) still counts the uploads of the editors before it.\n */\nconst docRuns = new WeakMap<object, Map<string, Promise<void>>>()\n\nconst docOf = (editor: Editor): object | null => collaborationFragment(editor)?.doc ?? null\n\n/**\n * Resolves once every upload running for this editor has written its result (its `src`, or its error), also after\n * the editor is destroyed; null when none is running. Counts the uploads this editor started and, for a collaborative\n * editor, every upload still running on its Yjs document (started by an earlier editor of it). A collaborative editor\n * destroyed meanwhile writes the result into its Yjs document: keep that document open (and saved, synced) until\n * then, e.g. close it in `.finally()`. A plain (`v-model`) editor destroyed meanwhile cannot keep the result.\n */\nexport function uploadsSettled(editor: Editor): Promise<void> | null {\n const runs = new Set(editor.storage.fileDrop?.running.values() ?? [])\n const doc = docOf(editor)\n for (const run of (doc && docRuns.get(doc)?.values()) || []) runs.add(run)\n if (!runs.size) return null\n return Promise.allSettled([...runs]).then(() => {})\n}\n\n/**\n * Validates and uploads the file of a placeholder node, then sets its `src` (or `error`).\n * Also used by the node views' \"Retry\" button.\n */\nexport function runUpload(editor: Editor, uploadId: string): Promise<void> {\n const running = editor.storage.fileDrop?.running\n const current = running?.get(uploadId)\n if (current) return current\n const doc = docOf(editor)\n let onDoc = doc ? docRuns.get(doc) : undefined\n if (doc && !onDoc) docRuns.set(doc, (onDoc = new Map()))\n const run = upload(editor, uploadId).finally(() => {\n if (running?.get(uploadId) === run) running.delete(uploadId)\n if (onDoc?.get(uploadId) === run) onDoc.delete(uploadId)\n })\n running?.set(uploadId, run)\n onDoc?.set(uploadId, run)\n return run\n}\n\nasync function upload(editor: Editor, uploadId: string): Promise<void> {\n const entry = pendingUpload(editor, uploadId)\n const hit = findUpload(editor.state.doc, uploadId)\n if (!entry || !hit) return\n // Captured now: read after an await, the editor may be gone.\n const fragment = collaborationFragment(editor)\n /** The result, through the editor while it lives, else straight into its document. */\n const finish = (attrs: Record<string, unknown>) => {\n if (!editor.isDestroyed) return setUploadAttrs(editor, uploadId, attrs)\n return fragment ? writeToDocument(fragment, uploadId, attrs) : false\n }\n const { file } = entry\n const isImage = hit.node.type.name === 'image'\n const config = editor.storage.meiConfig\n const fileOptions = fileBlockOptions(editor)\n const maxMb = isImage ? config.maxImageSize : fileOptions?.maxSize ?? config.maxImageSize\n\n if (isImage && !DISPLAYABLE_IMAGES.test(file.type)) return void setUploadAttrs(editor, uploadId, { uploading: false, error: 'badType' })\n if (file.size > maxMb * MB) return void setUploadAttrs(editor, uploadId, { uploading: false, error: 'tooLarge' })\n\n entry.progress = 0\n setUploadAttrs(editor, uploadId, { uploading: true, uploadStartedAt: Date.now(), error: null })\n const onProgress = (fraction: number) => {\n entry.progress = Math.min(1, Math.max(0, fraction))\n }\n try {\n let src: string\n if (isImage) {\n const upload = config.uploadImage\n src = upload ? await upload(file, onProgress) : await readAsDataUrl(file)\n }\n else {\n const kind = (hit.node.attrs.kind ?? 'file') as FileKind\n src = fileOptions?.upload ? await fileOptions.upload(file, kind, onProgress) : await readAsDataUrl(file)\n }\n const done = finish({ src, uploading: false, uploadStartedAt: null, error: null, uploadId: null })\n if (done || editor.isDestroyed || !findUpload(editor.state.doc, uploadId)) dropEntry(editor, uploadId)\n }\n catch {\n finish({ uploading: false, error: 'failed' })\n // Nobody is left to retry it here: the block shows the failure (Delete) and the file is let go.\n if (editor.isDestroyed) dropEntry(editor, uploadId)\n }\n}\n\n/** Builds one placeholder node per file (images → `image`, others → `fileBlock`), in order. */\nfunction placeholders(editor: Editor, files: File[]): PMNode[] {\n const { schema } = editor\n const nodes: PMNode[] = []\n for (const file of files) {\n const uploadId = uuid()\n const isImage = file.type.startsWith('image/') && !!schema.nodes.image\n const type = isImage ? schema.nodes.image : schema.nodes.fileBlock\n if (!type) continue\n const attrs = isImage\n ? { src: null, alt: file.name, uploading: true, uploadStartedAt: Date.now(), uploadId }\n : { src: null, name: file.name, size: file.size, mime: file.type, kind: kindOf(file.type), uploading: true, uploadStartedAt: Date.now(), uploadId }\n const preview = isImage && DISPLAYABLE_IMAGES.test(file.type) ? URL.createObjectURL(file) : null\n editor.storage.fileDrop.uploads.set(uploadId, reactive({ file, preview, progress: 0 }))\n nodes.push(type.create(attrs))\n }\n return nodes\n}\n\nfunction startAll(editor: Editor, nodes: PMNode[]) {\n for (const node of nodes) void runUpload(editor, node.attrs.uploadId as string)\n}\n\n/** Files of a clipboard / drop, in order; null when there are none. */\nfunction filesOf(data: DataTransfer | null): File[] | null {\n if (!data) return null\n let files = Array.from(data.files ?? [])\n if (!files.length && data.items) files = Array.from(data.items).filter(i => i.kind === 'file').map(i => i.getAsFile()).filter((f): f is File => !!f)\n return files.length ? files : null\n}\n\n/**\n * True when the clipboard's HTML carries content of its own (text, or images on the web): the regular paste keeps\n * it (Word / web pages also put a picture of the selection in `files`). HTML that is only images with local\n * sources (`file:`, `blob:`) — a copied image — gives way to the files.\n */\nfunction htmlHasContent(html: string): boolean {\n if (!html.trim()) return false\n const doc = new DOMParser().parseFromString(html, 'text/html')\n if ((doc.body.textContent ?? '').trim()) return true\n return Array.from(doc.querySelectorAll('img')).some(img => /^https?:/i.test(img.getAttribute('src') ?? ''))\n}\n\n/** Local images in pasted HTML (Word: `<img src=\"file:///…\">`), whose bytes may be in the clipboard's files. */\nconst LOCAL_IMG = /<img\\b[^>]*?\\ssrc\\s*=\\s*([\"'])file:[^\"']*\\1/gi\n\n/** True when a step inserts a node carrying an `uploadId` (a duplicate or a paste of a placeholder). */\nfunction insertsUpload(steps: readonly unknown[]): boolean {\n return steps.some((step) => {\n if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep)) return false\n let found = false\n // Image and file blocks never sit inside text blocks: skip their (large) inline content.\n step.slice.content.descendants((n) => {\n if (n.attrs.uploadId) found = true\n return !found && !n.isAtom && !n.isTextblock\n })\n return found\n })\n}\n\n/**\n * True for a transaction made by y-tiptap's sync plugin (remote changes, initial render): any meta of a\n * `PluginKey('y-sync')` (`y-sync$`, or `y-sync$1`… when the module is loaded twice) with `isChangeOrigin`. Read by key\n * name so Yjs stays out of the main chunk. `Transaction.meta` is internal: when it can't be read, the transaction\n * counts as remote (the cleanup below then skips it, never the reverse).\n */\nfunction isSyncTransaction(tr: { getMeta: (key: string) => unknown }): boolean {\n const meta = (tr as unknown as { meta?: unknown }).meta\n if (!meta || typeof meta !== 'object') return true\n return Object.keys(meta).some(key => key.startsWith('y-sync$') && !!(tr.getMeta(key) as { isChangeOrigin?: boolean } | undefined)?.isChangeOrigin)\n}\n\nconst isAccepted = (editor: Editor, file: File) => (file.type.startsWith('image/') ? !!editor.schema.nodes.image : !!editor.schema.nodes.fileBlock)\n\n/**\n * Paste or drop images and files anywhere in the editor: each file becomes an image block (with an instant preview)\n * or a file block, uploaded through `uploadImage` / `fileBlock.upload`. Failures stay on the block with a Retry.\n * Runs before `markdownPaste`; pastes with text or web images keep the regular path.\n */\nexport const FileDrop = Extension.create<Record<string, never>, FileDropStorage>({\n name: 'fileDrop',\n // Above markdownPaste (default 100): files win over the clipboard's text/plain (e.g. Finder's file name).\n priority: 110,\n\n addStorage() {\n return { uploads: shallowReactive(new Map<string, PendingUpload>()), running: new Map<string, Promise<void>>(), firstSeen: new Map<string, number>() }\n },\n\n onDestroy() {\n // Uploads still running finish without the editor (see runUpload): their file and preview stay until then.\n for (const [id, entry] of this.storage.uploads) {\n if (this.storage.running.has(id)) adrift.set(id, entry)\n else if (entry.preview) URL.revokeObjectURL(entry.preview)\n }\n this.storage.uploads.clear()\n this.storage.firstSeen.clear()\n },\n\n addProseMirrorPlugins() {\n const editor = this.editor\n /** Images for the `file:` sources of the HTML being pasted (Word), consumed by `transformPasted`. */\n let wordImages: { nonce: string, nodes: PMNode[] } | null = null\n const insert = (view: EditorView, files: File[], at: number | null) => {\n const nodes = placeholders(editor, files)\n if (!nodes.length) return false\n const slice = new Slice(Fragment.from(nodes), 0, 0)\n let tr = view.state.tr\n if (at === null) tr = tr.replaceSelection(slice)\n else {\n const pos = dropPoint(tr.doc, at, slice) ?? at\n tr = tr.replace(pos, pos, slice)\n }\n view.dispatch(tr.scrollIntoView())\n startAll(editor, nodes)\n return true\n }\n return [new Plugin({\n key: new PluginKey('fileDrop'),\n // A node-level copy of a placeholder (duplicate, copy inside the editor) gets a state of its own: its\n // `uploadId` belongs to the original. Without a local file it shows as interrupted (Delete), never stuck.\n appendTransaction: (trs, _old, state) => {\n if (!trs.some(tr => tr.docChanged && !isSyncTransaction(tr) && insertsUpload(tr.steps))) return null\n const seen = new Set<string>()\n const tr = state.tr\n state.doc.descendants((node, pos) => {\n const id = node.attrs.uploadId\n if (typeof id === 'string') {\n if (seen.has(id)) tr.setNodeMarkup(pos, undefined, { ...node.attrs, uploadId: null, ...(node.attrs.uploading ? { uploadStartedAt: 0 } : {}) })\n seen.add(id)\n }\n return !node.isAtom && !node.isTextblock\n })\n return tr.docChanged ? tr.setMeta('addToHistory', false) : null\n },\n props: {\n handlePaste: (view, event) => {\n if (!editor.isEditable || wordImages) return false\n const data = event.clipboardData\n const files = filesOf(data)?.filter(f => isAccepted(editor, f))\n if (!files?.length) return false\n const html = data!.getData('text/html')\n if (htmlHasContent(html)) {\n // Word: local images (`file:` sources) whose bytes are in `files`. Paste the HTML with those images\n // swapped (in order) for upload placeholders; the text stays.\n const images = files.filter(f => f.type.startsWith('image/'))\n if (!images.length || !editor.schema.nodes.image || html.search(LOCAL_IMG) < 0) return false\n const nonce = uuid()\n let i = 0\n const marked = html.replace(LOCAL_IMG, m => m.replace(/\\ssrc\\s*=\\s*([\"'])file:[^\"']*\\1/i, ` src=\"#me-upload-${nonce}-${i++}\"`))\n wordImages = { nonce, nodes: placeholders(editor, images.slice(0, i)) }\n const { nodes } = wordImages\n try {\n view.pasteHTML(marked, event)\n }\n finally {\n wordImages = null\n }\n // Placeholders that did not make it into the document (fewer images in the HTML) are dropped.\n for (const node of nodes) {\n if (findUpload(view.state.doc, node.attrs.uploadId as string)) void runUpload(editor, node.attrs.uploadId as string)\n else dropEntry(editor, node.attrs.uploadId as string)\n }\n return true\n }\n // A text selection is replaced, like Notion.\n return insert(view, files, null)\n },\n transformPasted: (slice) => {\n if (!wordImages) return slice\n const { nonce, nodes } = wordImages\n const prefix = `#me-upload-${nonce}-`\n const swap = (fragment: Fragment): Fragment => {\n const out: PMNode[] = []\n fragment.forEach((node) => {\n const src = node.type.name === 'image' ? node.attrs.src : null\n if (typeof src === 'string' && src.startsWith(prefix)) {\n const placeholder = nodes[Number(src.slice(prefix.length))]\n // More `file:` images than files: an empty image block (as before).\n out.push(placeholder ?? node.type.create({ ...node.attrs, src: null }))\n }\n else out.push(node.isLeaf ? node : node.copy(swap(node.content)))\n })\n return Fragment.from(out)\n }\n return new Slice(swap(slice.content), slice.openStart, slice.openEnd)\n },\n handleDrop: (view, event, _slice, moved) => {\n if (!editor.isEditable || moved || view.dragging) return false\n const files = filesOf(event.dataTransfer)?.filter(f => isAccepted(editor, f))\n if (!files?.length) return false\n const coords = view.posAtCoords({ left: event.clientX, top: event.clientY })\n event.preventDefault()\n // Over node-view gaps and the gutter, posAtCoords finds nothing: use the block geometry (as BlockDrop).\n const containers = (editor.extensionManager.extensions.find(e => e.name === 'blockDrop')?.options as { containers?: string[] } | undefined)?.containers\n const at = coords?.pos ?? blockGapAtPoint(view, event.clientX, event.clientY, containers)\n return insert(view, files, at ?? view.state.selection.from)\n },\n },\n })]\n },\n})\n","/**\n * Which `data:` URLs a block may load: `image` (only `data:image/*`), `any`, or `none`.\n */\nexport type DataUrlPolicy = 'image' | 'any' | 'none'\n\n/**\n * URLs from document content (pasted, synced, imported) before they reach `src`, `href` or\n * `window.open`: http(s), `blob:`, URLs without a scheme and the allowed `data:` URLs. Anything\n * else — `javascript:`, `data:text/html`, `vbscript:`, URLs with control characters — gives `null`.\n *\n * URLs without a scheme take the page's: paths (`/api/v1/files/<id>`, `a.png`) are same-origin,\n * while `//cdn.example.com/a.png` (and `\\\\host`, `/\\host`, which browsers read the same way) are\n * http(s) URLs on another host — as safe as any https URL, but not same-origin. Use `isSameOrigin`\n * when that matters.\n */\nexport function safeUrl(src: unknown, data: DataUrlPolicy = 'none'): string | null {\n if (typeof src !== 'string') return null\n const url = src.trim()\n // Browsers drop tabs / newlines inside URLs (\"java\\tscript:\"), so refuse any control character.\n // eslint-disable-next-line no-control-regex\n if (!url || /[\\u0000-\\u001F\\u007F]/.test(url)) return null\n const scheme = /^([a-z][a-z\\d+.-]*):/i.exec(url)?.[1]?.toLowerCase()\n if (!scheme) return url // relative or protocol-relative: same scheme as the page\n if (scheme === 'http' || scheme === 'https' || scheme === 'blob') return url\n if (scheme === 'data') {\n if (data === 'any') return url\n if (data === 'image' && /^data:image\\/[a-z\\d.+-]+[;,]/i.test(url)) return url\n }\n return null\n}\n\n/** True when `url` (resolved against the page) is on the page's origin. */\nexport function isSameOrigin(url: string, base: string = globalThis.location?.href ?? 'http://localhost/'): boolean {\n try {\n return new URL(url, base).origin === new URL(base).origin\n }\n catch {\n return false\n }\n}\n\n/** True when `url` (resolved against the page) is an http(s) URL. */\nexport function isWebUrl(url: string, base: string = globalThis.location?.href ?? 'http://localhost/'): boolean {\n try {\n return /^https?:$/.test(new URL(url, base).protocol)\n }\n catch {\n return false\n }\n}\n","import { Extension, type JSONContent } from '@tiptap/core'\nimport type { Schema } from '@tiptap/pm/model'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\nimport { safeUrl } from '../safe-url'\n\n/**\n * Pasting Markdown as plain text (from a chat, a README, an LLM answer…) gives blocks instead of\n * one paragraph per line (KS-BUG-11): headings, bullet / numbered / task lists (nested by\n * indentation), quotes, fenced code, dividers, and inline bold, italic, strike, code and links\n * (bare http(s) URLs too). Tiptap's paste rules are not run on the result: they would undo\n * escapes (`\\\\*x\\\\*`) and the word rules (`__init__.py`).\n *\n * Converted only when the text clearly is Markdown (`looksLikeMarkdown`), at most\n * `MARKDOWN_PASTE_MAX` characters, never inside a code block, never for \"paste as plain text\"\n * (Shift+Mod+V) and never when the clipboard also has HTML. The parsers are linear in the input\n * (no backtracking regexes, bounded nesting), so a pasted text can't freeze the tab.\n */\n\n/** Longer plain-text pastes are never converted. */\nexport const MARKDOWN_PASTE_MAX = 100 * 1024\n/** Deeper quote / list / emphasis nesting is flattened (or kept as text) at this depth. */\nconst MAX_DEPTH = 8\n\n// ---------------------------------------------------------------------------------------------\n// Lines\n\ninterface ListLine { indent: number, ordered: boolean, start: number, task: boolean | null, text: string }\n\ntype Line =\n | { kind: 'blank' }\n | { kind: 'fence', marker: string, info: string }\n | { kind: 'heading', level: number, text: string }\n | { kind: 'hr' }\n | { kind: 'quote' }\n | { kind: 'list', item: ListLine }\n | { kind: 'text' }\n\nconst isSpace = (c: string | undefined) => c === ' ' || c === '\\t'\nconst isDigit = (c: string | undefined) => c !== undefined && c >= '0' && c <= '9'\n\n/** Indentation width (tab = 4) and the index of the first other character. */\nfunction indentOf(line: string): [indent: number, at: number] {\n let indent = 0\n let at = 0\n while (at < line.length && isSpace(line[at])) indent += line[at++] === '\\t' ? 4 : 1\n return [indent, at]\n}\n\n/** Heading text without the optional closing `#`s (`## Title ##`). */\nfunction headingText(rest: string): string {\n let end = rest.length\n while (end > 0 && isSpace(rest[end - 1])) end--\n let hashes = end\n while (hashes > 0 && rest[hashes - 1] === '#') hashes--\n if (hashes < end && (hashes === 0 || isSpace(rest[hashes - 1]))) {\n end = hashes\n while (end > 0 && isSpace(rest[end - 1])) end--\n }\n return rest.slice(0, end)\n}\n\nfunction listItem(line: string, indent: number, at: number): ListLine | null {\n let i = at\n let ordered = false\n let start = 1\n if (line[i] === '-' || line[i] === '*' || line[i] === '+') {\n i++\n }\n else {\n const digits = i\n while (i - digits < 4 && isDigit(line[i])) i++\n // At most 3 digits: \"2024. A great year\" stays a sentence.\n if (i === digits || i - digits > 3 || (line[i] !== '.' && line[i] !== ')')) return null\n ordered = true\n start = Number(line.slice(digits, i))\n i++\n }\n if (!isSpace(line[i])) return null\n while (isSpace(line[i])) i++\n let task: boolean | null = null\n if (!ordered && line[i] === '[' && line[i + 2] === ']' && isSpace(line[i + 3]) && ' xX'.includes(line[i + 1] ?? '-')) {\n task = line[i + 1] !== ' '\n i += 4\n while (isSpace(line[i])) i++\n }\n const text = line.slice(i)\n return text.trim() ? { indent, ordered, start, task, text } : null\n}\n\nfunction classify(line: string): Line {\n const [indent, at] = indentOf(line)\n if (at === line.length) return { kind: 'blank' }\n const c = line[at]!\n if (indent < 4) {\n if ((c === '`' || c === '~') && line.startsWith(c.repeat(3), at)) {\n let end = at\n while (line[end] === c) end++\n const info = line.slice(end).trim()\n const space = info.search(/[ \\t]/)\n return { kind: 'fence', marker: line.slice(at, end), info: space === -1 ? info : info.slice(0, space) }\n }\n if (c === '#') {\n let end = at\n while (line[end] === '#' && end - at < 7) end++\n const level = end - at\n if (level <= 6 && isSpace(line[end])) {\n const text = headingText(line.slice(end + 1))\n if (text.trim()) return { kind: 'heading', level, text: text.trim() }\n }\n }\n if (c === '-' || c === '*' || c === '_') {\n let n = 0\n let only = true\n for (let i = at; i < line.length && only; i++) {\n if (line[i] === c) n++\n else if (!isSpace(line[i])) only = false\n }\n if (only && n >= 3) return { kind: 'hr' }\n }\n if (c === '>') return { kind: 'quote' }\n }\n const item = listItem(line, indent, at)\n return item ? { kind: 'list', item } : { kind: 'text' }\n}\n\nconst splitLines = (text: string) => text.replace(/\\r\\n?/g, '\\n').split('\\n')\n\nconst closesFence = (line: Line, open: string) => line.kind === 'fence' && !line.info && line.marker[0] === open[0] && line.marker.length >= open.length\n\n/**\n * True when `text` clearly is Markdown: a heading, a closed code fence, a task item, or two list\n * items of the same kind in a row. A lone \"- Alice\" signature or \"1) apples\" is not enough.\n */\nexport function looksLikeMarkdown(text: string): boolean {\n if (text.length > MARKDOWN_PASTE_MAX) return false\n let openFence: string | null = null\n let previousList: boolean | null = null // previous non-blank line was a list item: ordered?\n for (const raw of splitLines(text)) {\n const line = classify(raw)\n if (openFence !== null) {\n if (closesFence(line, openFence)) return true\n continue\n }\n if (line.kind === 'blank') continue\n if (line.kind === 'heading') return true\n if (line.kind === 'fence') {\n openFence = line.marker\n continue\n }\n if (line.kind === 'list') {\n if (line.item.task !== null || previousList === line.item.ordered) return true\n previousList = line.item.ordered\n continue\n }\n previousList = null\n }\n return false\n}\n\n// ---------------------------------------------------------------------------------------------\n// Inline\n\ntype Mark = { type: string, attrs?: Record<string, unknown> }\nconst OPEN_AFTER = '([{\\'\"'\nconst CLOSE_BEFORE = '.,;:!?)]}\\'\"'\nconst ESCAPABLE = '\\\\`*_~[]()#>!-'\nconst isWs = (c: string | undefined) => c === undefined || c === ' ' || c === '\\t' || c === '\\n' || c === ' '\nconst isWord = (c: string | undefined) => c !== undefined && /[\\p{L}\\p{N}_]/u.test(c)\nconst EMPHASIS: [delimiter: string, mark: string][] = [['**', 'bold'], ['__', 'bold'], ['~~', 'strike'], ['*', 'italic'], ['_', 'italic']]\n\n/**\n * Next match of `needle` at or after `from`, optionally passing `valid`. Queries for one key come\n * in increasing `from` order, so the last answer is reused: the whole scan stays linear even\n * with thousands of unmatched `[`, `` ` `` or `*`.\n */\nfunction finder(text: string) {\n const last = new Map<string, number>()\n return (key: string, needle: string, from: number, valid?: (i: number) => boolean): number => {\n const cached = last.get(key)\n if (cached !== undefined && (cached === -1 || cached >= from)) return cached\n let i = text.indexOf(needle, from)\n while (i !== -1 && valid && !valid(i)) i = text.indexOf(needle, i + 1)\n last.set(key, i)\n return i\n }\n}\n\n/** End of a bare URL starting at `start`: up to whitespace, without trailing punctuation. */\nfunction urlEnd(text: string, start: number): number {\n let end = start\n while (end < text.length && !isWs(text[end]) && text[end] !== '<') end++\n while (end > start && CLOSE_BEFORE.includes(text[end - 1]!)) {\n // Keep a closing parenthesis that belongs to the URL (`…/Foo_(bar)`).\n if (text[end - 1] === ')' && text.slice(start, end).split('(').length > text.slice(start, end).split(')').length - 1) break\n end--\n }\n return end\n}\n\n/**\n * Inline Markdown → text nodes with marks (bold, italic, strike, code, link), bare http(s) URLs\n * linked. Linear time; emphasis nested deeper than MAX_DEPTH stays text.\n */\nexport function parseInline(text: string, marks: Mark[] = [], inLink = false, depth = 0): JSONContent[] {\n const out: JSONContent[] = []\n let buf = ''\n const flush = () => {\n if (!buf) return\n const last = out.at(-1)\n if (last?.text !== undefined && JSON.stringify(last.marks ?? []) === JSON.stringify(marks)) last.text += buf\n else out.push(marks.length ? { type: 'text', text: buf, marks } : { type: 'text', text: buf })\n buf = ''\n }\n const next = finder(text)\n // An emphasis closer follows a non-space and ends a word: `__init__.py`, `2*3*4` and\n // `snake_case` stay text.\n const closer = (len: number) => (i: number) => !isWs(text[i - 1]) && text[i - 1] !== text[i]\n && (isWs(text[i + len]) || (CLOSE_BEFORE.includes(text[i + len]!) && !isWord(text[i + len + 1])))\n\n let i = 0\n while (i < text.length) {\n const c = text[i]!\n if (c === '\\\\' && ESCAPABLE.includes(text[i + 1] ?? '\\0')) {\n buf += text[i + 1]\n i += 2\n continue\n }\n if (c === '`') {\n const end = next('`', '`', i + 1)\n if (end > i + 1) {\n flush()\n out.push({ type: 'text', text: text.slice(i + 1, end), marks: [...marks, { type: 'code' }] })\n i = end + 1\n continue\n }\n }\n if (c === '[' && !inLink) {\n const close = next(']', ']', i + 1)\n if (close > i + 1 && text[close + 1] === '(') {\n const paren = next(')', ')', close + 2)\n if (paren !== -1) {\n const inside = text.slice(close + 2, paren).trim()\n const space = inside.search(/\\s/)\n const url = space === -1 ? inside : inside.slice(0, space)\n const title = space === -1 ? '' : inside.slice(space).trim()\n if (url && (!title || (title.length > 1 && title[0] === '\"' && title.at(-1) === '\"' && !title.slice(1, -1).includes('\"')))) {\n flush()\n const href = safeUrl(url)\n out.push(...parseInline(text.slice(i + 1, close), href ? [...marks, { type: 'link', attrs: { href } }] : marks, true, depth + 1))\n i = paren + 1\n continue\n }\n }\n }\n }\n // Bare URLs become links here (paste rules aren't run: they'd undo escapes and word rules).\n if (c === 'h' && !inLink && (i === 0 || !isWord(text[i - 1])) && (text.startsWith('https://', i) || text.startsWith('http://', i))) {\n const end = urlEnd(text, i)\n const url = text.slice(i, end)\n const href = /^https?:\\/\\/[^/?#\\s]/.test(url) ? safeUrl(url) : null\n if (href) {\n flush()\n out.push({ type: 'text', text: url, marks: [...marks, { type: 'link', attrs: { href } }] })\n i = end\n continue\n }\n }\n if (c === '*' || c === '_' || c === '~') {\n const delimiter = depth < MAX_DEPTH ? EMPHASIS.find(([d]) => text.startsWith(d, i)) : undefined\n // Opens at a word start, before a non-space.\n if (delimiter && (i === 0 || isWs(text[i - 1]) || OPEN_AFTER.includes(text[i - 1]!)) && !isWs(text[i + delimiter[0].length])) {\n const [d, type] = delimiter\n const end = next(`em${d}`, d, i + d.length + 1, closer(d.length))\n if (end !== -1) {\n flush()\n // `*_*x*_*`: a mark already applied isn't added twice (ProseMirror refuses that).\n const inner = marks.some(m => m.type === type) ? marks : [...marks, { type }]\n out.push(...parseInline(text.slice(i + d.length, end), inner, inLink, depth + 1))\n i = end + d.length\n continue\n }\n }\n // Not a delimiter here: keep the whole run as text.\n let j = i\n while (text[j] === c) j++\n buf += text.slice(i, j)\n i = j\n continue\n }\n buf += c\n i++\n }\n flush()\n return out\n}\n\n// ---------------------------------------------------------------------------------------------\n// Blocks\n\nconst paragraph = (text: string): JSONContent => {\n const content = parseInline(text)\n return content.length ? { type: 'paragraph', content } : { type: 'paragraph' }\n}\n\n/** Nested lists from consecutive list items, without recursion (nesting capped at MAX_DEPTH). */\nfunction buildList(items: ListLine[]): JSONContent[] {\n const root: JSONContent[] = []\n const stack: { indent: number, container: JSONContent[], list: JSONContent }[] = []\n for (const line of items) {\n while (stack.length && line.indent < stack.at(-1)!.indent) stack.pop()\n const type = line.task !== null ? 'taskList' : line.ordered ? 'orderedList' : 'bulletList'\n let top = stack.at(-1)\n if (top && line.indent > top.indent && stack.length < MAX_DEPTH) {\n const parent = top.list.content!.at(-1)!\n const list: JSONContent = { type, content: [] }\n parent.content!.push(list)\n top = { indent: line.indent, container: parent.content!, list }\n stack.push(top)\n }\n if (!top) {\n const list: JSONContent = { type, content: [] }\n root.push(list)\n top = { indent: line.indent, container: root, list }\n stack.push(top)\n }\n if (top.list.type !== type) {\n top.list = { type, content: [] }\n top.container.push(top.list)\n }\n if (type === 'orderedList' && !top.list.content!.length && line.start !== 1) top.list.attrs = { start: line.start }\n const item: JSONContent = { type: type === 'taskList' ? 'taskItem' : 'listItem', content: [paragraph(line.text)] }\n if (type === 'taskList') item.attrs = { checked: !!line.task }\n top.list.content!.push(item)\n }\n return root\n}\n\n/** Removes one quote marker (`> `), or all of them (`>>> x` → `x`). */\nfunction unquote(line: string, all: boolean): string {\n let at = indentOf(line)[1]\n do {\n at++ // the '>'\n if (line[at] === ' ') at++\n if (!all) break\n while (isSpace(line[at])) at++\n } while (line[at] === '>')\n return line.slice(at)\n}\n\n/** Block Markdown → Tiptap JSON blocks (types are mapped to the schema by `fitToSchema`). */\nexport function markdownToBlocks(markdown: string, depth = 0): JSONContent[] {\n const lines = splitLines(markdown)\n const kinds = lines.map(classify)\n const blocks: JSONContent[] = []\n for (let i = 0; i < lines.length;) {\n const kind = kinds[i]!\n if (kind.kind === 'fence') {\n const body: string[] = []\n i++\n while (i < lines.length && !closesFence(kinds[i]!, kind.marker)) body.push(lines[i++]!)\n i++ // closing fence\n const text = body.join('\\n')\n blocks.push({ type: 'codeBlock', attrs: { language: /^[\\w+#.-]{1,32}$/.test(kind.info) ? kind.info : null }, content: text ? [{ type: 'text', text }] : [] })\n continue\n }\n if (kind.kind === 'heading') {\n const content = parseInline(kind.text)\n blocks.push({ type: 'heading', attrs: { level: Math.min(3, kind.level) }, ...(content.length ? { content } : {}) })\n i++\n continue\n }\n if (kind.kind === 'hr') {\n blocks.push({ type: 'horizontalRule' })\n i++\n continue\n }\n if (kind.kind === 'quote') {\n const quoted: string[] = []\n const flatten = depth + 1 >= MAX_DEPTH\n while (i < lines.length && kinds[i]!.kind === 'quote') quoted.push(unquote(lines[i++]!, flatten))\n const content = flatten ? quoted.filter(l => l.trim()).map(l => paragraph(l.trim())) : markdownToBlocks(quoted.join('\\n'), depth + 1)\n blocks.push({ type: 'blockquote', content: content.length ? content : [{ type: 'paragraph' }] })\n continue\n }\n if (kind.kind === 'list') {\n // A lone numbered line not starting at 1 (\"7) and so on\") stays a paragraph.\n const following = kinds[i + 1]\n const lone = kind.item.ordered && kind.item.start !== 1 && !(following?.kind === 'list' && following.item.ordered)\n if (!lone) {\n const items: ListLine[] = []\n while (i < lines.length) {\n const k = kinds[i]!\n if (k.kind === 'list') items.push(k.item)\n else if (k.kind === 'blank' && items.length && kinds[i + 1]?.kind === 'list') { /* loose list */ }\n else if (k.kind === 'text' && items.length && isSpace(lines[i]![0])) items.at(-1)!.text += ` ${lines[i]!.trim()}`\n else break\n i++\n }\n blocks.push(...buildList(items))\n continue\n }\n }\n // Text: one paragraph per line, like a plain-text paste (line breaks are kept).\n if (kind.kind !== 'blank') blocks.push(paragraph(lines[i]!.trim()))\n i++\n }\n return blocks\n}\n\n/** Replaces node / mark types the editor doesn't have (e.g. no task lists loaded) with plain ones. */\nexport function fitToSchema(node: JSONContent, schema: Schema): JSONContent {\n const map: Record<string, string> = { taskList: 'bulletList', taskItem: 'listItem' }\n let type = node.type!\n if (type !== 'text' && !schema.nodes[type]) type = schema.nodes[map[type] ?? ''] ? map[type]! : 'paragraph'\n const out: JSONContent = { ...node, type }\n if (type !== node.type) delete out.attrs\n if (type === 'paragraph' && node.type !== 'paragraph' && node.content?.some(c => c.type !== 'text')) {\n // A block we can't represent: keep its text.\n out.content = [{ type: 'text', text: textOf(node) }].filter(t => t.text)\n return out\n }\n if (node.marks) out.marks = node.marks.filter(m => schema.marks[m.type])\n if (node.content) out.content = node.content.map(c => fitToSchema(c, schema))\n return out\n}\n\n/** All text in a node, without recursion. */\nfunction textOf(node: JSONContent): string {\n const parts: string[] = []\n const stack: JSONContent[] = [node]\n while (stack.length) {\n const n = stack.pop()!\n if (n.text) parts.push(n.text)\n if (n.content) for (let i = n.content.length - 1; i >= 0; i--) stack.push(n.content[i]!)\n }\n return parts.join(' ')\n}\n\nexport const MarkdownPaste = Extension.create({\n name: 'markdownPaste',\n addProseMirrorPlugins() {\n const editor = this.editor\n return [new Plugin({\n key: new PluginKey('markdownPaste'),\n props: {\n handlePaste: (view, event) => {\n const data = event.clipboardData\n const text = data?.getData('text/plain')\n if (!text || data!.getData('text/html')) return false\n // Shift+Mod+V, \"paste as plain text\". Same test as ProseMirror's own plain paste:\n // Shift+Insert (key code 45) is a normal paste.\n const input = (view as unknown as { input?: { shiftKey?: boolean, lastKeyCode?: number | null } }).input\n if (input?.shiftKey && input.lastKeyCode !== 45) return false\n if (view.state.selection.$from.parent.type.spec.code) return false\n let blocks: JSONContent[]\n try {\n if (!looksLikeMarkdown(text)) return false\n blocks = markdownToBlocks(text).map(b => fitToSchema(b, view.state.schema))\n }\n catch (error) {\n // Whatever goes wrong, the paste still happens, as plain text.\n console.warn('[MeiEditor] Markdown paste failed, pasting as plain text:', error)\n return false\n }\n if (!blocks.length) return false\n return editor.commands.insertContent(blocks)\n },\n },\n })]\n },\n})\n","import { type Editor, Extension } from '@tiptap/core'\nimport type { Node as PMNode } from '@tiptap/pm/model'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\nimport { Decoration, DecorationSet } from '@tiptap/pm/view'\n\nexport interface PlaceholderOptions {\n /** Hint for an empty text block, e.g. \"Type '/' for commands\". */\n placeholder: string | ((props: { editor: Editor, node: PMNode, pos: number }) => string)\n}\n\nexport const placeholderPluginKey = new PluginKey('mePlaceholder')\n\n/**\n * \"Type '/'…\" hint on the empty text block holding the cursor, at any depth (inside\n * lists, callouts, toggles, columns). Renders `class=\"is-empty\"` and `data-placeholder`;\n * `is-editor-empty` is added when the whole document is empty.\n *\n * Replaces Tiptap's Placeholder: with `includeChildren` it keeps an incremental\n * decoration set whose rescan ranges are off by one, so hints stayed on blocks the\n * cursor had left (moving up through empty lines showed one on each). Only the\n * cursor's block can show a hint, so it's computed from the selection on every render:\n * no stored state to go stale, and O(1) whatever the document size.\n */\nexport const Placeholder = Extension.create<PlaceholderOptions>({\n name: 'placeholder',\n\n addOptions: () => ({ placeholder: '' }),\n\n addProseMirrorPlugins() {\n const { editor, options } = this\n return [new Plugin({\n key: placeholderPluginKey,\n props: {\n decorations: ({ doc, selection }) => {\n if (!editor.isEditable) return null\n const { $anchor } = selection\n const node = $anchor.parent\n if ($anchor.depth === 0 || !node.isTextblock || node.content.size > 0) return null\n const pos = $anchor.before()\n const text = typeof options.placeholder === 'function' ? options.placeholder({ editor, node, pos }) : options.placeholder\n return DecorationSet.create(doc, [Decoration.node(pos, pos + node.nodeSize, {\n 'class': editor.isEmpty ? 'is-empty is-editor-empty' : 'is-empty',\n 'data-placeholder': text,\n })])\n },\n },\n })]\n },\n})\n","import { Extension, Mark, mergeAttributes } from '@tiptap/core'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n textColor: {\n /** Sets a palette color by name (`'red'`, `'blue'`…); `null`/`'default'` removes it. */\n setTextColor: (color: string | null) => ReturnType\n }\n bgColor: {\n setBgColor: (color: string | null) => ReturnType\n }\n }\n}\n\nconst isDefault = (color: string | null) => !color || color === 'default'\n\n/** Text color stored by palette name, so themes and dark mode can restyle it. */\nexport const TextColor = Mark.create({\n name: 'textColor',\n addAttributes() {\n return {\n color: {\n default: null,\n parseHTML: el => el.getAttribute('data-text-color'),\n renderHTML: attrs => ({ 'data-text-color': attrs.color }),\n },\n }\n },\n parseHTML() {\n return [{ tag: 'span[data-text-color]' }]\n },\n renderHTML({ HTMLAttributes }) {\n return ['span', mergeAttributes(HTMLAttributes), 0]\n },\n addCommands() {\n return {\n setTextColor: color => ({ commands }) =>\n isDefault(color) ? commands.unsetMark(this.name) : commands.setMark(this.name, { color }),\n }\n },\n})\n\n/** Background (highlight) color stored by palette name. */\nexport const BgColor = Mark.create({\n name: 'bgColor',\n addAttributes() {\n return {\n color: {\n default: null,\n parseHTML: el => el.getAttribute('data-bg-color'),\n renderHTML: attrs => ({ 'data-bg-color': attrs.color }),\n },\n }\n },\n parseHTML() {\n return [{ tag: 'mark[data-bg-color]' }]\n },\n renderHTML({ HTMLAttributes }) {\n return ['mark', mergeAttributes(HTMLAttributes), 0]\n },\n addCommands() {\n return {\n setBgColor: color => ({ commands }) =>\n isDefault(color) ? commands.unsetMark(this.name) : commands.setMark(this.name, { color }),\n }\n },\n})\n\n/** Blocks that take a whole-block color (Notion's block menu / \"/red\" colors). */\nexport const COLORABLE_BLOCKS = ['paragraph', 'heading', 'blockquote', 'bulletList', 'orderedList', 'taskList', 'listItem', 'taskItem', 'details']\n\n/**\n * Whole-block text/background color, stored by palette name as `blockColor` / `blockBg`.\n * Renders the same `data-text-color` / `data-bg-color` attributes as the marks, so one\n * set of palette rules styles both. New blocks split off with Enter start uncolored.\n */\nexport const BlockColor = Extension.create({\n name: 'blockColor',\n addGlobalAttributes() {\n const attr = (data: string) => ({\n default: null,\n keepOnSplit: false,\n parseHTML: (el: HTMLElement) => (el.tagName === 'SPAN' || el.tagName === 'MARK' ? null : el.getAttribute(data)),\n })\n return [{\n types: COLORABLE_BLOCKS,\n attributes: {\n blockColor: { ...attr('data-text-color'), renderHTML: a => (a.blockColor ? { 'data-text-color': a.blockColor } : {}) },\n blockBg: { ...attr('data-bg-color'), renderHTML: a => (a.blockBg ? { 'data-bg-color': a.blockBg } : {}) },\n },\n }]\n },\n})\n","import type { Editor } from '@tiptap/core'\nimport { computed } from 'vue'\n\n/**\n * Theme scope attributes (mode class + overrides id) for elements rendered outside\n * the editor root, e.g. popovers teleported to <body>. Use with `v-bind`.\n */\nexport function useScope(editor: () => Editor | undefined) {\n return computed(() => editor()?.storage.meiConfig?.scope ?? { 'class': ['me-scope'], 'data-me-id': '' })\n}\n","/**\n * For menus that open at the caret (slash, mentions, emoji): hovering a row may select it only\n * after the pointer really moved. When a menu opens — or its rows change while typing — under a\n * resting pointer, the browser fires mouseenter (and Chrome a synthetic mousemove) on the row\n * that slid under it; selecting that row made Enter insert the wrong block (KS-BUG-3).\n *\n * Returns a handler for `mousemove`: true when the pointer is at a new position since the last\n * event this menu saw (the first event only records the position).\n */\nexport function usePointerMoved() {\n let last: { x: number, y: number } | null = null\n return (event: MouseEvent): boolean => {\n const moved = last !== null && (last.x !== event.screenX || last.y !== event.screenY)\n last = { x: event.screenX, y: event.screenY }\n return moved\n }\n}\n","<script setup lang=\"ts\">\nimport type { Editor } from '@tiptap/core'\nimport { computed, nextTick, ref, watch } from 'vue'\nimport { useScope } from '../composables/useScope'\nimport type { SlashItem } from '../slash-items'\nimport { usePointerMoved } from '../composables/usePointerMoved'\n\nconst props = defineProps<{\n editor: Editor\n items: SlashItem[]\n query: string\n command: (item: SlashItem) => void\n}>()\n\nconst selected = ref(0)\nconst listEl = ref<HTMLElement | null>(null)\nconst m = computed(() => props.editor.storage.meiConfig.messages)\nconst scope = useScope(() => props.editor)\n\n// While searching, show one ranked list; otherwise keep the sections (recent, groups, colors).\nconst groups = computed(() => {\n if (props.query.trim()) return [[m.value.slash.results, props.items.map((item, index) => ({ item, index }))] as const]\n const map = new Map<string, { item: SlashItem, index: number }[]>()\n props.items.forEach((item, index) => {\n if (!map.has(item.group)) map.set(item.group, [])\n map.get(item.group)!.push({ item, index })\n })\n return [...map.entries()]\n})\n\nwatch(() => props.items, () => (selected.value = 0))\nwatch(selected, async (i) => {\n await nextTick()\n listEl.value?.querySelector(`[data-index=\"${i}\"]`)?.scrollIntoView({ block: 'nearest' })\n})\n\nfunction select(index: number) {\n const item = props.items[index]\n if (item) props.command(item)\n}\n\nfunction onKeyDown(event: KeyboardEvent) {\n const n = props.items.length\n if (!n) return false\n if (event.key === 'ArrowDown') {\n selected.value = (selected.value + 1) % n\n return true\n }\n if (event.key === 'ArrowUp') {\n selected.value = (selected.value + n - 1) % n\n return true\n }\n if (event.key === 'Enter' || event.key === 'Tab') {\n select(selected.value)\n return true\n }\n return false\n}\n\ndefineExpose({ onKeyDown })\n\n// Hover selects a row only after a real pointer move (KS-BUG-3).\nconst pointerMoved = usePointerMoved()\n</script>\n\n<template>\n <div ref=\"listEl\" v-bind=\"scope\" class=\"me-popover me-menu\">\n <template v-if=\"items.length\">\n <div v-for=\"[group, entries] in groups\" :key=\"group\">\n <div class=\"me-menu-label\">\n {{ group }}\n </div>\n <button\n v-for=\"{ item, index } in entries\"\n :key=\"item.key\"\n type=\"button\"\n :data-index=\"index\"\n class=\"me-menu-item\"\n :class=\"{ 'is-active': index === selected }\"\n @mousemove=\"pointerMoved($event) && (selected = index)\"\n @mousedown.prevent=\"select(index)\"\n >\n <span v-if=\"item.swatch\" class=\"me-menu-icon\" :class=\"item.swatch.kind === 'text' ? 'me-swatch--text' : 'me-swatch--bg'\" :data-color=\"item.swatch.color\">A</span>\n <span v-else class=\"me-menu-icon\"><component :is=\"item.icon\" /></span>\n <span class=\"me-menu-text\">\n <span class=\"me-menu-title\">{{ item.title }}</span>\n <span v-if=\"item.description\" class=\"me-menu-desc\">{{ item.description }}</span>\n </span>\n <span v-if=\"item.shortcut\" class=\"me-menu-shortcut\">{{ item.shortcut }}</span>\n </button>\n </div>\n </template>\n <div v-else class=\"me-menu-empty\">\n {{ m.slash.empty }}\n </div>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport type { Editor } from '@tiptap/core'\nimport { computed, nextTick, ref, watch } from 'vue'\nimport { useScope } from '../composables/useScope'\nimport type { SlashItem } from '../slash-items'\nimport { usePointerMoved } from '../composables/usePointerMoved'\n\nconst props = defineProps<{\n editor: Editor\n items: SlashItem[]\n query: string\n command: (item: SlashItem) => void\n}>()\n\nconst selected = ref(0)\nconst listEl = ref<HTMLElement | null>(null)\nconst m = computed(() => props.editor.storage.meiConfig.messages)\nconst scope = useScope(() => props.editor)\n\n// While searching, show one ranked list; otherwise keep the sections (recent, groups, colors).\nconst groups = computed(() => {\n if (props.query.trim()) return [[m.value.slash.results, props.items.map((item, index) => ({ item, index }))] as const]\n const map = new Map<string, { item: SlashItem, index: number }[]>()\n props.items.forEach((item, index) => {\n if (!map.has(item.group)) map.set(item.group, [])\n map.get(item.group)!.push({ item, index })\n })\n return [...map.entries()]\n})\n\nwatch(() => props.items, () => (selected.value = 0))\nwatch(selected, async (i) => {\n await nextTick()\n listEl.value?.querySelector(`[data-index=\"${i}\"]`)?.scrollIntoView({ block: 'nearest' })\n})\n\nfunction select(index: number) {\n const item = props.items[index]\n if (item) props.command(item)\n}\n\nfunction onKeyDown(event: KeyboardEvent) {\n const n = props.items.length\n if (!n) return false\n if (event.key === 'ArrowDown') {\n selected.value = (selected.value + 1) % n\n return true\n }\n if (event.key === 'ArrowUp') {\n selected.value = (selected.value + n - 1) % n\n return true\n }\n if (event.key === 'Enter' || event.key === 'Tab') {\n select(selected.value)\n return true\n }\n return false\n}\n\ndefineExpose({ onKeyDown })\n\n// Hover selects a row only after a real pointer move (KS-BUG-3).\nconst pointerMoved = usePointerMoved()\n</script>\n\n<template>\n <div ref=\"listEl\" v-bind=\"scope\" class=\"me-popover me-menu\">\n <template v-if=\"items.length\">\n <div v-for=\"[group, entries] in groups\" :key=\"group\">\n <div class=\"me-menu-label\">\n {{ group }}\n </div>\n <button\n v-for=\"{ item, index } in entries\"\n :key=\"item.key\"\n type=\"button\"\n :data-index=\"index\"\n class=\"me-menu-item\"\n :class=\"{ 'is-active': index === selected }\"\n @mousemove=\"pointerMoved($event) && (selected = index)\"\n @mousedown.prevent=\"select(index)\"\n >\n <span v-if=\"item.swatch\" class=\"me-menu-icon\" :class=\"item.swatch.kind === 'text' ? 'me-swatch--text' : 'me-swatch--bg'\" :data-color=\"item.swatch.color\">A</span>\n <span v-else class=\"me-menu-icon\"><component :is=\"item.icon\" /></span>\n <span class=\"me-menu-text\">\n <span class=\"me-menu-title\">{{ item.title }}</span>\n <span v-if=\"item.description\" class=\"me-menu-desc\">{{ item.description }}</span>\n </span>\n <span v-if=\"item.shortcut\" class=\"me-menu-shortcut\">{{ item.shortcut }}</span>\n </button>\n </div>\n </template>\n <div v-else class=\"me-menu-empty\">\n {{ m.slash.empty }}\n </div>\n </div>\n</template>\n","import { ref } from 'vue'\nimport type { ColorName } from './colors'\n\n/** Recently used colors and blocks, shared by all editors and kept in localStorage. */\nexport interface RecentColor { kind: 'text' | 'bg', color: ColorName }\n\nconst KEY = 'mei-editor:recent'\nconst MAX = 5\n\nfunction load(): { colors: RecentColor[], blocks: string[] } {\n try {\n const raw = JSON.parse(localStorage.getItem(KEY) ?? '{}')\n return { colors: Array.isArray(raw.colors) ? raw.colors : [], blocks: Array.isArray(raw.blocks) ? raw.blocks : [] }\n }\n catch {\n return { colors: [], blocks: [] }\n }\n}\n\nexport const recent = ref(typeof window === 'undefined' ? { colors: [], blocks: [] } : load())\n\nfunction save() {\n try {\n localStorage.setItem(KEY, JSON.stringify(recent.value))\n }\n catch {}\n}\n\nexport function pushRecentColor(entry: RecentColor) {\n const rest = recent.value.colors.filter(c => !(c.kind === entry.kind && c.color === entry.color))\n recent.value = { ...recent.value, colors: [entry, ...rest].slice(0, MAX) }\n save()\n}\n\nexport function pushRecentBlock(id: string) {\n recent.value = { ...recent.value, blocks: [id, ...recent.value.blocks.filter(b => b !== id)].slice(0, MAX) }\n save()\n}\n","import type { Editor } from '@tiptap/core'\nimport type { ResolvedPos } from '@tiptap/pm/model'\nimport type { Component } from 'vue'\nimport { type BlockType, blockTitle, enabledBlocks, groupLabel } from './block-items'\nimport { type BlockRange, colorBlocks, currentRange } from './block-ops'\nimport { PALETTE_NAMES } from './theme/tokens'\nimport { pushRecentBlock, pushRecentColor, recent } from './recent'\n\n/** One row of the slash menu: a block type or a color command. */\nexport interface SlashItem {\n key: string\n /** Section label shown above the row. */\n group: string\n title: string\n description?: string\n icon?: Component\n swatch?: { kind: 'text' | 'bg', color: string }\n shortcut?: string\n terms: string[]\n /** Runs after the `/query` text has been removed. */\n apply: (editor: Editor) => void\n}\n\nconst normalize = (s: string) => s.normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/đ/g, 'd').toLowerCase()\n\nfunction blockItem(editor: Editor, block: BlockType, group: string, key = block.id): SlashItem {\n const m = editor.storage.meiConfig.messages\n return {\n key,\n group,\n title: blockTitle(m, block),\n description: m.blocks[block.id]?.description,\n icon: block.icon,\n shortcut: block.shortcut,\n terms: [blockTitle(m, block), block.id, ...block.keywords],\n apply: (ed) => {\n pushRecentBlock(block.id)\n block.insert(ed.chain().focus()).run()\n },\n }\n}\n\nfunction listItemRange($pos: ResolvedPos): BlockRange | null {\n for (let d = $pos.depth; d > 0; d--) {\n const name = $pos.node(d).type.name\n if (name === 'listItem' || name === 'taskItem') return { from: $pos.before(d), to: $pos.after(d), depth: d - 1 }\n }\n return null\n}\n\nfunction colorItems(editor: Editor): SlashItem[] {\n const m = editor.storage.meiConfig.messages\n return (['text', 'bg'] as const).flatMap(kind => PALETTE_NAMES.map((color): SlashItem => {\n const name = m.colors[color] ?? color\n const title = kind === 'text' ? m.slash.textColor(name) : m.slash.bgColor(name)\n return {\n key: `color-${kind}-${color}`,\n group: m.slash.colors,\n title,\n swatch: { kind, color },\n terms: [title, name, color, kind === 'text' ? 'color mau chu 文字颜色' : 'background highlight nen 背景颜色'],\n apply: (ed) => {\n pushRecentColor({ kind, color })\n const caret = ed.state.selection.from\n // Inside a list, \"/red\" colors just that item (each item is its own block in Notion).\n const range = listItemRange(ed.state.selection.$from) ?? currentRange(ed.state)\n if (!range) return\n colorBlocks(ed, range, kind, color)\n ed.commands.setTextSelection(caret)\n },\n }\n }))\n}\n\n/**\n * Items for the slash menu. Without a query: recently used blocks, all blocks by group,\n * then colors. With a query: everything ranked (exact term > word prefix > substring).\n */\nexport function slashItems(editor: Editor, query: string): SlashItem[] {\n const m = editor.storage.meiConfig.messages\n const blocks = enabledBlocks(editor)\n const all = [...blocks.map(b => blockItem(editor, b, groupLabel(m, b.group))), ...colorItems(editor)]\n\n const q = normalize(query.trim())\n if (!q) {\n const recentItems = recent.value.blocks\n .map(id => blocks.find(b => b.id === id))\n .filter((b): b is BlockType => !!b)\n .map(b => blockItem(editor, b, m.slash.recent, `recent-${b.id}`))\n // The menu shows items grouped, and ↑/↓ follow this array — so keep each group\n // contiguous (blocks from later definitions, e.g. `file`, join their group).\n const rank = new Map<string, number>()\n for (const item of [...recentItems, ...all]) if (!rank.has(item.group)) rank.set(item.group, rank.size)\n return [...recentItems, ...all]\n .map((item, i) => ({ item, i }))\n .sort((a, b) => rank.get(a.item.group)! - rank.get(b.item.group)! || a.i - b.i)\n .map(x => x.item)\n }\n\n const score = (item: SlashItem) => {\n const terms = item.terms.map(normalize)\n // Title or id typed exactly beats a block that merely lists it as a keyword (\"/page\" → Page, not Mention).\n if (terms[0] === q || terms[1] === q) return 4\n if (terms.includes(q)) return 3\n if (terms.some(t => t.startsWith(q) || t.split(/\\s+/).some(w => w.startsWith(q)))) return 2\n if (terms.some(t => t.includes(q))) return 1\n return 0\n }\n return all\n .map((item, i) => ({ item, i, s: score(item) }))\n .filter(x => x.s > 0)\n .sort((a, b) => b.s - a.s || a.i - b.i)\n .map(x => x.item)\n}\n","import { cssVar } from './define'\n\n/**\n * Reads a token's resolved pixel value from an element, for JS-driven layout\n * (e.g. popover offsets). Returns `fallback` when unavailable.\n */\nexport function readTokenPx(el: Element | null | undefined, path: string, fallback = 0): number {\n if (!el || typeof getComputedStyle === 'undefined') return fallback\n const probe = document.createElement('div')\n probe.style.cssText = `position:absolute;visibility:hidden;width:var(${cssVar(path)})`\n el.appendChild(probe)\n const px = probe.getBoundingClientRect().width\n probe.remove()\n return px || fallback\n}\n","import type { PluginKey } from '@tiptap/pm/state'\nimport { exitSuggestion, type SuggestionKeyDownProps, type SuggestionOptions, type SuggestionProps } from '@tiptap/suggestion'\nimport { VueRenderer } from '@tiptap/vue-3'\nimport { autoUpdate, computePosition, flip, offset, shift } from '@floating-ui/dom'\nimport type { Component } from 'vue'\nimport { readTokenPx } from '../theme/read'\n\n/**\n * Renders a suggestion popup (slash menu, emoji, mentions) with a Vue component that\n * exposes `onKeyDown(event): boolean`, positioned under the caret with floating-ui.\n */\nexport function suggestionRenderer<I>(\n component: Component,\n pluginKey: PluginKey,\n hooks: { onUpdate?: (props: SuggestionProps<I>) => boolean | void, onStart?: () => void } = {},\n): SuggestionOptions<I>['render'] {\n return () => {\n let renderer: VueRenderer | null = null\n let cleanup: (() => void) | null = null\n\n const position = (props: SuggestionProps<I>) => {\n const el = renderer?.element as HTMLElement | undefined\n if (!el || !props.clientRect) return\n const reference = { getBoundingClientRect: () => props.clientRect?.() ?? new DOMRect() }\n const gap = readTokenPx(props.editor.view.dom, 'popover.offset')\n cleanup?.()\n cleanup = autoUpdate(reference, el, () => {\n computePosition(reference, el, {\n placement: 'bottom-start',\n strategy: 'fixed',\n middleware: [offset(gap), flip({ padding: gap }), shift({ padding: gap })],\n }).then(({ x, y }) => Object.assign(el.style, { left: `${x}px`, top: `${y}px` }))\n })\n }\n\n return {\n onStart: (props) => {\n hooks.onStart?.()\n renderer = new VueRenderer(component, { props, editor: props.editor })\n const el = renderer.element as HTMLElement\n Object.assign(el.style, { position: 'fixed', zIndex: '50', left: '0', top: '0' })\n document.body.appendChild(el)\n position(props)\n },\n onUpdate: (props) => {\n // A hook returning false closes the popup (deferred: no dispatch during view updates).\n if (hooks.onUpdate?.(props) === false) {\n setTimeout(() => exitSuggestion(props.editor.view, pluginKey))\n return\n }\n renderer?.updateProps(props)\n position(props)\n },\n onKeyDown: (props: SuggestionKeyDownProps) => {\n if (props.event.key === 'Escape') {\n exitSuggestion(props.view, pluginKey)\n return true\n }\n return renderer?.ref?.onKeyDown?.(props.event) ?? false\n },\n onExit: () => {\n cleanup?.()\n cleanup = null\n renderer?.element?.remove()\n renderer?.destroy()\n renderer = null\n },\n }\n }\n}\n","import { Extension } from '@tiptap/core'\nimport { PluginKey } from '@tiptap/pm/state'\nimport Suggestion from '@tiptap/suggestion'\nimport SlashMenu from '../components/SlashMenu.vue'\nimport { type SlashItem, slashItems } from '../slash-items'\nimport { suggestionRenderer } from './suggestion-renderer'\n\nexport const slashPluginKey = new PluginKey('slashCommand')\n\nexport const SlashCommand = Extension.create({\n name: 'slashCommand',\n // Above list/task keymaps, so Enter picks a menu item instead of splitting the item.\n priority: 200,\n\n addProseMirrorPlugins() {\n let lastMatch = 0\n return [\n Suggestion<SlashItem>({\n editor: this.editor,\n pluginKey: slashPluginKey,\n char: '/',\n // Multi-word names (\"tiêu đề 2\", \"nền vàng\") need spaces; see onUpdate for closing.\n allowSpaces: true,\n // Not inside code blocks, nor table cells (cells are text-only).\n allow: ({ state, range }) => {\n const $pos = state.doc.resolve(range.from)\n if ($pos.parent.type.spec.code) return false\n for (let d = $pos.depth; d > 0; d--) {\n if (['tableCell', 'tableHeader'].includes($pos.node(d).type.name)) return false\n }\n return true\n },\n items: ({ query, editor }) => slashItems(editor, query),\n command: ({ editor, range, props: item }) => {\n editor.chain().focus().deleteRange(range).run()\n item.apply(editor)\n },\n render: suggestionRenderer<SlashItem>(SlashMenu, slashPluginKey, {\n onStart: () => (lastMatch = 0),\n // Smart close (like Notion): stop once the user is clearly just typing text —\n // no results and a space, or 3+ chars past the last match. props.items is\n // briefly empty while items load, so count matches directly.\n onUpdate: (props) => {\n if (slashItems(props.editor, props.query).length) lastMatch = props.query.length\n else if (props.query.endsWith(' ') || props.query.length - lastMatch >= 3) return false\n },\n }),\n }),\n ]\n },\n})\n","import { Node } from '@tiptap/core'\nimport { NodeSelection, Plugin, PluginKey, TextSelection } from '@tiptap/pm/state'\n\n/**\n * Placeholders for content whose block type isn't loaded in this editor (e.g. a doc\n * written where `math` was enabled). The original JSON is kept in `data` and restored\n * on output, so nothing is lost; the block can be moved or deleted but not edited.\n */\nfunction placeholder(name: string, inline: boolean) {\n return Node.create({\n name,\n group: inline ? 'inline' : 'block',\n inline,\n atom: true,\n selectable: true,\n draggable: !inline,\n\n addAttributes() {\n return {\n data: {\n default: null,\n parseHTML: el => JSON.parse(el.getAttribute('data-json') || 'null'),\n renderHTML: attrs => ({ 'data-json': JSON.stringify(attrs.data) }),\n },\n /** True when the block type is known but its content was invalid. */\n invalid: { default: false, rendered: false },\n }\n },\n\n parseHTML() {\n return [{ tag: `${inline ? 'span' : 'div'}[data-type=\"${name}\"]` }]\n },\n\n renderHTML({ HTMLAttributes }) {\n return [inline ? 'span' : 'div', { ...HTMLAttributes, 'data-type': name }]\n },\n\n addProseMirrorPlugins() {\n // Typing while the placeholder is selected would replace it (and lose its data);\n // put the text in a new paragraph after it instead. Deleting still works on purpose.\n return [new Plugin({\n key: new PluginKey(`${name}Guard`),\n props: {\n handleTextInput: (view, _from, _to, text) => {\n const sel = view.state.selection\n if (!(sel instanceof NodeSelection) || sel.node.type.name !== name) return false\n const tr = view.state.tr\n if (inline) {\n tr.setSelection(TextSelection.create(tr.doc, sel.to)).insertText(text)\n }\n else {\n const paragraph = view.state.schema.nodes.paragraph!.create(null, view.state.schema.text(text))\n tr.insert(sel.to, paragraph).setSelection(TextSelection.create(tr.doc, sel.to + 1 + text.length))\n }\n view.dispatch(tr.scrollIntoView())\n return true\n },\n },\n })]\n },\n\n addNodeView() {\n return ({ node, editor }) => {\n const dom = document.createElement(inline ? 'span' : 'div')\n dom.className = inline ? 'me-unknown me-unknown--inline' : `me-unknown${node.attrs.invalid ? ' is-invalid' : ''}`\n dom.contentEditable = 'false'\n const m = editor.storage.meiConfig?.messages\n const label = node.attrs.invalid ? (m?.invalidBlock ?? 'Invalid block') : (m?.unknownBlock ?? 'Unsupported block')\n dom.textContent = `${label}: ${node.attrs.data?.type ?? '?'}`\n return { dom }\n }\n },\n })\n}\n\nexport const UnknownBlock = placeholder('unknownBlock', false)\nexport const UnknownInline = placeholder('unknownInline', true)\n","import type { AnyExtension } from '@tiptap/core'\nimport StarterKit from '@tiptap/starter-kit'\nimport { MeiConfig, type MeiConfigStorage } from '../config'\nimport { collectExtensions, type BlockDefinition } from '../define-block'\nimport { BlockDrop } from './block-drop'\nimport { BlockId } from './block-id'\nimport { BlockSelection } from './block-selection'\nimport { FileDrop } from './file-drop'\nimport { MarkdownPaste } from './markdown-paste'\nimport { Placeholder } from './placeholder'\nimport { BgColor, BlockColor, TextColor } from './color-marks'\nimport { SlashCommand } from './slash-command'\nimport { UnknownBlock, UnknownInline } from './unknown'\n\nexport interface MeiExtensionsOptions extends Partial<MeiConfigStorage> {\n /** Block definitions to load (their extensions and menu items). */\n blocks: BlockDefinition[]\n /**\n * Built-in undo / redo (StarterKit's `undoRedo`). Default true. Set false with\n * `collaborationExtensions()` (`@toantranmei/editor/collaboration`), which brings Yjs undo.\n */\n undoRedo?: boolean\n}\n\n/**\n * Editor core (always loaded) + the extensions of the given blocks.\n * Core: paragraphs, text marks, links, history, colors, slash menu, drag & drop, file paste / drop,\n * block selection, block ids and the unknown-block fallback.\n */\nexport function createExtensions({ blocks, undoRedo = true, ...config }: MeiExtensionsOptions): AnyExtension[] {\n return [\n MeiConfig.configure({ ...config, items: blocks.flatMap(b => b.items), formatActions: blocks.flatMap(b => b.formatActions ?? []) }),\n StarterKit.configure({\n // Block types come from block definitions.\n heading: false,\n bulletList: false,\n orderedList: false,\n listItem: false,\n listKeymap: false,\n blockquote: false,\n codeBlock: false,\n horizontalRule: false,\n ...(undoRedo ? {} : { undoRedo: false as const }),\n dropcursor: { color: '#93c5fd', width: 3 },\n link: { openOnClick: false, autolink: true, defaultProtocol: 'https' },\n }),\n Placeholder.configure({\n placeholder: ({ editor, node }) => {\n const m = editor.storage.meiConfig.messages\n if (node.type.name === 'heading') return m.headingPlaceholder(node.attrs.level)\n if (node.type.name === 'detailsSummary') return m.togglePlaceholder\n return m.placeholder\n },\n }),\n TextColor,\n BgColor,\n BlockColor,\n SlashCommand,\n // Pasted / dropped files become image and file blocks (before markdownPaste).\n FileDrop,\n MarkdownPaste,\n BlockDrop,\n BlockSelection,\n UnknownBlock,\n UnknownInline,\n ...collectExtensions(blocks),\n // Stable ids for block-level nodes (used by \"Copy link to block\").\n BlockId.configure({ types: ['paragraph', ...new Set(blocks.flatMap(b => b.nodes))] }),\n ]\n}\n","/**\n * The line the block handle (+ ⋮⋮) is vertically centered on, like Notion:\n * - text blocks: their first line of text (headings, callouts, lists, tables…)\n * - blocks with a header bar (code, HTML): the bar\n * - dividers: the line itself\n * - media and other blocks without text (image, embed, file…): a text line at their top edge\n *\n * Centering on a line, instead of aligning tops, keeps the handle level with the text\n * whatever padding, margin or font size a block has.\n */\nexport function handleAnchorRect(dom: HTMLElement): DOMRect {\n const box = dom.getBoundingClientRect()\n const lineHeight = lineHeightOf(dom)\n const line = (center: number) => new DOMRect(box.left, center - lineHeight / 2, box.width, lineHeight)\n\n if (dom.tagName === 'HR') return line(box.top + box.height / 2)\n\n const bar = dom.querySelector<HTMLElement>('.me-block-bar')\n if (bar) {\n const r = bar.getBoundingClientRect()\n return line(r.top + r.height / 2)\n }\n\n const text = firstTextRect(dom)\n if (text) return line(text.top + text.height / 2)\n\n // An empty text block: the middle of its first (empty) line.\n const block = dom.matches('p, h1, h2, h3, h4, summary') ? dom : dom.querySelector<HTMLElement>('p, h1, h2, h3, h4, summary')\n if (block) {\n const r = block.getBoundingClientRect()\n const padTop = Number.parseFloat(getComputedStyle(block).paddingTop) || 0\n return line(r.top + padTop + lineHeightOf(block) / 2)\n }\n\n return line(box.top + lineHeight / 2)\n}\n\n/**\n * Rect of the first visible character. Prefers editable text over UI inside the block\n * (a callout's emoji button, an image toolbar); blocks that only have UI text (TOC,\n * upload placeholders) fall back to that.\n */\nfunction firstTextRect(root: HTMLElement): DOMRect | null {\n const inUi = (node: Node) => {\n const ui = node.parentElement?.closest('[contenteditable=\"false\"]')\n return !!ui && ui !== root && root.contains(ui)\n }\n return findTextRect(root, node => !inUi(node)) ?? findTextRect(root, () => true)\n}\n\nfunction findTextRect(root: HTMLElement, accept: (node: Node) => boolean): DOMRect | null {\n const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {\n acceptNode: node => (node.textContent?.trim() && accept(node) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP),\n })\n for (let node = walker.nextNode(); node; node = walker.nextNode()) {\n const offset = node.textContent!.search(/\\S/)\n const range = document.createRange()\n range.setStart(node, offset)\n range.setEnd(node, offset + 1)\n const rect = range.getClientRects()[0]\n if (rect && rect.height > 0) return rect\n }\n return null\n}\n\nfunction lineHeightOf(el: HTMLElement): number {\n const style = getComputedStyle(el)\n const lh = Number.parseFloat(style.lineHeight)\n return Number.isNaN(lh) ? Number.parseFloat(style.fontSize) * 1.5 : lh\n}\n","/** Formats a Tiptap-style shortcut ('Mod-Shift-ArrowUp') for display: ⌘⇧↑ on Mac, Ctrl+Shift+↑ elsewhere. */\nconst isMac = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform)\n\nconst MAC: Record<string, string> = { Mod: '⌘', Shift: '⇧', Alt: '⌥', ArrowUp: '↑', ArrowDown: '↓', Backspace: '⌫', Delete: 'Del', Escape: 'Esc' }\nconst PC: Record<string, string> = { Mod: 'Ctrl', Shift: 'Shift', Alt: 'Alt', ArrowUp: '↑', ArrowDown: '↓', Backspace: 'Backspace', Delete: 'Del', Escape: 'Esc' }\n\nexport function kbd(shortcut: string): string {\n const parts = shortcut.split('-').map(p => (isMac ? MAC : PC)[p] ?? p.toUpperCase())\n return isMac ? parts.join('') : parts.join('+')\n}\n\n/** True for ⌘ on Mac / Ctrl elsewhere. */\nexport const isMod = (e: KeyboardEvent | MouseEvent) => (isMac ? e.metaKey : e.ctrlKey)\n","import type { InjectionKey, Ref } from 'vue'\nimport type { BlockDefinition } from './define-block'\nimport type { ThemeTokens } from './theme/tokens'\n\n/** App-wide token overrides provided by the Vue plugin (`app.use(MeiEditorPlugin, { tokens })`). */\nexport const GLOBAL_TOKENS_KEY: InjectionKey<Ref<ThemeTokens | undefined>> = Symbol('mei-editor-tokens')\n\n/** App-wide blocks provided by the Vue plugin / Nuxt module. */\nexport const GLOBAL_BLOCKS_KEY: InjectionKey<BlockDefinition[]> = Symbol('mei-editor-blocks')\n","import { TextSelection } from '@tiptap/pm/state'\nimport { VueNodeViewRenderer } from '@tiptap/vue-3'\nimport type { Component } from 'vue'\n\ninterface PatchedView {\n stopEvent?: (event: Event) => boolean\n handleSelectionUpdate?: () => void\n renderer?: { props?: { selected?: boolean } }\n}\n\n/**\n * VueNodeViewRenderer with two fixes for block node views (image, embed, callout, code…):\n *\n * 1. Lets `mousemove` through from the node view's own UI. Tiptap stops those events\n * by default, which keeps the drag handle from appearing while hovering them.\n * 2. Skips the per-keystroke selection check while typing. Every node view listens to\n * selection changes and calls getPos(), which scans sibling blocks — with thousands\n * of node views that made each keystroke O(views × blocks). A plain caret can't\n * select a node view, so it only needs checking when one is currently selected.\n */\nexport function blockNodeView(component: Component) {\n const render = VueNodeViewRenderer(component)\n return ((props: Parameters<typeof render>[0]) => {\n const view = render(props) as ReturnType<typeof render> & PatchedView\n\n const stop = view.stopEvent?.bind(view)\n if (stop) view.stopEvent = (event: Event) => (event.type === 'mousemove' ? false : stop(event))\n\n const original = view.handleSelectionUpdate\n if (original) {\n const { editor } = props\n const fast = () => {\n const sel = editor.state.selection\n if (sel.empty && sel instanceof TextSelection && !view.renderer?.props?.selected) return\n original()\n }\n editor.off('selectionUpdate', original)\n editor.on('selectionUpdate', fast)\n // destroy() unsubscribes `this.handleSelectionUpdate`, so point it at the new handler.\n view.handleSelectionUpdate = fast\n }\n return view\n }) as typeof render\n}\n","import type { Editor } from '@tiptap/core'\nimport { onBeforeUnmount, readonly, ref } from 'vue'\n\n/**\n * `editor.isEditable` as a Vue ref. The editor's flag isn't reactive, so node views\n * would keep showing edit controls after switching to read-only (setEditable emits\n * an update, which is what we listen to).\n */\nexport function useEditable(editor: Editor) {\n const editable = ref(editor.isEditable)\n const sync = () => {\n if (editable.value !== editor.isEditable) editable.value = editor.isEditable\n }\n editor.on('update', sync)\n onBeforeUnmount(() => editor.off('update', sync))\n return readonly(editable)\n}\n","import { onBeforeUnmount, onMounted, type Ref } from 'vue'\n\n/** An element, or a component whose root element counts (e.g. a NodeViewWrapper ref). */\ntype Target = HTMLElement | { $el?: unknown } | null | undefined\n\n/** Calls `handler` on a pointerdown outside `target` while `active` is true. */\nexport function useClickOutside(target: Ref<Target>, active: { readonly value: boolean }, handler: () => void) {\n const listener = (e: PointerEvent) => {\n if (!active.value) return\n const value = target.value\n const el = value instanceof Element ? value : value?.$el\n if (el instanceof Element && !el.contains(e.target as Node)) handler()\n }\n onMounted(() => document.addEventListener('pointerdown', listener, true))\n onBeforeUnmount(() => document.removeEventListener('pointerdown', listener, true))\n}\n","<script setup lang=\"ts\">\nimport { NodeViewContent, NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'\nimport { useEditable } from '../composables/useEditable'\nimport { handleAnchorRect } from '../handle-anchor'\nimport { PALETTE_NAMES } from '../theme/tokens'\nimport { useClickOutside } from '../composables/useClickOutside'\n\nconst props = defineProps(nodeViewProps)\nconst editable = useEditable(props.editor)\n\nconst ICONS = ['💡', '⚠️', '❗', '✅', 'ℹ️', '📌', '🔥', '📝', '🚀', '❓', '⭐', '🎯']\nconst open = ref(false)\nconst pickerEl = ref<HTMLElement | null>(null)\nuseClickOutside(pickerEl, open, () => (open.value = false))\n\nconst m = computed(() => props.editor.storage.meiConfig.messages)\n\n// Keep the icon centered on the first line of the content, whatever block it is\n// (text, heading, list, code…), measured the same way as the block handle.\nconst root = ref<{ $el: HTMLElement } | null>(null)\nconst iconEl = ref<HTMLElement | null>(null)\nconst iconOffset = ref(0)\nfunction alignIcon() {\n const content = root.value?.$el.querySelector<HTMLElement>('.me-callout-content')\n const first = content?.firstElementChild\n if (!content || !(first instanceof HTMLElement) || !iconEl.value) return\n const line = handleAnchorRect(first)\n const center = line.top + line.height / 2 - content.getBoundingClientRect().top\n iconOffset.value = Math.round(center - iconEl.value.offsetHeight / 2)\n}\nlet observer: ResizeObserver | null = null\nonMounted(() => {\n alignIcon()\n if (typeof ResizeObserver !== 'undefined') {\n observer = new ResizeObserver(() => alignIcon())\n const content = root.value?.$el.querySelector('.me-callout-content')\n if (content) observer.observe(content)\n }\n})\nwatch(() => props.node, () => nextTick(alignIcon))\nonBeforeUnmount(() => observer?.disconnect())\n</script>\n\n<template>\n <NodeViewWrapper ref=\"root\" class=\"me-callout\" :data-color=\"node.attrs.color\">\n <div ref=\"pickerEl\" class=\"me-callout-icon-wrap\" contenteditable=\"false\" :style=\"{ marginTop: `${iconOffset}px` }\">\n <button ref=\"iconEl\" type=\"button\" class=\"me-callout-icon\" :title=\"m.callout.change\" :disabled=\"!editable\" @click=\"open = !open\">\n {{ node.attrs.icon }}\n </button>\n <div v-if=\"open\" class=\"me-popover me-callout-picker\">\n <div class=\"me-menu-label\">\n {{ m.callout.icon }}\n </div>\n <div class=\"me-emoji-grid\">\n <button v-for=\"icon in ICONS\" :key=\"icon\" type=\"button\" class=\"me-emoji\" @click=\"updateAttributes({ icon }); open = false\">\n {{ icon }}\n </button>\n </div>\n <div class=\"me-menu-label\">\n {{ m.callout.background }}\n </div>\n <div class=\"me-swatch-grid\">\n <button\n v-for=\"c in PALETTE_NAMES\"\n :key=\"c\"\n type=\"button\"\n class=\"me-swatch-btn\"\n :class=\"{ 'is-active': node.attrs.color === c }\"\n :data-color=\"c\"\n :title=\"m.colors[c]\"\n @click=\"updateAttributes({ color: c })\"\n />\n </div>\n </div>\n </div>\n <NodeViewContent class=\"me-callout-content\" />\n </NodeViewWrapper>\n</template>\n","<script setup lang=\"ts\">\nimport { NodeViewContent, NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'\nimport { useEditable } from '../composables/useEditable'\nimport { handleAnchorRect } from '../handle-anchor'\nimport { PALETTE_NAMES } from '../theme/tokens'\nimport { useClickOutside } from '../composables/useClickOutside'\n\nconst props = defineProps(nodeViewProps)\nconst editable = useEditable(props.editor)\n\nconst ICONS = ['💡', '⚠️', '❗', '✅', 'ℹ️', '📌', '🔥', '📝', '🚀', '❓', '⭐', '🎯']\nconst open = ref(false)\nconst pickerEl = ref<HTMLElement | null>(null)\nuseClickOutside(pickerEl, open, () => (open.value = false))\n\nconst m = computed(() => props.editor.storage.meiConfig.messages)\n\n// Keep the icon centered on the first line of the content, whatever block it is\n// (text, heading, list, code…), measured the same way as the block handle.\nconst root = ref<{ $el: HTMLElement } | null>(null)\nconst iconEl = ref<HTMLElement | null>(null)\nconst iconOffset = ref(0)\nfunction alignIcon() {\n const content = root.value?.$el.querySelector<HTMLElement>('.me-callout-content')\n const first = content?.firstElementChild\n if (!content || !(first instanceof HTMLElement) || !iconEl.value) return\n const line = handleAnchorRect(first)\n const center = line.top + line.height / 2 - content.getBoundingClientRect().top\n iconOffset.value = Math.round(center - iconEl.value.offsetHeight / 2)\n}\nlet observer: ResizeObserver | null = null\nonMounted(() => {\n alignIcon()\n if (typeof ResizeObserver !== 'undefined') {\n observer = new ResizeObserver(() => alignIcon())\n const content = root.value?.$el.querySelector('.me-callout-content')\n if (content) observer.observe(content)\n }\n})\nwatch(() => props.node, () => nextTick(alignIcon))\nonBeforeUnmount(() => observer?.disconnect())\n</script>\n\n<template>\n <NodeViewWrapper ref=\"root\" class=\"me-callout\" :data-color=\"node.attrs.color\">\n <div ref=\"pickerEl\" class=\"me-callout-icon-wrap\" contenteditable=\"false\" :style=\"{ marginTop: `${iconOffset}px` }\">\n <button ref=\"iconEl\" type=\"button\" class=\"me-callout-icon\" :title=\"m.callout.change\" :disabled=\"!editable\" @click=\"open = !open\">\n {{ node.attrs.icon }}\n </button>\n <div v-if=\"open\" class=\"me-popover me-callout-picker\">\n <div class=\"me-menu-label\">\n {{ m.callout.icon }}\n </div>\n <div class=\"me-emoji-grid\">\n <button v-for=\"icon in ICONS\" :key=\"icon\" type=\"button\" class=\"me-emoji\" @click=\"updateAttributes({ icon }); open = false\">\n {{ icon }}\n </button>\n </div>\n <div class=\"me-menu-label\">\n {{ m.callout.background }}\n </div>\n <div class=\"me-swatch-grid\">\n <button\n v-for=\"c in PALETTE_NAMES\"\n :key=\"c\"\n type=\"button\"\n class=\"me-swatch-btn\"\n :class=\"{ 'is-active': node.attrs.color === c }\"\n :data-color=\"c\"\n :title=\"m.colors[c]\"\n @click=\"updateAttributes({ color: c })\"\n />\n </div>\n </div>\n </div>\n <NodeViewContent class=\"me-callout-content\" />\n </NodeViewWrapper>\n</template>\n","import { Node, mergeAttributes } from '@tiptap/core'\nimport { blockNodeView } from '../nodeviews/renderer'\nimport CalloutView from '../nodeviews/CalloutView.vue'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n callout: {\n setCallout: (attrs?: { icon?: string, color?: string }) => ReturnType\n }\n }\n}\n\nexport const Callout = Node.create({\n name: 'callout',\n group: 'block',\n content: 'block+',\n defining: true,\n draggable: true,\n\n addAttributes() {\n return {\n icon: {\n default: '💡',\n parseHTML: el => el.getAttribute('data-icon') || '💡',\n renderHTML: attrs => ({ 'data-icon': attrs.icon }),\n },\n color: {\n default: 'gray',\n parseHTML: el => el.getAttribute('data-color') || 'gray',\n renderHTML: attrs => ({ 'data-color': attrs.color }),\n },\n }\n },\n\n parseHTML() {\n return [{ tag: 'div[data-type=\"callout\"]' }]\n },\n\n renderHTML({ HTMLAttributes }) {\n return ['div', mergeAttributes(HTMLAttributes, { 'data-type': 'callout' }), 0]\n },\n\n addCommands() {\n return {\n setCallout: attrs => ({ commands }) => commands.wrapIn(this.name, attrs),\n }\n },\n\n addNodeView() {\n return blockNodeView(CalloutView)\n },\n})\n","/**\n * Heavy libraries load on first use, so apps only pay for what documents contain.\n * KaTeX and Mermaid are optional peer dependencies: install them to use `math` / `mermaid`.\n */\nlet katexPromise: Promise<typeof import('katex')['default']> | null = null\n/**\n * KaTeX's stylesheet is NOT imported here: Vite's dev optimizer can't stub a CSS subpath\n * of a missing optional peer, which would break apps that don't use math. The Nuxt module\n * adds it when `math` is enabled; Vue apps import 'katex/dist/katex.min.css' themselves.\n */\nexport function loadKatex() {\n katexPromise ??= import('katex').then(m => m.default)\n return katexPromise\n}\n\nlet mermaidPromise: Promise<typeof import('mermaid')['default']> | null = null\nexport function loadMermaid() {\n mermaidPromise ??= import('mermaid').then(m => m.default)\n return mermaidPromise\n}\n","<script lang=\"ts\">\n/**\n * A page-unique id for every render. Node views are separate Vue render roots, so useId()\n * gave every diagram the same id (`me-mermaid-v-0`): when several diagrams rendered together\n * (opening a page), a failing one removed `#id` — another diagram's SVG — and the next renders\n * failed too (KS-BUG-8).\n */\nlet counter = 0\nconst nextId = () => `me-mermaid-${++counter}`\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, onBeforeUnmount, ref, watch } from 'vue'\nimport type { EditorMessages } from '../locale'\nimport { loadMermaid } from '../lazy'\n\nconst props = defineProps<{ code: string, messages: EditorMessages, dark: boolean }>()\n\nconst svg = ref('')\nconst error = ref('')\nlet timer: ReturnType<typeof setTimeout> | undefined\nlet latest = ''\n\nasync function render() {\n if (!props.code.trim()) {\n svg.value = ''\n return\n }\n const id = nextId()\n latest = id\n try {\n const mermaid = await loadMermaid()\n // securityLevel 'strict' sanitizes labels and disables click handlers in diagrams.\n mermaid.initialize({ startOnLoad: false, securityLevel: 'strict', theme: props.dark ? 'dark' : 'default' })\n const result = await mermaid.render(id, props.code)\n if (latest !== id) return // a newer render took over\n svg.value = result.svg\n error.value = ''\n }\n catch (e) {\n if (latest !== id) return\n // The last good diagram stays while the code has a syntax error (e.g. mid-typing).\n error.value = e instanceof Error && /Failed to fetch|import/i.test(e.message) ? props.messages.mermaid.missing : props.messages.mermaid.invalid\n }\n finally {\n // Mermaid renders in temporary elements in <body> and leaves them there on a syntax error.\n for (const leftover of [id, `d${id}`, `i${id}`]) {\n const el = document.getElementById(leftover)\n if (el && !el.closest('.me-mermaid')) el.remove()\n }\n }\n}\n\n// Debounced while typing.\nwatch(() => [props.code, props.dark], () => {\n clearTimeout(timer)\n timer = setTimeout(render, 300)\n}, { immediate: true })\nonBeforeUnmount(() => clearTimeout(timer))\n\nconst label = computed(() => props.messages.mermaid.preview)\n</script>\n\n<template>\n <div class=\"me-mermaid\" contenteditable=\"false\" :aria-label=\"label\">\n <div v-if=\"svg\" class=\"me-mermaid-svg\" v-html=\"svg\" />\n <p v-if=\"error\" class=\"me-error\">\n {{ error }}\n </p>\n </div>\n</template>\n","<script lang=\"ts\">\n/**\n * A page-unique id for every render. Node views are separate Vue render roots, so useId()\n * gave every diagram the same id (`me-mermaid-v-0`): when several diagrams rendered together\n * (opening a page), a failing one removed `#id` — another diagram's SVG — and the next renders\n * failed too (KS-BUG-8).\n */\nlet counter = 0\nconst nextId = () => `me-mermaid-${++counter}`\n</script>\n\n<script setup lang=\"ts\">\nimport { computed, onBeforeUnmount, ref, watch } from 'vue'\nimport type { EditorMessages } from '../locale'\nimport { loadMermaid } from '../lazy'\n\nconst props = defineProps<{ code: string, messages: EditorMessages, dark: boolean }>()\n\nconst svg = ref('')\nconst error = ref('')\nlet timer: ReturnType<typeof setTimeout> | undefined\nlet latest = ''\n\nasync function render() {\n if (!props.code.trim()) {\n svg.value = ''\n return\n }\n const id = nextId()\n latest = id\n try {\n const mermaid = await loadMermaid()\n // securityLevel 'strict' sanitizes labels and disables click handlers in diagrams.\n mermaid.initialize({ startOnLoad: false, securityLevel: 'strict', theme: props.dark ? 'dark' : 'default' })\n const result = await mermaid.render(id, props.code)\n if (latest !== id) return // a newer render took over\n svg.value = result.svg\n error.value = ''\n }\n catch (e) {\n if (latest !== id) return\n // The last good diagram stays while the code has a syntax error (e.g. mid-typing).\n error.value = e instanceof Error && /Failed to fetch|import/i.test(e.message) ? props.messages.mermaid.missing : props.messages.mermaid.invalid\n }\n finally {\n // Mermaid renders in temporary elements in <body> and leaves them there on a syntax error.\n for (const leftover of [id, `d${id}`, `i${id}`]) {\n const el = document.getElementById(leftover)\n if (el && !el.closest('.me-mermaid')) el.remove()\n }\n }\n}\n\n// Debounced while typing.\nwatch(() => [props.code, props.dark], () => {\n clearTimeout(timer)\n timer = setTimeout(render, 300)\n}, { immediate: true })\nonBeforeUnmount(() => clearTimeout(timer))\n\nconst label = computed(() => props.messages.mermaid.preview)\n</script>\n\n<template>\n <div class=\"me-mermaid\" contenteditable=\"false\" :aria-label=\"label\">\n <div v-if=\"svg\" class=\"me-mermaid-svg\" v-html=\"svg\" />\n <p v-if=\"error\" class=\"me-error\">\n {{ error }}\n </p>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport { NodeViewContent, NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport { Check, ChevronDown, Copy } from '@lucide/vue'\nimport { computed, ref } from 'vue'\nimport { useEditable } from '../composables/useEditable'\nimport { CODE_LANGUAGES } from '../extensions/code-block'\nimport MermaidDiagram from '../components/MermaidDiagram.vue'\n\nconst props = defineProps(nodeViewProps)\nconst editable = useEditable(props.editor)\n\nconst m = computed(() => props.editor.storage.meiConfig.messages.code)\nconst hasMermaid = computed(() => !!props.editor.extensionManager.extensions.find(e => e.name === 'mermaidPreview'))\nconst languages = computed(() => {\n const list = hasMermaid.value ? [...CODE_LANGUAGES, 'mermaid'] : CODE_LANGUAGES\n // Keep an unknown current language (e.g. an alias like \"js\") selectable.\n const current = props.node.attrs.language\n return current && !list.includes(current) ? [...list, current] : list\n})\nconst copied = ref(false)\n\nconst showDiagram = computed(() => props.node.attrs.language === 'mermaid' && hasMermaid.value)\n// Dark when the editor is forced dark, or follows a dark page.\nconst isDark = computed(() => {\n const scope = props.editor.storage.meiConfig.scope.class\n return scope.includes('me-dark') || (!scope.includes('me-light') && document.documentElement.classList.contains('dark'))\n})\n\nasync function copy() {\n await navigator.clipboard.writeText(props.node.textContent)\n copied.value = true\n setTimeout(() => (copied.value = false), 1500)\n}\n</script>\n\n<template>\n <NodeViewWrapper class=\"me-code-block\">\n <div class=\"me-block-bar me-code-toolbar\" contenteditable=\"false\">\n <label class=\"me-code-lang\">\n <select\n :value=\"node.attrs.language || 'plaintext'\"\n :disabled=\"!editable\"\n @change=\"updateAttributes({ language: ($event.target as HTMLSelectElement).value })\"\n >\n <option v-for=\"lang in languages\" :key=\"lang\" :value=\"lang\">{{ lang }}</option>\n </select>\n <ChevronDown />\n </label>\n <button type=\"button\" class=\"me-tool-btn me-code-copy\" @click=\"copy\">\n <component :is=\"copied ? Check : Copy\" /> {{ copied ? m.copied : m.copy }}\n </button>\n </div>\n <pre><NodeViewContent as=\"code\" :class=\"`hljs language-${node.attrs.language || 'plaintext'}`\" /></pre>\n <MermaidDiagram v-if=\"showDiagram\" :code=\"node.textContent\" :messages=\"editor.storage.meiConfig.messages\" :dark=\"isDark\" />\n </NodeViewWrapper>\n</template>\n","<script setup lang=\"ts\">\nimport { NodeViewContent, NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport { Check, ChevronDown, Copy } from '@lucide/vue'\nimport { computed, ref } from 'vue'\nimport { useEditable } from '../composables/useEditable'\nimport { CODE_LANGUAGES } from '../extensions/code-block'\nimport MermaidDiagram from '../components/MermaidDiagram.vue'\n\nconst props = defineProps(nodeViewProps)\nconst editable = useEditable(props.editor)\n\nconst m = computed(() => props.editor.storage.meiConfig.messages.code)\nconst hasMermaid = computed(() => !!props.editor.extensionManager.extensions.find(e => e.name === 'mermaidPreview'))\nconst languages = computed(() => {\n const list = hasMermaid.value ? [...CODE_LANGUAGES, 'mermaid'] : CODE_LANGUAGES\n // Keep an unknown current language (e.g. an alias like \"js\") selectable.\n const current = props.node.attrs.language\n return current && !list.includes(current) ? [...list, current] : list\n})\nconst copied = ref(false)\n\nconst showDiagram = computed(() => props.node.attrs.language === 'mermaid' && hasMermaid.value)\n// Dark when the editor is forced dark, or follows a dark page.\nconst isDark = computed(() => {\n const scope = props.editor.storage.meiConfig.scope.class\n return scope.includes('me-dark') || (!scope.includes('me-light') && document.documentElement.classList.contains('dark'))\n})\n\nasync function copy() {\n await navigator.clipboard.writeText(props.node.textContent)\n copied.value = true\n setTimeout(() => (copied.value = false), 1500)\n}\n</script>\n\n<template>\n <NodeViewWrapper class=\"me-code-block\">\n <div class=\"me-block-bar me-code-toolbar\" contenteditable=\"false\">\n <label class=\"me-code-lang\">\n <select\n :value=\"node.attrs.language || 'plaintext'\"\n :disabled=\"!editable\"\n @change=\"updateAttributes({ language: ($event.target as HTMLSelectElement).value })\"\n >\n <option v-for=\"lang in languages\" :key=\"lang\" :value=\"lang\">{{ lang }}</option>\n </select>\n <ChevronDown />\n </label>\n <button type=\"button\" class=\"me-tool-btn me-code-copy\" @click=\"copy\">\n <component :is=\"copied ? Check : Copy\" /> {{ copied ? m.copied : m.copy }}\n </button>\n </div>\n <pre><NodeViewContent as=\"code\" :class=\"`hljs language-${node.attrs.language || 'plaintext'}`\" /></pre>\n <MermaidDiagram v-if=\"showDiagram\" :code=\"node.textContent\" :messages=\"editor.storage.meiConfig.messages\" :dark=\"isDark\" />\n </NodeViewWrapper>\n</template>\n","import CodeBlockLowlight from '@tiptap/extension-code-block-lowlight'\nimport type { Editor } from '@tiptap/core'\nimport type { NodeType } from '@tiptap/pm/model'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\nimport type { EditorView } from '@tiptap/pm/view'\nimport { createLowlight } from 'lowlight'\nimport { blockNodeView } from '../nodeviews/renderer'\nimport CodeBlockView from '../nodeviews/CodeBlockView.vue'\nimport { LANGUAGE_ALIASES as ALIASES } from './code-languages'\n\n/** Starts empty: each language's grammar is loaded the first time a code block uses it. */\nexport const lowlight = createLowlight()\n\ntype Grammar = Parameters<typeof lowlight.register>[1]\nconst LOADERS: Record<string, () => Promise<{ default: Grammar }>> = {\n arduino: () => import('highlight.js/lib/languages/arduino'),\n bash: () => import('highlight.js/lib/languages/bash'),\n c: () => import('highlight.js/lib/languages/c'),\n cpp: () => import('highlight.js/lib/languages/cpp'),\n csharp: () => import('highlight.js/lib/languages/csharp'),\n css: () => import('highlight.js/lib/languages/css'),\n diff: () => import('highlight.js/lib/languages/diff'),\n go: () => import('highlight.js/lib/languages/go'),\n graphql: () => import('highlight.js/lib/languages/graphql'),\n ini: () => import('highlight.js/lib/languages/ini'),\n java: () => import('highlight.js/lib/languages/java'),\n javascript: () => import('highlight.js/lib/languages/javascript'),\n json: () => import('highlight.js/lib/languages/json'),\n kotlin: () => import('highlight.js/lib/languages/kotlin'),\n less: () => import('highlight.js/lib/languages/less'),\n lua: () => import('highlight.js/lib/languages/lua'),\n makefile: () => import('highlight.js/lib/languages/makefile'),\n markdown: () => import('highlight.js/lib/languages/markdown'),\n objectivec: () => import('highlight.js/lib/languages/objectivec'),\n perl: () => import('highlight.js/lib/languages/perl'),\n php: () => import('highlight.js/lib/languages/php'),\n python: () => import('highlight.js/lib/languages/python'),\n r: () => import('highlight.js/lib/languages/r'),\n ruby: () => import('highlight.js/lib/languages/ruby'),\n rust: () => import('highlight.js/lib/languages/rust'),\n scss: () => import('highlight.js/lib/languages/scss'),\n shell: () => import('highlight.js/lib/languages/shell'),\n sql: () => import('highlight.js/lib/languages/sql'),\n swift: () => import('highlight.js/lib/languages/swift'),\n typescript: () => import('highlight.js/lib/languages/typescript'),\n xml: () => import('highlight.js/lib/languages/xml'),\n yaml: () => import('highlight.js/lib/languages/yaml'),\n}\n\n/** Languages offered in the code block's language picker. */\nexport const CODE_LANGUAGES = ['plaintext', ...Object.keys(LOADERS)]\n\n\nconst pending = new Map<string, Promise<boolean>>()\n\n/** Loads and registers a grammar. Resolves true when newly registered. */\nexport function loadLanguage(language: string): Promise<boolean> {\n const name = ALIASES[language] ?? language\n if (lowlight.registered(name) || !LOADERS[name]) return Promise.resolve(false)\n if (!pending.has(name)) {\n pending.set(name, LOADERS[name]!().then((mod) => {\n lowlight.register(name, mod.default)\n if (name !== language) lowlight.registerAlias(name, language)\n return true\n }).catch(() => false))\n }\n return pending.get(name)!\n}\n\n/** Re-highlights code blocks in `language` once its grammar arrives. */\nfunction refresh(view: EditorView, language: string) {\n if (view.isDestroyed) return\n const tr = view.state.tr\n view.state.doc.descendants((node, pos) => {\n if (node.type.name === 'codeBlock' && node.attrs.language === language) tr.setNodeMarkup(pos, undefined, node.attrs)\n })\n if (tr.docChanged) view.dispatch(tr.setMeta('addToHistory', false))\n}\n\n/** What Tab inserts in a code block. */\nexport const CODE_INDENT = ' '\n\n/**\n * Tab / Shift-Tab in a code block: indent / outdent. A collapsed selection gets an indent at\n * the cursor; a selection indents (outdents) every line it touches. Always handled inside a\n * code block, so focus never leaves the editor (KS-BUG-5).\n */\nexport function indentCode(editor: Editor, type: NodeType, direction: 1 | -1): boolean {\n const { state } = editor\n const { $from, $to, empty } = state.selection\n if ($from.parent.type !== type) return false\n if (!$to.sameParent($from)) return true\n if (!editor.isEditable) return true\n const tr = state.tr\n if (empty && direction === 1) {\n editor.view.dispatch(tr.insertText(CODE_INDENT).scrollIntoView())\n return true\n }\n const start = $from.start()\n const text = $from.parent.textContent\n // Start offsets of the lines touched by the selection.\n const from = $from.parentOffset\n const to = $to.parentOffset\n // (lastIndexOf with -1 would look at index 0.) A selection ending right at a line start\n // doesn't touch that line.\n const lines: number[] = [from === 0 ? 0 : text.lastIndexOf('\\n', from - 1) + 1]\n for (let i = text.indexOf('\\n', from); i !== -1 && i + 1 < to; i = text.indexOf('\\n', i + 1)) lines.push(i + 1)\n // Right to left, so earlier positions stay valid.\n for (const line of lines.reverse()) {\n if (direction === 1) {\n tr.insertText(CODE_INDENT, start + line)\n continue\n }\n const lead = /^(\\t| {1,2})/.exec(text.slice(line))?.[0]\n if (lead) tr.delete(start + line, start + line + lead.length)\n }\n if (tr.docChanged) editor.view.dispatch(tr.scrollIntoView())\n return true\n}\n\nexport const CodeBlock = CodeBlockLowlight.extend({\n addAttributes() {\n const parent: Record<string, object> = this.parent?.() ?? {}\n // No language stays null: a default here would be filled in for every code block read from\n // a Yjs document (it doesn't store null attributes), turning a pure view into an edit (KS-BUG-4).\n // Highlighting still falls back to `defaultLanguage`.\n return { ...parent, language: { ...parent.language, default: null } }\n },\n addKeyboardShortcuts() {\n return {\n ...this.parent?.(),\n 'Tab': () => indentCode(this.editor, this.type, 1),\n 'Shift-Tab': () => indentCode(this.editor, this.type, -1),\n }\n },\n addProseMirrorPlugins() {\n // One load + one re-highlight per language (not per code block: that was O(n²)).\n const requested = new Set<string>()\n const check = (view: EditorView) => {\n view.state.doc.descendants((node) => {\n const language = node.attrs.language as string | null\n if (node.type.name === 'codeBlock' && language && !requested.has(language)) {\n requested.add(language)\n loadLanguage(language).then(added => added && refresh(view, language))\n }\n return !node.isTextblock\n })\n }\n return [\n ...(this.parent?.() ?? []),\n new Plugin({\n key: new PluginKey('codeBlockLanguages'),\n view: (view) => {\n check(view)\n return { update: (v, prev) => !v.state.doc.eq(prev.doc) && check(v) }\n },\n }),\n ]\n },\n addNodeView() {\n return blockNodeView(CodeBlockView)\n },\n}).configure({ lowlight, defaultLanguage: 'plaintext' })\n","import { Node, mergeAttributes } from '@tiptap/core'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n columns: {\n setColumns: (count: number) => ReturnType\n }\n }\n}\n\nexport const Column = Node.create({\n name: 'column',\n content: 'block+',\n isolating: true,\n\n parseHTML() {\n return [{ tag: 'div[data-type=\"column\"]' }]\n },\n\n renderHTML({ HTMLAttributes }) {\n return ['div', mergeAttributes(HTMLAttributes, { 'data-type': 'column', class: 'me-column' }), 0]\n },\n})\n\nexport const Columns = Node.create({\n name: 'columns',\n group: 'block',\n content: 'column{2,5}',\n isolating: true,\n defining: true,\n\n parseHTML() {\n return [{ tag: 'div[data-type=\"columns\"]' }]\n },\n\n renderHTML({ HTMLAttributes, node }) {\n return ['div', mergeAttributes(HTMLAttributes, {\n 'data-type': 'columns',\n class: 'me-columns',\n style: `--cols:${node.childCount}`,\n }), 0]\n },\n\n addCommands() {\n return {\n setColumns: count => ({ commands }) => commands.insertContent({\n type: this.name,\n content: Array.from({ length: count }, () => ({\n type: 'column',\n content: [{ type: 'paragraph' }],\n })),\n }),\n }\n },\n})\n","import { TableCell, TableHeader, TableKit } from '@tiptap/extension-table'\n\n/** Background color by palette name (`data-color`), so themes and dark mode apply. */\nconst colorAttr = {\n color: {\n default: null,\n parseHTML: (el: HTMLElement) => el.getAttribute('data-color'),\n renderHTML: (attrs: Record<string, any>) => (attrs.color ? { 'data-color': attrs.color } : {}),\n },\n}\n\n// Cells hold paragraphs only (like Notion's simple tables): no images, lists or columns\n// nested in cells, which made tables hard to use.\nconst ColoredCell = TableCell.extend({\n content: 'paragraph+',\n addAttributes() {\n return { ...this.parent?.(), ...colorAttr }\n },\n})\nconst ColoredHeader = TableHeader.extend({\n content: 'paragraph+',\n addAttributes() {\n return { ...this.parent?.(), ...colorAttr }\n },\n})\n\nexport const tableExtensions = [\n TableKit.configure({ table: { resizable: true }, tableCell: false, tableHeader: false }),\n ColoredCell,\n ColoredHeader,\n]\n","import { Details, DetailsContent, DetailsSummary } from '@tiptap/extension-details'\n\n/**\n * Toggle (collapsible) block. `level` turns the summary into a heading, which is how\n * Notion's toggle headings work: the heading's content folds under it.\n */\nexport const ToggleDetails = Details.extend({\n addAttributes() {\n return {\n ...this.parent?.(),\n level: {\n default: null,\n parseHTML: el => Number(el.getAttribute('data-level')) || null,\n renderHTML: attrs => (attrs.level ? { 'data-level': attrs.level } : {}),\n },\n }\n },\n\n // Tiptap's node view doesn't re-render attributes on update; keep level and block\n // colors in sync so changing them shows without a reload.\n //\n // Upstream also opens a toggle created open with a deferred *flip*\n // (`setTimeout(() => toggleDetailsContent())`). If update() runs before that timer\n // (any transaction touching the toggle right after it renders, e.g. typing inside a\n // nested toggle), update() opens it and the timer closes it again: an open toggle shows\n // closed although the document says `open: true`. So until that timer has fired we only\n // remember the latest node, then settle the DOM on its `open` attribute (set, not flip).\n // Remove once upstream sets the value instead of toggling (it still flips in\n // @tiptap/extension-details 3.32.0 through 3.32.2). Covered by test/toggle.test.ts.\n addNodeView() {\n const parent = this.parent?.()\n if (!parent) return null\n return (props) => {\n const view = parent(props)\n type PMNode = typeof props.node\n const upstreamUpdate = view.update?.bind(view) as ((node: PMNode, ...rest: any[]) => boolean) | undefined\n let latest = props.node\n let openPending = Boolean(props.node.attrs.open) && !!upstreamUpdate\n if (openPending) {\n // Queued after upstream's timer (same delay, FIFO), so it runs right after the flip.\n setTimeout(() => {\n openPending = false\n upstreamUpdate?.(latest)\n })\n }\n const dom = view.dom as HTMLElement\n const sync = (attrs: Record<string, any>) => {\n for (const [data, value] of [['data-level', attrs.level], ['data-text-color', attrs.blockColor], ['data-bg-color', attrs.blockBg]]) {\n if (value) dom.setAttribute(data, String(value))\n else dom.removeAttribute(data)\n }\n }\n return Object.assign(view, {\n update: (node: PMNode, ...rest: any[]) => {\n const ok = upstreamUpdate && !openPending ? upstreamUpdate(node, ...rest) : node.type === props.node.type\n if (ok && openPending) latest = node\n if (ok) sync(node.attrs)\n return ok\n },\n })\n }\n },\n}).configure({ persist: true, HTMLAttributes: { class: 'me-toggle' } })\n\nexport const toggleExtensions = [ToggleDetails, DetailsSummary, DetailsContent]\n","import { Code, Columns2, Columns3, Columns4, Heading1, Heading2, Heading3, Lightbulb, ListCollapse, Table } from '@lucide/vue'\nimport type { ChainedCommands } from '@tiptap/core'\nimport { type BlockType, isNode } from '../block-items'\nimport { defineBlock } from '../define-block'\nimport { Callout } from '../extensions/callout'\nimport { CodeBlock } from '../extensions/code-block'\nimport { Column, Columns } from '../extensions/columns'\nimport { tableExtensions } from '../extensions/table'\nimport { toggleExtensions } from '../extensions/toggle'\n\nexport const codeBlock = defineBlock({\n name: 'codeBlock',\n nodes: ['codeBlock'],\n extensions: () => [CodeBlock],\n items: () => [{\n id: 'codeBlock',\n icon: Code,\n group: 'basic',\n keywords: ['code', 'snippet', 'pre', '代码', '代码块'],\n shortcut: '```',\n insert: c => c.setCodeBlock(),\n turnInto: c => c.setCodeBlock(),\n matches: n => n.type.name === 'codeBlock' && n.attrs.language !== 'mermaid',\n }],\n})\n\nexport const callout = defineBlock({\n name: 'callout',\n nodes: ['callout'],\n extensions: () => [Callout],\n items: () => [{\n id: 'callout',\n icon: Lightbulb,\n group: 'advanced',\n keywords: ['callout', 'note', 'info', 'warning', 'ghi chu', '标注', '提示'],\n insert: c => c.setCallout(),\n turnInto: c => c.setCallout(),\n matches: isNode('callout'),\n }],\n})\n\nexport const toggle = defineBlock({\n name: 'toggle',\n nodes: ['details'],\n extensions: () => toggleExtensions,\n items: () => [{\n id: 'toggle',\n icon: ListCollapse,\n group: 'advanced',\n keywords: ['toggle', 'details', 'collapse', 'thu gon', '折叠', '折叠列表'],\n insert: c => c.setDetails(),\n turnInto: c => c.setDetails(),\n matches: n => n.type.name === 'details' && !n.attrs.level,\n }],\n})\n\n/** Sets `level` on the toggle that holds the selection (after setDetails). */\nconst setToggleLevel = (level: number) => (c: ChainedCommands) => c.command(({ tr }) => {\n const { $from } = tr.selection\n for (let d = $from.depth; d > 0; d--) {\n if ($from.node(d).type.name === 'details') {\n tr.setNodeMarkup($from.before(d), undefined, { ...$from.node(d).attrs, level })\n return true\n }\n }\n return false\n})\n\nconst TOGGLE_HEADING_ICONS = { 1: Heading1, 2: Heading2, 3: Heading3 } as const\n\n/** Notion's toggle headings: a heading whose content folds under it. */\nexport const toggleHeading = defineBlock({\n name: 'toggleHeading',\n nodes: ['details'],\n extensions: () => toggleExtensions,\n items: () => ([1, 2, 3] as const).map((level): BlockType => ({\n id: `toggleHeading${level}`,\n icon: TOGGLE_HEADING_ICONS[level],\n group: 'advanced',\n keywords: ['toggle heading', `toggle h${level}`, 'tieu de thu gon', 'collapse', '折叠标题'],\n insert: c => setToggleLevel(level)(c.setDetails()),\n turnInto: c => setToggleLevel(level)(c.setDetails()),\n matches: n => n.type.name === 'details' && n.attrs.level === level,\n })),\n})\n\nexport const table = defineBlock({\n name: 'table',\n nodes: ['table'],\n extensions: () => tableExtensions,\n items: () => [{\n id: 'table',\n icon: Table,\n group: 'advanced',\n keywords: ['table', 'grid', 'bang', '表格'],\n insert: c => c.insertTable({ rows: 3, cols: 3, withHeaderRow: true }),\n matches: isNode('table'),\n }],\n})\n\nconst COLUMN_ICONS = { 2: Columns2, 3: Columns3, 4: Columns4 } as const\n\nexport const columns = defineBlock({\n name: 'columns',\n nodes: ['columns'],\n extensions: () => [Columns, Column],\n items: () => ([2, 3, 4] as const).map((n): BlockType => ({\n id: `columns${n}`,\n icon: COLUMN_ICONS[n],\n group: 'layout',\n keywords: ['columns', 'column', 'cot', 'layout', `${n}`, '分栏', '栏', '布局'],\n insert: c => c.setColumns(n),\n matches: node => node.type.name === 'columns' && node.childCount === n,\n })),\n})\n","import { Heading1, Heading2, Heading3, Heading4, List, ListOrdered, ListTodo, Minus, Quote, Type } from '@lucide/vue'\nimport Heading from '@tiptap/extension-heading'\nimport Blockquote from '@tiptap/extension-blockquote'\nimport HorizontalRule from '@tiptap/extension-horizontal-rule'\nimport { BulletList, ListItem, ListKeymap, OrderedList, TaskItem, TaskList } from '@tiptap/extension-list'\nimport { type BlockType, isNode } from '../block-items'\nimport { defineBlock } from '../define-block'\n\n/** Plain text. Always loaded: the paragraph is part of the editor core. */\nexport const text = defineBlock({\n name: 'text',\n items: () => [{\n id: 'paragraph',\n icon: Type,\n group: 'basic',\n keywords: ['text', 'paragraph', 'p', 'van ban', '文本', '段落'],\n // Already text: Tiptap's setParagraph would then lift the line out of its wrapper.\n // That's right for lists and quotes (\"/text\" drops the bullet, like Notion) but not\n // for callouts, columns, toggles or table cells, where the line should stay put.\n insert: c => c.command(({ state, commands }) => {\n const { $from } = state.selection\n if ($from.parent.type.name !== 'paragraph') return commands.setParagraph()\n const wrapper = $from.depth > 1 ? $from.node($from.depth - 1).type.name : 'doc'\n return ['listItem', 'taskItem', 'blockquote'].includes(wrapper) ? commands.setParagraph() : true\n }),\n turnInto: c => c.setParagraph(),\n matches: isNode('paragraph'),\n }],\n})\n\nconst HEADING_ICONS = { 1: Heading1, 2: Heading2, 3: Heading3, 4: Heading4 } as const\n\nexport const heading = defineBlock<{ levels: (1 | 2 | 3 | 4)[] }>({\n name: 'heading',\n defaults: { levels: [1, 2, 3, 4] },\n nodes: ['heading'],\n extensions: o => [Heading.configure({ levels: o.levels })],\n items: o => o.levels.map((level): BlockType => ({\n id: `heading${level}`,\n icon: HEADING_ICONS[level],\n group: 'basic',\n keywords: [`h${level}`, 'heading', 'tieu de', 'title', '标题'],\n shortcut: '#'.repeat(level),\n insert: c => c.setHeading({ level }),\n turnInto: c => c.setHeading({ level }),\n matches: n => n.type.name === 'heading' && n.attrs.level === level,\n })),\n})\n\nexport const bulletList = defineBlock({\n name: 'bulletList',\n nodes: ['bulletList'],\n extensions: () => [BulletList, ListItem, ListKeymap],\n items: () => [{\n id: 'bulletList',\n icon: List,\n group: 'basic',\n keywords: ['bullet', 'list', 'ul', 'danh sach', '无序列表', '列表'],\n shortcut: '-',\n insert: c => c.toggleBulletList(),\n turnInto: c => c.toggleBulletList(),\n matches: isNode('bulletList'),\n }],\n})\n\nexport const orderedList = defineBlock({\n name: 'orderedList',\n nodes: ['orderedList'],\n extensions: () => [OrderedList, ListItem, ListKeymap],\n items: () => [{\n id: 'orderedList',\n icon: ListOrdered,\n group: 'basic',\n keywords: ['number', 'ordered', 'list', 'ol', 'danh sach so', '有序列表', '编号列表'],\n shortcut: '1.',\n insert: c => c.toggleOrderedList(),\n turnInto: c => c.toggleOrderedList(),\n matches: isNode('orderedList'),\n }],\n})\n\nexport const taskList = defineBlock({\n name: 'taskList',\n nodes: ['taskList'],\n extensions: () => [TaskList, TaskItem.configure({ nested: true })],\n items: () => [{\n id: 'taskList',\n icon: ListTodo,\n group: 'basic',\n keywords: ['todo', 'task', 'checkbox', 'check', 'viec can lam', '待办', '待办清单', '任务'],\n shortcut: '[]',\n insert: c => c.toggleTaskList(),\n turnInto: c => c.toggleTaskList(),\n matches: isNode('taskList'),\n }],\n})\n\nexport const quote = defineBlock({\n name: 'quote',\n nodes: ['blockquote'],\n extensions: () => [Blockquote],\n items: () => [{\n id: 'blockquote',\n icon: Quote,\n group: 'basic',\n keywords: ['quote', 'blockquote', 'trich dan', '引用'],\n shortcut: '>',\n insert: c => c.setBlockquote(),\n turnInto: c => c.setBlockquote(),\n matches: isNode('blockquote'),\n }],\n})\n\nexport const divider = defineBlock({\n name: 'divider',\n nodes: ['horizontalRule'],\n extensions: () => [HorizontalRule],\n items: () => [{\n id: 'divider',\n icon: Minus,\n group: 'basic',\n keywords: ['divider', 'hr', 'line', 'separator', 'duong ke', '分割线', '分隔线'],\n shortcut: '---',\n insert: c => c.setHorizontalRule(),\n matches: isNode('horizontalRule'),\n }],\n})\n","<script setup lang=\"ts\">\nimport { NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport { computed, ref } from 'vue'\nimport { useEditable } from '../composables/useEditable'\nimport { toEmbedUrl } from '../extensions/embed'\n\nconst props = defineProps(nodeViewProps)\nconst editable = useEditable(props.editor)\n\nconst m = computed(() => props.editor.storage.meiConfig.messages.embed)\nconst link = ref('')\nconst error = ref('')\nconst resizing = ref(false)\nconst safeSrc = computed(() => (props.node.attrs.src ? toEmbedUrl(props.node.attrs.src) : null))\n\nfunction submit() {\n const src = toEmbedUrl(link.value)\n if (!src) {\n error.value = m.value.invalid\n return\n }\n props.updateAttributes({ src })\n}\n\nfunction startResize(e: PointerEvent) {\n e.preventDefault()\n resizing.value = true\n const startY = e.clientY\n const startH = props.node.attrs.height as number\n const move = (ev: PointerEvent) => {\n props.updateAttributes({ height: Math.round(Math.min(1200, Math.max(160, startH + ev.clientY - startY))) })\n }\n const up = () => {\n resizing.value = false\n window.removeEventListener('pointermove', move)\n window.removeEventListener('pointerup', up)\n }\n window.addEventListener('pointermove', move)\n window.addEventListener('pointerup', up)\n}\n</script>\n\n<template>\n <NodeViewWrapper class=\"me-media\" :class=\"{ 'is-readonly-empty': !editable && !safeSrc }\">\n <form v-if=\"!safeSrc\" class=\"me-media-empty\" contenteditable=\"false\" @submit.prevent=\"submit\">\n <div class=\"me-hint\">\n {{ m.hint }}\n </div>\n <div class=\"me-inline-form\">\n <input v-model=\"link\" class=\"me-input\" :placeholder=\"m.placeholder\" @keydown.stop>\n <button type=\"submit\" class=\"me-btn me-btn--primary\">\n {{ m.submit }}\n </button>\n </div>\n <p v-if=\"error\" class=\"me-error\">\n {{ error }}\n </p>\n </form>\n <div v-else class=\"me-embed\" :class=\"{ 'is-selected': selected }\" contenteditable=\"false\">\n <iframe\n :src=\"safeSrc\"\n :height=\"node.attrs.height\"\n class=\"me-embed-frame\"\n allowfullscreen\n sandbox=\"allow-scripts allow-same-origin allow-popups allow-presentation\"\n />\n <!-- Iframes swallow pointer events; cover them while resizing. -->\n <div v-if=\"resizing\" class=\"me-embed-overlay\" />\n <span v-if=\"editable\" class=\"me-embed-resize\" @pointerdown=\"startResize\" />\n </div>\n </NodeViewWrapper>\n</template>\n","<script setup lang=\"ts\">\nimport { NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport { computed, ref } from 'vue'\nimport { useEditable } from '../composables/useEditable'\nimport { toEmbedUrl } from '../extensions/embed'\n\nconst props = defineProps(nodeViewProps)\nconst editable = useEditable(props.editor)\n\nconst m = computed(() => props.editor.storage.meiConfig.messages.embed)\nconst link = ref('')\nconst error = ref('')\nconst resizing = ref(false)\nconst safeSrc = computed(() => (props.node.attrs.src ? toEmbedUrl(props.node.attrs.src) : null))\n\nfunction submit() {\n const src = toEmbedUrl(link.value)\n if (!src) {\n error.value = m.value.invalid\n return\n }\n props.updateAttributes({ src })\n}\n\nfunction startResize(e: PointerEvent) {\n e.preventDefault()\n resizing.value = true\n const startY = e.clientY\n const startH = props.node.attrs.height as number\n const move = (ev: PointerEvent) => {\n props.updateAttributes({ height: Math.round(Math.min(1200, Math.max(160, startH + ev.clientY - startY))) })\n }\n const up = () => {\n resizing.value = false\n window.removeEventListener('pointermove', move)\n window.removeEventListener('pointerup', up)\n }\n window.addEventListener('pointermove', move)\n window.addEventListener('pointerup', up)\n}\n</script>\n\n<template>\n <NodeViewWrapper class=\"me-media\" :class=\"{ 'is-readonly-empty': !editable && !safeSrc }\">\n <form v-if=\"!safeSrc\" class=\"me-media-empty\" contenteditable=\"false\" @submit.prevent=\"submit\">\n <div class=\"me-hint\">\n {{ m.hint }}\n </div>\n <div class=\"me-inline-form\">\n <input v-model=\"link\" class=\"me-input\" :placeholder=\"m.placeholder\" @keydown.stop>\n <button type=\"submit\" class=\"me-btn me-btn--primary\">\n {{ m.submit }}\n </button>\n </div>\n <p v-if=\"error\" class=\"me-error\">\n {{ error }}\n </p>\n </form>\n <div v-else class=\"me-embed\" :class=\"{ 'is-selected': selected }\" contenteditable=\"false\">\n <iframe\n :src=\"safeSrc\"\n :height=\"node.attrs.height\"\n class=\"me-embed-frame\"\n allowfullscreen\n sandbox=\"allow-scripts allow-same-origin allow-popups allow-presentation\"\n />\n <!-- Iframes swallow pointer events; cover them while resizing. -->\n <div v-if=\"resizing\" class=\"me-embed-overlay\" />\n <span v-if=\"editable\" class=\"me-embed-resize\" @pointerdown=\"startResize\" />\n </div>\n </NodeViewWrapper>\n</template>\n","import { Node, mergeAttributes } from '@tiptap/core'\nimport { blockNodeView } from '../nodeviews/renderer'\nimport EmbedView from '../nodeviews/EmbedView.vue'\nimport { toEmbedUrl } from './embed-url'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n embed: {\n setEmbed: (attrs?: { src?: string | null }) => ReturnType\n }\n }\n}\n\nexport { toEmbedUrl }\n\nexport const Embed = Node.create({\n name: 'embed',\n group: 'block',\n atom: true,\n draggable: true,\n\n addAttributes() {\n return {\n src: { default: null },\n height: { default: 400 },\n }\n },\n\n parseHTML() {\n return [{\n tag: 'div[data-type=\"embed\"]',\n getAttrs: el => ({\n src: toEmbedUrl(el.querySelector('iframe')?.getAttribute('src') ?? ''),\n height: Number(el.querySelector('iframe')?.getAttribute('height')) || 400,\n }),\n }]\n },\n\n renderHTML({ HTMLAttributes, node }) {\n return ['div', { 'data-type': 'embed' }, ['iframe', mergeAttributes(HTMLAttributes, {\n src: node.attrs.src,\n height: node.attrs.height,\n allowfullscreen: 'true',\n sandbox: 'allow-scripts allow-same-origin allow-popups allow-presentation',\n })]]\n },\n\n addCommands() {\n return {\n setEmbed: attrs => ({ commands }) => commands.insertContent({ type: this.name, attrs }),\n }\n },\n\n addNodeView() {\n return blockNodeView(EmbedView)\n },\n})\n","<script setup lang=\"ts\">\n/**\n * Non-destructive crop: shows the whole image with a draggable crop box (move it or\n * drag its corners/edges). The result is stored as fractions of the original image,\n * so the crop can be changed or reset later.\n */\nimport { onBeforeUnmount, onMounted, ref } from 'vue'\nimport type { EditorMessages } from '../locale'\n\nexport interface ImageCrop {\n /** Left / top / width / height as fractions (0–1) of the original image. */\n x: number\n y: number\n w: number\n h: number\n /** Width / height of the cropped area in pixels, for the block's aspect ratio. */\n ratio: number\n}\n\nconst props = defineProps<{ src: string, alt?: string, crop: ImageCrop | null, messages: EditorMessages['image'] }>()\nconst emit = defineEmits<{ done: [crop: ImageCrop | null], cancel: [] }>()\n\nconst MIN = 0.05\nconst box = ref({ x: props.crop?.x ?? 0, y: props.crop?.y ?? 0, w: props.crop?.w ?? 1, h: props.crop?.h ?? 1 })\nconst stage = ref<HTMLElement | null>(null)\nconst img = ref<HTMLImageElement | null>(null)\n\ntype Handle = 'move' | 'n' | 's' | 'e' | 'w' | 'ne' | 'nw' | 'se' | 'sw'\nconst HANDLES: Handle[] = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w']\nconst clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v))\n\nfunction start(e: PointerEvent, handle: Handle) {\n const rect = stage.value?.getBoundingClientRect()\n if (!rect) return\n e.preventDefault()\n e.stopPropagation()\n const from = { ...box.value }\n const sx = e.clientX\n const sy = e.clientY\n const move = (ev: PointerEvent) => {\n const dx = (ev.clientX - sx) / rect.width\n const dy = (ev.clientY - sy) / rect.height\n let { x, y, w, h } = from\n if (handle === 'move') {\n x = clamp(from.x + dx, 0, 1 - from.w)\n y = clamp(from.y + dy, 0, 1 - from.h)\n }\n else {\n if (handle.includes('w')) {\n x = clamp(from.x + dx, 0, from.x + from.w - MIN)\n w = from.x + from.w - x\n }\n if (handle.includes('e')) w = clamp(from.w + dx, MIN, 1 - from.x)\n if (handle.includes('n')) {\n y = clamp(from.y + dy, 0, from.y + from.h - MIN)\n h = from.y + from.h - y\n }\n if (handle.includes('s')) h = clamp(from.h + dy, MIN, 1 - from.y)\n }\n box.value = { x, y, w, h }\n }\n const up = () => {\n window.removeEventListener('pointermove', move)\n window.removeEventListener('pointerup', up)\n }\n window.addEventListener('pointermove', move)\n window.addEventListener('pointerup', up)\n}\n\nfunction done() {\n const { x, y, w, h } = box.value\n const full = w > 0.995 && h > 0.995\n const natural = img.value\n const ratio = natural?.naturalWidth && natural.naturalHeight ? (w * natural.naturalWidth) / (h * natural.naturalHeight) : w / h\n emit('done', full ? null : { x, y, w, h, ratio })\n}\nconst reset = () => (box.value = { x: 0, y: 0, w: 1, h: 1 })\n\nfunction onKey(e: KeyboardEvent) {\n if (e.key === 'Escape') emit('cancel')\n else if (e.key === 'Enter') done()\n else return\n e.preventDefault()\n e.stopPropagation()\n}\nonMounted(() => window.addEventListener('keydown', onKey, true))\nonBeforeUnmount(() => window.removeEventListener('keydown', onKey, true))\n\nconst pct = (v: number) => `${v * 100}%`\n</script>\n\n<template>\n <div class=\"me-cropper\">\n <div ref=\"stage\" class=\"me-cropper-stage\">\n <img ref=\"img\" class=\"me-figure-img\" :src=\"src\" :alt=\"alt || ''\" draggable=\"false\">\n <!-- Dimming is clipped to the image; the box and its handles are not, so edge handles stay grabbable. -->\n <div class=\"me-cropper-shade\">\n <div class=\"me-cropper-hole\" :style=\"{ left: pct(box.x), top: pct(box.y), width: pct(box.w), height: pct(box.h) }\" />\n </div>\n <div\n class=\"me-cropper-box\"\n :style=\"{ left: pct(box.x), top: pct(box.y), width: pct(box.w), height: pct(box.h) }\"\n @pointerdown=\"start($event, 'move')\"\n >\n <span v-for=\"h in HANDLES\" :key=\"h\" class=\"me-cropper-handle\" :data-handle=\"h\" @pointerdown=\"start($event, h)\" />\n </div>\n </div>\n <div class=\"me-cropper-actions\">\n <button type=\"button\" class=\"me-btn\" @click=\"reset\">\n {{ messages.cropReset }}\n </button>\n <span class=\"me-cropper-spacer\" />\n <button type=\"button\" class=\"me-btn\" @click=\"emit('cancel')\">\n {{ messages.cropCancel }}\n </button>\n <button type=\"button\" class=\"me-btn me-btn--primary\" @click=\"done\">\n {{ messages.cropDone }}\n </button>\n </div>\n </div>\n</template>\n","<script setup lang=\"ts\">\n/**\n * Non-destructive crop: shows the whole image with a draggable crop box (move it or\n * drag its corners/edges). The result is stored as fractions of the original image,\n * so the crop can be changed or reset later.\n */\nimport { onBeforeUnmount, onMounted, ref } from 'vue'\nimport type { EditorMessages } from '../locale'\n\nexport interface ImageCrop {\n /** Left / top / width / height as fractions (0–1) of the original image. */\n x: number\n y: number\n w: number\n h: number\n /** Width / height of the cropped area in pixels, for the block's aspect ratio. */\n ratio: number\n}\n\nconst props = defineProps<{ src: string, alt?: string, crop: ImageCrop | null, messages: EditorMessages['image'] }>()\nconst emit = defineEmits<{ done: [crop: ImageCrop | null], cancel: [] }>()\n\nconst MIN = 0.05\nconst box = ref({ x: props.crop?.x ?? 0, y: props.crop?.y ?? 0, w: props.crop?.w ?? 1, h: props.crop?.h ?? 1 })\nconst stage = ref<HTMLElement | null>(null)\nconst img = ref<HTMLImageElement | null>(null)\n\ntype Handle = 'move' | 'n' | 's' | 'e' | 'w' | 'ne' | 'nw' | 'se' | 'sw'\nconst HANDLES: Handle[] = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w']\nconst clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v))\n\nfunction start(e: PointerEvent, handle: Handle) {\n const rect = stage.value?.getBoundingClientRect()\n if (!rect) return\n e.preventDefault()\n e.stopPropagation()\n const from = { ...box.value }\n const sx = e.clientX\n const sy = e.clientY\n const move = (ev: PointerEvent) => {\n const dx = (ev.clientX - sx) / rect.width\n const dy = (ev.clientY - sy) / rect.height\n let { x, y, w, h } = from\n if (handle === 'move') {\n x = clamp(from.x + dx, 0, 1 - from.w)\n y = clamp(from.y + dy, 0, 1 - from.h)\n }\n else {\n if (handle.includes('w')) {\n x = clamp(from.x + dx, 0, from.x + from.w - MIN)\n w = from.x + from.w - x\n }\n if (handle.includes('e')) w = clamp(from.w + dx, MIN, 1 - from.x)\n if (handle.includes('n')) {\n y = clamp(from.y + dy, 0, from.y + from.h - MIN)\n h = from.y + from.h - y\n }\n if (handle.includes('s')) h = clamp(from.h + dy, MIN, 1 - from.y)\n }\n box.value = { x, y, w, h }\n }\n const up = () => {\n window.removeEventListener('pointermove', move)\n window.removeEventListener('pointerup', up)\n }\n window.addEventListener('pointermove', move)\n window.addEventListener('pointerup', up)\n}\n\nfunction done() {\n const { x, y, w, h } = box.value\n const full = w > 0.995 && h > 0.995\n const natural = img.value\n const ratio = natural?.naturalWidth && natural.naturalHeight ? (w * natural.naturalWidth) / (h * natural.naturalHeight) : w / h\n emit('done', full ? null : { x, y, w, h, ratio })\n}\nconst reset = () => (box.value = { x: 0, y: 0, w: 1, h: 1 })\n\nfunction onKey(e: KeyboardEvent) {\n if (e.key === 'Escape') emit('cancel')\n else if (e.key === 'Enter') done()\n else return\n e.preventDefault()\n e.stopPropagation()\n}\nonMounted(() => window.addEventListener('keydown', onKey, true))\nonBeforeUnmount(() => window.removeEventListener('keydown', onKey, true))\n\nconst pct = (v: number) => `${v * 100}%`\n</script>\n\n<template>\n <div class=\"me-cropper\">\n <div ref=\"stage\" class=\"me-cropper-stage\">\n <img ref=\"img\" class=\"me-figure-img\" :src=\"src\" :alt=\"alt || ''\" draggable=\"false\">\n <!-- Dimming is clipped to the image; the box and its handles are not, so edge handles stay grabbable. -->\n <div class=\"me-cropper-shade\">\n <div class=\"me-cropper-hole\" :style=\"{ left: pct(box.x), top: pct(box.y), width: pct(box.w), height: pct(box.h) }\" />\n </div>\n <div\n class=\"me-cropper-box\"\n :style=\"{ left: pct(box.x), top: pct(box.y), width: pct(box.w), height: pct(box.h) }\"\n @pointerdown=\"start($event, 'move')\"\n >\n <span v-for=\"h in HANDLES\" :key=\"h\" class=\"me-cropper-handle\" :data-handle=\"h\" @pointerdown=\"start($event, h)\" />\n </div>\n </div>\n <div class=\"me-cropper-actions\">\n <button type=\"button\" class=\"me-btn\" @click=\"reset\">\n {{ messages.cropReset }}\n </button>\n <span class=\"me-cropper-spacer\" />\n <button type=\"button\" class=\"me-btn\" @click=\"emit('cancel')\">\n {{ messages.cropCancel }}\n </button>\n <button type=\"button\" class=\"me-btn me-btn--primary\" @click=\"done\">\n {{ messages.cropDone }}\n </button>\n </div>\n </div>\n</template>\n","<script setup lang=\"ts\">\n/**\n * Full-screen image viewer (Notion's zoom): fit to screen, zoom with the buttons,\n * wheel, +/- or double-click, drag to pan when zoomed, Esc to close.\n */\nimport { Download, Minus, Plus, X } from '@lucide/vue'\nimport { computed, onBeforeUnmount, onMounted, ref } from 'vue'\nimport type { EditorMessages } from '../locale'\n\ndefineProps<{ src: string, alt?: string, messages: EditorMessages['image'], scope: Record<string, unknown> }>()\nconst emit = defineEmits<{ close: [], download: [] }>()\n\nconst MIN = 0.25\nconst MAX = 8\nconst zoom = ref(1)\nconst pan = ref({ x: 0, y: 0 })\nconst percent = computed(() => `${Math.round(zoom.value * 100)}%`)\n\nfunction setZoom(next: number) {\n zoom.value = Math.min(MAX, Math.max(MIN, Math.round(next * 100) / 100))\n if (zoom.value <= 1) pan.value = { x: 0, y: 0 }\n}\nconst zoomIn = () => setZoom(zoom.value * 1.25)\nconst zoomOut = () => setZoom(zoom.value / 1.25)\nconst reset = () => setZoom(1)\n\nfunction onWheel(e: WheelEvent) {\n e.preventDefault()\n setZoom(zoom.value * (e.deltaY < 0 ? 1.1 : 1 / 1.1))\n}\n\nlet drag: { x: number, y: number, px: number, py: number } | null = null\nconst dragging = ref(false)\nfunction onPointerDown(e: PointerEvent) {\n if (zoom.value <= 1) return\n e.preventDefault()\n drag = { x: e.clientX, y: e.clientY, px: pan.value.x, py: pan.value.y }\n dragging.value = true\n ;(e.target as HTMLElement).setPointerCapture(e.pointerId)\n}\nfunction onPointerMove(e: PointerEvent) {\n if (!drag) return\n pan.value = { x: drag.px + e.clientX - drag.x, y: drag.py + e.clientY - drag.y }\n}\nfunction onPointerUp() {\n drag = null\n dragging.value = false\n}\n\nfunction onKey(e: KeyboardEvent) {\n if (e.key === 'Escape') emit('close')\n else if (e.key === '+' || e.key === '=') zoomIn()\n else if (e.key === '-') zoomOut()\n else if (e.key === '0') reset()\n else return\n e.preventDefault()\n e.stopPropagation()\n}\nonMounted(() => window.addEventListener('keydown', onKey, true))\nonBeforeUnmount(() => window.removeEventListener('keydown', onKey, true))\n</script>\n\n<template>\n <Teleport to=\"body\">\n <div v-bind=\"scope\" class=\"me-lightbox\" role=\"dialog\" aria-modal=\"true\" @mousedown.self=\"emit('close')\" @wheel=\"onWheel\">\n <img\n class=\"me-lightbox-img\"\n :class=\"{ 'is-zoomed': zoom > 1, 'is-dragging': dragging }\"\n :src=\"src\"\n :alt=\"alt || ''\"\n draggable=\"false\"\n :style=\"{ transform: `translate(${pan.x}px, ${pan.y}px) scale(${zoom})` }\"\n @dblclick=\"zoom > 1 ? reset() : setZoom(2)\"\n @pointerdown=\"onPointerDown\"\n @pointermove=\"onPointerMove\"\n @pointerup=\"onPointerUp\"\n @pointercancel=\"onPointerUp\"\n >\n <div class=\"me-popover me-toolbar me-lightbox-toolbar\" @mousedown.stop>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"messages.zoomOut\" :disabled=\"zoom <= MIN\" @click=\"zoomOut\">\n <Minus />\n </button>\n <button type=\"button\" class=\"me-tool-btn me-lightbox-percent\" :title=\"messages.zoomReset\" @click=\"reset\">\n {{ percent }}\n </button>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"messages.zoomIn\" :disabled=\"zoom >= MAX\" @click=\"zoomIn\">\n <Plus />\n </button>\n <span class=\"me-toolbar-divider\" />\n <button type=\"button\" class=\"me-tool-btn\" :title=\"messages.download\" @click=\"emit('download')\">\n <Download />\n </button>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"messages.close\" @click=\"emit('close')\">\n <X />\n </button>\n </div>\n </div>\n </Teleport>\n</template>\n","<script setup lang=\"ts\">\n/**\n * Full-screen image viewer (Notion's zoom): fit to screen, zoom with the buttons,\n * wheel, +/- or double-click, drag to pan when zoomed, Esc to close.\n */\nimport { Download, Minus, Plus, X } from '@lucide/vue'\nimport { computed, onBeforeUnmount, onMounted, ref } from 'vue'\nimport type { EditorMessages } from '../locale'\n\ndefineProps<{ src: string, alt?: string, messages: EditorMessages['image'], scope: Record<string, unknown> }>()\nconst emit = defineEmits<{ close: [], download: [] }>()\n\nconst MIN = 0.25\nconst MAX = 8\nconst zoom = ref(1)\nconst pan = ref({ x: 0, y: 0 })\nconst percent = computed(() => `${Math.round(zoom.value * 100)}%`)\n\nfunction setZoom(next: number) {\n zoom.value = Math.min(MAX, Math.max(MIN, Math.round(next * 100) / 100))\n if (zoom.value <= 1) pan.value = { x: 0, y: 0 }\n}\nconst zoomIn = () => setZoom(zoom.value * 1.25)\nconst zoomOut = () => setZoom(zoom.value / 1.25)\nconst reset = () => setZoom(1)\n\nfunction onWheel(e: WheelEvent) {\n e.preventDefault()\n setZoom(zoom.value * (e.deltaY < 0 ? 1.1 : 1 / 1.1))\n}\n\nlet drag: { x: number, y: number, px: number, py: number } | null = null\nconst dragging = ref(false)\nfunction onPointerDown(e: PointerEvent) {\n if (zoom.value <= 1) return\n e.preventDefault()\n drag = { x: e.clientX, y: e.clientY, px: pan.value.x, py: pan.value.y }\n dragging.value = true\n ;(e.target as HTMLElement).setPointerCapture(e.pointerId)\n}\nfunction onPointerMove(e: PointerEvent) {\n if (!drag) return\n pan.value = { x: drag.px + e.clientX - drag.x, y: drag.py + e.clientY - drag.y }\n}\nfunction onPointerUp() {\n drag = null\n dragging.value = false\n}\n\nfunction onKey(e: KeyboardEvent) {\n if (e.key === 'Escape') emit('close')\n else if (e.key === '+' || e.key === '=') zoomIn()\n else if (e.key === '-') zoomOut()\n else if (e.key === '0') reset()\n else return\n e.preventDefault()\n e.stopPropagation()\n}\nonMounted(() => window.addEventListener('keydown', onKey, true))\nonBeforeUnmount(() => window.removeEventListener('keydown', onKey, true))\n</script>\n\n<template>\n <Teleport to=\"body\">\n <div v-bind=\"scope\" class=\"me-lightbox\" role=\"dialog\" aria-modal=\"true\" @mousedown.self=\"emit('close')\" @wheel=\"onWheel\">\n <img\n class=\"me-lightbox-img\"\n :class=\"{ 'is-zoomed': zoom > 1, 'is-dragging': dragging }\"\n :src=\"src\"\n :alt=\"alt || ''\"\n draggable=\"false\"\n :style=\"{ transform: `translate(${pan.x}px, ${pan.y}px) scale(${zoom})` }\"\n @dblclick=\"zoom > 1 ? reset() : setZoom(2)\"\n @pointerdown=\"onPointerDown\"\n @pointermove=\"onPointerMove\"\n @pointerup=\"onPointerUp\"\n @pointercancel=\"onPointerUp\"\n >\n <div class=\"me-popover me-toolbar me-lightbox-toolbar\" @mousedown.stop>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"messages.zoomOut\" :disabled=\"zoom <= MIN\" @click=\"zoomOut\">\n <Minus />\n </button>\n <button type=\"button\" class=\"me-tool-btn me-lightbox-percent\" :title=\"messages.zoomReset\" @click=\"reset\">\n {{ percent }}\n </button>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"messages.zoomIn\" :disabled=\"zoom >= MAX\" @click=\"zoomIn\">\n <Plus />\n </button>\n <span class=\"me-toolbar-divider\" />\n <button type=\"button\" class=\"me-tool-btn\" :title=\"messages.download\" @click=\"emit('download')\">\n <Download />\n </button>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"messages.close\" @click=\"emit('close')\">\n <X />\n </button>\n </div>\n </div>\n </Teleport>\n</template>\n","import type { Editor } from '@tiptap/core'\nimport type { Node as PMNode } from '@tiptap/pm/model'\nimport { computed, onBeforeUnmount, ref, watchEffect } from 'vue'\nimport { pendingUpload, uploadStaleAt, uploadState } from '../extensions/file-drop'\n\n/**\n * Upload state of an image / file node view (`uploadState`), re-evaluated when an `uploading` node without a local\n * file becomes stale (shown as interrupted).\n */\nexport function useUploadState(editor: Editor, node: () => PMNode) {\n const now = ref(Date.now())\n let timer: ReturnType<typeof setTimeout> | null = null\n const stop = () => {\n if (timer) clearTimeout(timer)\n timer = null\n }\n const pending = computed(() => pendingUpload(editor, node().attrs.uploadId))\n const state = computed(() => uploadState(editor, node().attrs, now.value))\n watchEffect(() => {\n stop()\n if (state.value !== 'remote') return\n const at = uploadStaleAt(editor, node().attrs, now.value)\n timer = setTimeout(() => (now.value = Date.now()), Math.max(0, at - now.value) + 50)\n })\n onBeforeUnmount(stop)\n return { pending, state }\n}\n","<script setup lang=\"ts\">\nimport { NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport {\n AlignCenter, AlignLeft, AlignRight, Captions, Check, Copy, Crop, Download, Ellipsis, ExternalLink,\n Image as ImageIcon, Link as LinkIcon, RefreshCw, Trash, Upload, ZoomIn,\n} from '@lucide/vue'\nimport { computed, nextTick, ref } from 'vue'\nimport ImageCropper, { type ImageCrop } from '../components/ImageCropper.vue'\nimport ImageLightbox from '../components/ImageLightbox.vue'\nimport { useClickOutside } from '../composables/useClickOutside'\nimport { useEditable } from '../composables/useEditable'\nimport { useScope } from '../composables/useScope'\nimport { isSameOrigin, isWebUrl, safeUrl } from '../safe-url'\nimport { runUpload, type UploadError } from '../extensions/file-drop'\nimport { useUploadState } from '../composables/useUploadState'\n\nconst props = defineProps(nodeViewProps)\nconst editable = useEditable(props.editor)\n\nconst config = computed(() => props.editor.storage.meiConfig)\nconst m = computed(() => config.value.messages.image)\nconst tab = ref<'upload' | 'link'>('upload')\nconst link = ref('')\nconst error = ref('')\nconst uploading = ref(false)\nconst fileInput = ref<HTMLInputElement | null>(null)\nconst figure = ref<HTMLElement | null>(null)\nconst scope = useScope(() => props.editor)\n\n// --- Pasted / dropped image (FileDrop): local preview, progress, error + retry ----------\n// `local`: this tab owns the file; `remote`: another tab uploads it; `interrupted`: stale (> 2 min, nobody here).\nconst { pending, state: uploadState } = useUploadState(props.editor, () => props.node)\nconst uploadError = computed(() => props.node.attrs.error as UploadError | null)\nconst isPending = computed(() => !props.node.attrs.src && (!!props.node.attrs.uploading || !!uploadError.value))\nconst progress = computed(() => `${Math.round((pending.value?.progress ?? 0) * 100)}%`)\nconst uploadErrorText = computed(() => {\n const e = uploadError.value\n return e === 'tooLarge' ? m.value.tooLarge(config.value.maxImageSize) : e === 'badType' ? m.value.badType : m.value.uploadFailed\n})\n\nconst readAsDataUrl = (file: File) => new Promise<string>((resolve, reject) => {\n const reader = new FileReader()\n reader.onload = () => resolve(reader.result as string)\n reader.onerror = () => reject(reader.error)\n reader.readAsDataURL(file)\n})\n\nasync function handleFile(file: File) {\n error.value = ''\n const maxMb = config.value.maxImageSize\n if (!file.type.startsWith('image/')) return (error.value = m.value.notImage)\n if (file.size > maxMb * 1024 * 1024) return (error.value = m.value.tooLarge(maxMb))\n\n uploading.value = true\n try {\n const upload = config.value.uploadImage\n const src = upload ? await upload(file) : await readAsDataUrl(file)\n // A new image starts uncropped.\n props.updateAttributes({ src, alt: file.name, crop: null })\n }\n catch {\n error.value = m.value.uploadFailed\n }\n finally {\n uploading.value = false\n }\n}\n\nfunction onFileChange(e: Event) {\n const file = (e.target as HTMLInputElement).files?.[0]\n if (file) handleFile(file)\n}\n\nfunction onDrop(e: DragEvent) {\n const file = e.dataTransfer?.files?.[0]\n if (!file) return\n e.preventDefault()\n e.stopPropagation()\n handleFile(file)\n}\n\nfunction submitLink() {\n error.value = ''\n try {\n const url = new URL(link.value.trim())\n if (!/^https?:$/.test(url.protocol)) throw new Error('bad protocol')\n props.updateAttributes({ src: url.toString() })\n }\n catch {\n error.value = m.value.invalidLink\n }\n}\n\n// Resize from either side; the image stays centered so both sides move.\nfunction startResize(e: PointerEvent, side: 1 | -1) {\n const parent = figure.value?.parentElement\n if (!parent) return\n e.preventDefault()\n const startX = e.clientX\n const startWidth = props.node.attrs.width as number\n const total = parent.getBoundingClientRect().width\n const move = (ev: PointerEvent) => {\n // Centered images grow on both sides, aligned ones on one.\n const factor = align.value === 'center' ? 2 : 1\n const delta = ((ev.clientX - startX) * side * factor / total) * 100\n props.updateAttributes({ width: Math.round(Math.min(100, Math.max(15, startWidth + delta))) })\n }\n const up = () => {\n window.removeEventListener('pointermove', move)\n window.removeEventListener('pointerup', up)\n }\n window.addEventListener('pointermove', move)\n window.addEventListener('pointerup', up)\n}\n\n// --- Toolbar (like Notion's image menu) ---------------------------------------------\ntype Align = 'left' | 'center' | 'right'\nconst align = computed(() => (props.node.attrs.align ?? 'center') as Align)\nconst ALIGN_ICONS = { left: AlignLeft, center: AlignCenter, right: AlignRight }\nconst crop = computed(() => props.node.attrs.crop as ImageCrop | null)\nconst captionShown = computed(() => props.node.attrs.showCaption ?? !!props.node.attrs.caption)\n/** The image URL if it is safe to load and open (KS-BUG-7: never `javascript:` / `data:text/html`). */\nconst src = computed(() => safeUrl(props.node.attrs.src, 'image'))\n/** A web URL (link actions apply); `isRemote` when it is on another origin (download fetches it). */\nconst isWeb = computed(() => !!src.value && isWebUrl(src.value))\nconst isRemote = computed(() => isWeb.value && !isSameOrigin(src.value!))\n\nconst menu = ref<'align' | 'more' | null>(null)\nconst toolbar = ref<HTMLElement | null>(null)\nuseClickOutside(toolbar, computed(() => menu.value !== null), () => (menu.value = null))\nconst captionInput = ref<HTMLInputElement | null>(null)\nconst cropping = ref(false)\nconst viewing = ref(false)\nconst copied = ref(false)\n\nfunction setAlign(value: Align) {\n props.updateAttributes({ align: value })\n menu.value = null\n}\nfunction toggleCaption() {\n const show = !captionShown.value\n props.updateAttributes({ showCaption: show })\n if (show) nextTick(() => captionInput.value?.focus())\n}\nfunction finishCrop(value: ImageCrop | null) {\n props.updateAttributes({ crop: value })\n cropping.value = false\n}\n\n/** Saves the original file; cross-origin links that refuse fetch open in a new tab. */\nasync function download() {\n const url = src.value\n if (!url) return\n const name = (props.node.attrs.alt as string) || 'image'\n const save = (href: string) => {\n const a = document.createElement('a')\n a.href = href\n a.download = name\n a.click()\n }\n if (!isRemote.value) return save(url)\n try {\n const blob = await (await fetch(url)).blob()\n const objectUrl = URL.createObjectURL(blob)\n save(objectUrl)\n setTimeout(() => URL.revokeObjectURL(objectUrl), 1000)\n }\n catch {\n window.open(url, '_blank', 'noopener')\n }\n}\n\nasync function copyLink() {\n if (!src.value) return\n await navigator.clipboard?.writeText(new URL(src.value, location.href).href)\n copied.value = true\n setTimeout(() => (copied.value = false), 1500)\n menu.value = null\n}\nfunction replace() {\n menu.value = null\n fileInput.value?.click()\n}\nfunction openOriginal() {\n menu.value = null\n if (src.value) window.open(src.value, '_blank', 'noopener')\n}\nfunction remove() {\n menu.value = null\n props.deleteNode()\n}\n\n// Cropped view: the frame takes the crop's aspect ratio and the image is offset inside it.\nconst cropStyle = computed(() => {\n const c = crop.value\n if (!c) return undefined\n return {\n width: `${100 / c.w}%`,\n left: `${(-c.x / c.w) * 100}%`,\n top: `${(-c.y / c.h) * 100}%`,\n }\n})\n</script>\n\n<template>\n <NodeViewWrapper class=\"me-media\" :class=\"{ 'is-readonly-empty': !editable && !node.attrs.src && !isPending }\">\n <div v-if=\"isPending\" class=\"me-media-pending\" :class=\"{ 'is-failed': !!uploadError || uploadState === 'interrupted' }\" contenteditable=\"false\">\n <img v-if=\"pending?.preview\" :src=\"pending.preview\" :alt=\"node.attrs.alt || ''\" class=\"me-media-preview\" draggable=\"false\">\n <div class=\"me-media-status\" role=\"status\">\n <template v-if=\"uploadState === 'interrupted'\">\n <!-- Its tab went away mid-upload: any editor can remove it. -->\n <span class=\"me-error me-media-status-error\">{{ m.uploadInterrupted }}</span>\n <button v-if=\"editable\" type=\"button\" class=\"me-btn\" @click=\"deleteNode()\">\n <Trash /> {{ m.delete }}\n </button>\n </template>\n <template v-else-if=\"!uploadError\">\n <span>{{ m.uploading }}</span>\n <!-- Progress and Delete only in the tab that owns the file; others just see it uploading. -->\n <span v-if=\"pending\" class=\"me-media-progress\"><span class=\"me-media-progress-bar\" :style=\"{ width: progress }\" /></span>\n <button v-if=\"editable && pending\" type=\"button\" class=\"me-btn\" @click=\"deleteNode()\">\n <Trash /> {{ m.delete }}\n </button>\n </template>\n <template v-else>\n <span class=\"me-error me-media-status-error\">{{ uploadErrorText }}</span>\n <button v-if=\"editable && pending && uploadError === 'failed'\" type=\"button\" class=\"me-btn\" @click=\"runUpload(editor, node.attrs.uploadId)\">\n <RefreshCw /> {{ m.retry }}\n </button>\n <button v-if=\"editable\" type=\"button\" class=\"me-btn\" @click=\"deleteNode()\">\n <Trash /> {{ m.delete }}\n </button>\n </template>\n </div>\n </div>\n <div v-else-if=\"!node.attrs.src\" class=\"me-media-empty\" contenteditable=\"false\" @dragover.prevent @drop=\"onDrop\">\n <div class=\"me-tabs\">\n <button\n v-for=\"t in (['upload', 'link'] as const)\"\n :key=\"t\"\n type=\"button\"\n class=\"me-tab\"\n :class=\"{ 'is-active': tab === t }\"\n @click=\"tab = t\"\n >\n <component :is=\"t === 'upload' ? Upload : LinkIcon\" />\n {{ t === 'upload' ? m.upload : m.link }}\n </button>\n </div>\n <div v-if=\"tab === 'upload'\" class=\"me-media-body\">\n <button type=\"button\" class=\"me-btn\" :disabled=\"uploading\" @click=\"fileInput?.click()\">\n <ImageIcon /> {{ uploading ? m.uploading : m.choose }}\n </button>\n <p class=\"me-hint\">\n {{ m.dropHint(config.maxImageSize) }}\n </p>\n <input ref=\"fileInput\" type=\"file\" accept=\"image/*\" hidden @change=\"onFileChange\">\n </div>\n <form v-else class=\"me-inline-form\" @submit.prevent=\"submitLink\">\n <input v-model=\"link\" class=\"me-input\" placeholder=\"https://...\" @keydown.stop>\n <button type=\"submit\" class=\"me-btn me-btn--primary\">\n {{ m.insert }}\n </button>\n </form>\n <p v-if=\"error\" class=\"me-error\">\n {{ error }}\n </p>\n </div>\n\n <figure\n v-else\n ref=\"figure\"\n class=\"me-figure\"\n :class=\"`me-figure--${align}`\"\n :style=\"{ width: `${node.attrs.width}%` }\"\n >\n <ImageCropper\n v-if=\"cropping && src\"\n :src=\"src\"\n :alt=\"node.attrs.alt\"\n :crop=\"crop\"\n :messages=\"m\"\n @done=\"finishCrop\"\n @cancel=\"cropping = false\"\n />\n <div\n v-else\n class=\"me-figure-frame\"\n :class=\"{ 'is-selected': selected, 'is-menu-open': menu !== null }\"\n >\n <!-- Only this layer clips (for crops), so the toolbar's menus can overflow the frame. -->\n <div class=\"me-figure-media\" :class=\"{ 'is-cropped': !!crop }\" :style=\"crop ? { aspectRatio: String(crop.ratio) } : undefined\">\n <img v-if=\"src\" :src=\"src\" :alt=\"node.attrs.alt || ''\" class=\"me-figure-img\" :style=\"cropStyle\" draggable=\"false\" @dblclick=\"viewing = true\">\n <p v-else class=\"me-error me-image-blocked\">\n {{ m.invalidLink }}\n </p>\n </div>\n\n <div ref=\"toolbar\" class=\"me-popover me-toolbar me-image-toolbar\" contenteditable=\"false\" @mousedown.stop>\n <template v-if=\"editable\">\n <div class=\"me-image-menu-anchor\">\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.align\" @click=\"menu = menu === 'align' ? null : 'align'\">\n <component :is=\"ALIGN_ICONS[align]\" />\n </button>\n <div v-if=\"menu === 'align'\" class=\"me-popover me-menu me-image-menu\">\n <button v-for=\"a in (['left', 'center', 'right'] as const)\" :key=\"a\" type=\"button\" class=\"me-menu-item\" @click=\"setAlign(a)\">\n <span class=\"me-menu-icon\"><component :is=\"ALIGN_ICONS[a]\" /></span>\n <span class=\"me-menu-title me-menu-text\">{{ m.alignments[a] }}</span>\n <Check v-if=\"align === a\" class=\"me-menu-check\" />\n </button>\n </div>\n </div>\n <button type=\"button\" class=\"me-tool-btn\" :class=\"{ 'is-active': captionShown }\" :title=\"m.captionToggle\" @click=\"toggleCaption\">\n <Captions />\n </button>\n <button type=\"button\" class=\"me-tool-btn\" :class=\"{ 'is-active': !!crop }\" :title=\"m.crop\" @click=\"cropping = true\">\n <Crop />\n </button>\n </template>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.zoom\" @click=\"viewing = true\">\n <ZoomIn />\n </button>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.download\" @click=\"download\">\n <Download />\n </button>\n <div class=\"me-image-menu-anchor\">\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.more\" @click=\"menu = menu === 'more' ? null : 'more'\">\n <Ellipsis />\n </button>\n <div v-if=\"menu === 'more'\" class=\"me-popover me-menu me-image-menu\">\n <button v-if=\"editable\" type=\"button\" class=\"me-menu-item\" @click=\"replace\">\n <span class=\"me-menu-icon\"><RefreshCw /></span>\n <span class=\"me-menu-title me-menu-text\">{{ m.replace }}</span>\n </button>\n <button v-if=\"isWeb\" type=\"button\" class=\"me-menu-item\" @click=\"copyLink\">\n <span class=\"me-menu-icon\"><component :is=\"copied ? Check : Copy\" /></span>\n <span class=\"me-menu-title me-menu-text\">{{ copied ? m.linkCopied : m.copyLink }}</span>\n </button>\n <button v-if=\"isWeb\" type=\"button\" class=\"me-menu-item\" @click=\"openOriginal\">\n <span class=\"me-menu-icon\"><ExternalLink /></span>\n <span class=\"me-menu-title me-menu-text\">{{ m.original }}</span>\n </button>\n <button v-if=\"editable\" type=\"button\" class=\"me-menu-item is-danger\" @click=\"remove\">\n <span class=\"me-menu-icon\"><Trash /></span>\n <span class=\"me-menu-title me-menu-text\">{{ m.delete }}</span>\n </button>\n </div>\n </div>\n </div>\n\n <template v-if=\"editable\">\n <span class=\"me-resize-handle me-resize-handle--left\" @pointerdown=\"startResize($event, -1)\" />\n <span class=\"me-resize-handle me-resize-handle--right\" @pointerdown=\"startResize($event, 1)\" />\n </template>\n </div>\n <input\n v-if=\"captionShown && !cropping\"\n ref=\"captionInput\"\n class=\"me-caption\"\n :value=\"node.attrs.caption\"\n :readonly=\"!editable\"\n :placeholder=\"editable ? m.caption : ''\"\n @input=\"updateAttributes({ caption: ($event.target as HTMLInputElement).value })\"\n @keydown.stop\n >\n <input ref=\"fileInput\" type=\"file\" accept=\"image/*\" hidden @change=\"onFileChange\">\n <p v-if=\"error\" class=\"me-error\">\n {{ error }}\n </p>\n </figure>\n\n <ImageLightbox\n v-if=\"viewing && src\"\n :src=\"src\"\n :alt=\"node.attrs.alt\"\n :messages=\"m\"\n :scope=\"scope\"\n @close=\"viewing = false\"\n @download=\"download\"\n />\n </NodeViewWrapper>\n</template>\n","<script setup lang=\"ts\">\nimport { NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport {\n AlignCenter, AlignLeft, AlignRight, Captions, Check, Copy, Crop, Download, Ellipsis, ExternalLink,\n Image as ImageIcon, Link as LinkIcon, RefreshCw, Trash, Upload, ZoomIn,\n} from '@lucide/vue'\nimport { computed, nextTick, ref } from 'vue'\nimport ImageCropper, { type ImageCrop } from '../components/ImageCropper.vue'\nimport ImageLightbox from '../components/ImageLightbox.vue'\nimport { useClickOutside } from '../composables/useClickOutside'\nimport { useEditable } from '../composables/useEditable'\nimport { useScope } from '../composables/useScope'\nimport { isSameOrigin, isWebUrl, safeUrl } from '../safe-url'\nimport { runUpload, type UploadError } from '../extensions/file-drop'\nimport { useUploadState } from '../composables/useUploadState'\n\nconst props = defineProps(nodeViewProps)\nconst editable = useEditable(props.editor)\n\nconst config = computed(() => props.editor.storage.meiConfig)\nconst m = computed(() => config.value.messages.image)\nconst tab = ref<'upload' | 'link'>('upload')\nconst link = ref('')\nconst error = ref('')\nconst uploading = ref(false)\nconst fileInput = ref<HTMLInputElement | null>(null)\nconst figure = ref<HTMLElement | null>(null)\nconst scope = useScope(() => props.editor)\n\n// --- Pasted / dropped image (FileDrop): local preview, progress, error + retry ----------\n// `local`: this tab owns the file; `remote`: another tab uploads it; `interrupted`: stale (> 2 min, nobody here).\nconst { pending, state: uploadState } = useUploadState(props.editor, () => props.node)\nconst uploadError = computed(() => props.node.attrs.error as UploadError | null)\nconst isPending = computed(() => !props.node.attrs.src && (!!props.node.attrs.uploading || !!uploadError.value))\nconst progress = computed(() => `${Math.round((pending.value?.progress ?? 0) * 100)}%`)\nconst uploadErrorText = computed(() => {\n const e = uploadError.value\n return e === 'tooLarge' ? m.value.tooLarge(config.value.maxImageSize) : e === 'badType' ? m.value.badType : m.value.uploadFailed\n})\n\nconst readAsDataUrl = (file: File) => new Promise<string>((resolve, reject) => {\n const reader = new FileReader()\n reader.onload = () => resolve(reader.result as string)\n reader.onerror = () => reject(reader.error)\n reader.readAsDataURL(file)\n})\n\nasync function handleFile(file: File) {\n error.value = ''\n const maxMb = config.value.maxImageSize\n if (!file.type.startsWith('image/')) return (error.value = m.value.notImage)\n if (file.size > maxMb * 1024 * 1024) return (error.value = m.value.tooLarge(maxMb))\n\n uploading.value = true\n try {\n const upload = config.value.uploadImage\n const src = upload ? await upload(file) : await readAsDataUrl(file)\n // A new image starts uncropped.\n props.updateAttributes({ src, alt: file.name, crop: null })\n }\n catch {\n error.value = m.value.uploadFailed\n }\n finally {\n uploading.value = false\n }\n}\n\nfunction onFileChange(e: Event) {\n const file = (e.target as HTMLInputElement).files?.[0]\n if (file) handleFile(file)\n}\n\nfunction onDrop(e: DragEvent) {\n const file = e.dataTransfer?.files?.[0]\n if (!file) return\n e.preventDefault()\n e.stopPropagation()\n handleFile(file)\n}\n\nfunction submitLink() {\n error.value = ''\n try {\n const url = new URL(link.value.trim())\n if (!/^https?:$/.test(url.protocol)) throw new Error('bad protocol')\n props.updateAttributes({ src: url.toString() })\n }\n catch {\n error.value = m.value.invalidLink\n }\n}\n\n// Resize from either side; the image stays centered so both sides move.\nfunction startResize(e: PointerEvent, side: 1 | -1) {\n const parent = figure.value?.parentElement\n if (!parent) return\n e.preventDefault()\n const startX = e.clientX\n const startWidth = props.node.attrs.width as number\n const total = parent.getBoundingClientRect().width\n const move = (ev: PointerEvent) => {\n // Centered images grow on both sides, aligned ones on one.\n const factor = align.value === 'center' ? 2 : 1\n const delta = ((ev.clientX - startX) * side * factor / total) * 100\n props.updateAttributes({ width: Math.round(Math.min(100, Math.max(15, startWidth + delta))) })\n }\n const up = () => {\n window.removeEventListener('pointermove', move)\n window.removeEventListener('pointerup', up)\n }\n window.addEventListener('pointermove', move)\n window.addEventListener('pointerup', up)\n}\n\n// --- Toolbar (like Notion's image menu) ---------------------------------------------\ntype Align = 'left' | 'center' | 'right'\nconst align = computed(() => (props.node.attrs.align ?? 'center') as Align)\nconst ALIGN_ICONS = { left: AlignLeft, center: AlignCenter, right: AlignRight }\nconst crop = computed(() => props.node.attrs.crop as ImageCrop | null)\nconst captionShown = computed(() => props.node.attrs.showCaption ?? !!props.node.attrs.caption)\n/** The image URL if it is safe to load and open (KS-BUG-7: never `javascript:` / `data:text/html`). */\nconst src = computed(() => safeUrl(props.node.attrs.src, 'image'))\n/** A web URL (link actions apply); `isRemote` when it is on another origin (download fetches it). */\nconst isWeb = computed(() => !!src.value && isWebUrl(src.value))\nconst isRemote = computed(() => isWeb.value && !isSameOrigin(src.value!))\n\nconst menu = ref<'align' | 'more' | null>(null)\nconst toolbar = ref<HTMLElement | null>(null)\nuseClickOutside(toolbar, computed(() => menu.value !== null), () => (menu.value = null))\nconst captionInput = ref<HTMLInputElement | null>(null)\nconst cropping = ref(false)\nconst viewing = ref(false)\nconst copied = ref(false)\n\nfunction setAlign(value: Align) {\n props.updateAttributes({ align: value })\n menu.value = null\n}\nfunction toggleCaption() {\n const show = !captionShown.value\n props.updateAttributes({ showCaption: show })\n if (show) nextTick(() => captionInput.value?.focus())\n}\nfunction finishCrop(value: ImageCrop | null) {\n props.updateAttributes({ crop: value })\n cropping.value = false\n}\n\n/** Saves the original file; cross-origin links that refuse fetch open in a new tab. */\nasync function download() {\n const url = src.value\n if (!url) return\n const name = (props.node.attrs.alt as string) || 'image'\n const save = (href: string) => {\n const a = document.createElement('a')\n a.href = href\n a.download = name\n a.click()\n }\n if (!isRemote.value) return save(url)\n try {\n const blob = await (await fetch(url)).blob()\n const objectUrl = URL.createObjectURL(blob)\n save(objectUrl)\n setTimeout(() => URL.revokeObjectURL(objectUrl), 1000)\n }\n catch {\n window.open(url, '_blank', 'noopener')\n }\n}\n\nasync function copyLink() {\n if (!src.value) return\n await navigator.clipboard?.writeText(new URL(src.value, location.href).href)\n copied.value = true\n setTimeout(() => (copied.value = false), 1500)\n menu.value = null\n}\nfunction replace() {\n menu.value = null\n fileInput.value?.click()\n}\nfunction openOriginal() {\n menu.value = null\n if (src.value) window.open(src.value, '_blank', 'noopener')\n}\nfunction remove() {\n menu.value = null\n props.deleteNode()\n}\n\n// Cropped view: the frame takes the crop's aspect ratio and the image is offset inside it.\nconst cropStyle = computed(() => {\n const c = crop.value\n if (!c) return undefined\n return {\n width: `${100 / c.w}%`,\n left: `${(-c.x / c.w) * 100}%`,\n top: `${(-c.y / c.h) * 100}%`,\n }\n})\n</script>\n\n<template>\n <NodeViewWrapper class=\"me-media\" :class=\"{ 'is-readonly-empty': !editable && !node.attrs.src && !isPending }\">\n <div v-if=\"isPending\" class=\"me-media-pending\" :class=\"{ 'is-failed': !!uploadError || uploadState === 'interrupted' }\" contenteditable=\"false\">\n <img v-if=\"pending?.preview\" :src=\"pending.preview\" :alt=\"node.attrs.alt || ''\" class=\"me-media-preview\" draggable=\"false\">\n <div class=\"me-media-status\" role=\"status\">\n <template v-if=\"uploadState === 'interrupted'\">\n <!-- Its tab went away mid-upload: any editor can remove it. -->\n <span class=\"me-error me-media-status-error\">{{ m.uploadInterrupted }}</span>\n <button v-if=\"editable\" type=\"button\" class=\"me-btn\" @click=\"deleteNode()\">\n <Trash /> {{ m.delete }}\n </button>\n </template>\n <template v-else-if=\"!uploadError\">\n <span>{{ m.uploading }}</span>\n <!-- Progress and Delete only in the tab that owns the file; others just see it uploading. -->\n <span v-if=\"pending\" class=\"me-media-progress\"><span class=\"me-media-progress-bar\" :style=\"{ width: progress }\" /></span>\n <button v-if=\"editable && pending\" type=\"button\" class=\"me-btn\" @click=\"deleteNode()\">\n <Trash /> {{ m.delete }}\n </button>\n </template>\n <template v-else>\n <span class=\"me-error me-media-status-error\">{{ uploadErrorText }}</span>\n <button v-if=\"editable && pending && uploadError === 'failed'\" type=\"button\" class=\"me-btn\" @click=\"runUpload(editor, node.attrs.uploadId)\">\n <RefreshCw /> {{ m.retry }}\n </button>\n <button v-if=\"editable\" type=\"button\" class=\"me-btn\" @click=\"deleteNode()\">\n <Trash /> {{ m.delete }}\n </button>\n </template>\n </div>\n </div>\n <div v-else-if=\"!node.attrs.src\" class=\"me-media-empty\" contenteditable=\"false\" @dragover.prevent @drop=\"onDrop\">\n <div class=\"me-tabs\">\n <button\n v-for=\"t in (['upload', 'link'] as const)\"\n :key=\"t\"\n type=\"button\"\n class=\"me-tab\"\n :class=\"{ 'is-active': tab === t }\"\n @click=\"tab = t\"\n >\n <component :is=\"t === 'upload' ? Upload : LinkIcon\" />\n {{ t === 'upload' ? m.upload : m.link }}\n </button>\n </div>\n <div v-if=\"tab === 'upload'\" class=\"me-media-body\">\n <button type=\"button\" class=\"me-btn\" :disabled=\"uploading\" @click=\"fileInput?.click()\">\n <ImageIcon /> {{ uploading ? m.uploading : m.choose }}\n </button>\n <p class=\"me-hint\">\n {{ m.dropHint(config.maxImageSize) }}\n </p>\n <input ref=\"fileInput\" type=\"file\" accept=\"image/*\" hidden @change=\"onFileChange\">\n </div>\n <form v-else class=\"me-inline-form\" @submit.prevent=\"submitLink\">\n <input v-model=\"link\" class=\"me-input\" placeholder=\"https://...\" @keydown.stop>\n <button type=\"submit\" class=\"me-btn me-btn--primary\">\n {{ m.insert }}\n </button>\n </form>\n <p v-if=\"error\" class=\"me-error\">\n {{ error }}\n </p>\n </div>\n\n <figure\n v-else\n ref=\"figure\"\n class=\"me-figure\"\n :class=\"`me-figure--${align}`\"\n :style=\"{ width: `${node.attrs.width}%` }\"\n >\n <ImageCropper\n v-if=\"cropping && src\"\n :src=\"src\"\n :alt=\"node.attrs.alt\"\n :crop=\"crop\"\n :messages=\"m\"\n @done=\"finishCrop\"\n @cancel=\"cropping = false\"\n />\n <div\n v-else\n class=\"me-figure-frame\"\n :class=\"{ 'is-selected': selected, 'is-menu-open': menu !== null }\"\n >\n <!-- Only this layer clips (for crops), so the toolbar's menus can overflow the frame. -->\n <div class=\"me-figure-media\" :class=\"{ 'is-cropped': !!crop }\" :style=\"crop ? { aspectRatio: String(crop.ratio) } : undefined\">\n <img v-if=\"src\" :src=\"src\" :alt=\"node.attrs.alt || ''\" class=\"me-figure-img\" :style=\"cropStyle\" draggable=\"false\" @dblclick=\"viewing = true\">\n <p v-else class=\"me-error me-image-blocked\">\n {{ m.invalidLink }}\n </p>\n </div>\n\n <div ref=\"toolbar\" class=\"me-popover me-toolbar me-image-toolbar\" contenteditable=\"false\" @mousedown.stop>\n <template v-if=\"editable\">\n <div class=\"me-image-menu-anchor\">\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.align\" @click=\"menu = menu === 'align' ? null : 'align'\">\n <component :is=\"ALIGN_ICONS[align]\" />\n </button>\n <div v-if=\"menu === 'align'\" class=\"me-popover me-menu me-image-menu\">\n <button v-for=\"a in (['left', 'center', 'right'] as const)\" :key=\"a\" type=\"button\" class=\"me-menu-item\" @click=\"setAlign(a)\">\n <span class=\"me-menu-icon\"><component :is=\"ALIGN_ICONS[a]\" /></span>\n <span class=\"me-menu-title me-menu-text\">{{ m.alignments[a] }}</span>\n <Check v-if=\"align === a\" class=\"me-menu-check\" />\n </button>\n </div>\n </div>\n <button type=\"button\" class=\"me-tool-btn\" :class=\"{ 'is-active': captionShown }\" :title=\"m.captionToggle\" @click=\"toggleCaption\">\n <Captions />\n </button>\n <button type=\"button\" class=\"me-tool-btn\" :class=\"{ 'is-active': !!crop }\" :title=\"m.crop\" @click=\"cropping = true\">\n <Crop />\n </button>\n </template>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.zoom\" @click=\"viewing = true\">\n <ZoomIn />\n </button>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.download\" @click=\"download\">\n <Download />\n </button>\n <div class=\"me-image-menu-anchor\">\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.more\" @click=\"menu = menu === 'more' ? null : 'more'\">\n <Ellipsis />\n </button>\n <div v-if=\"menu === 'more'\" class=\"me-popover me-menu me-image-menu\">\n <button v-if=\"editable\" type=\"button\" class=\"me-menu-item\" @click=\"replace\">\n <span class=\"me-menu-icon\"><RefreshCw /></span>\n <span class=\"me-menu-title me-menu-text\">{{ m.replace }}</span>\n </button>\n <button v-if=\"isWeb\" type=\"button\" class=\"me-menu-item\" @click=\"copyLink\">\n <span class=\"me-menu-icon\"><component :is=\"copied ? Check : Copy\" /></span>\n <span class=\"me-menu-title me-menu-text\">{{ copied ? m.linkCopied : m.copyLink }}</span>\n </button>\n <button v-if=\"isWeb\" type=\"button\" class=\"me-menu-item\" @click=\"openOriginal\">\n <span class=\"me-menu-icon\"><ExternalLink /></span>\n <span class=\"me-menu-title me-menu-text\">{{ m.original }}</span>\n </button>\n <button v-if=\"editable\" type=\"button\" class=\"me-menu-item is-danger\" @click=\"remove\">\n <span class=\"me-menu-icon\"><Trash /></span>\n <span class=\"me-menu-title me-menu-text\">{{ m.delete }}</span>\n </button>\n </div>\n </div>\n </div>\n\n <template v-if=\"editable\">\n <span class=\"me-resize-handle me-resize-handle--left\" @pointerdown=\"startResize($event, -1)\" />\n <span class=\"me-resize-handle me-resize-handle--right\" @pointerdown=\"startResize($event, 1)\" />\n </template>\n </div>\n <input\n v-if=\"captionShown && !cropping\"\n ref=\"captionInput\"\n class=\"me-caption\"\n :value=\"node.attrs.caption\"\n :readonly=\"!editable\"\n :placeholder=\"editable ? m.caption : ''\"\n @input=\"updateAttributes({ caption: ($event.target as HTMLInputElement).value })\"\n @keydown.stop\n >\n <input ref=\"fileInput\" type=\"file\" accept=\"image/*\" hidden @change=\"onFileChange\">\n <p v-if=\"error\" class=\"me-error\">\n {{ error }}\n </p>\n </figure>\n\n <ImageLightbox\n v-if=\"viewing && src\"\n :src=\"src\"\n :alt=\"node.attrs.alt\"\n :messages=\"m\"\n :scope=\"scope\"\n @close=\"viewing = false\"\n @download=\"download\"\n />\n </NodeViewWrapper>\n</template>\n","/**\n * Transient attributes of an image / file block created by paste or drop (see `FileDrop`). Never rendered to HTML\n * nor parsed from it, so copies and exports never carry an upload in progress.\n */\nexport function uploadAttributes() {\n return {\n /** Key of the pending upload in `editor.storage.fileDrop.uploads` (this tab only). */\n uploadId: { default: null, rendered: false, parseHTML: () => null },\n uploading: { default: false, rendered: false, parseHTML: () => false },\n /** When the upload started (ms epoch). An `uploading` node older than 2 minutes counts as interrupted. */\n uploadStartedAt: { default: null, rendered: false, parseHTML: () => null },\n /** `'tooLarge' | 'badType' | 'failed'` when the upload could not finish. */\n error: { default: null, rendered: false, parseHTML: () => null },\n }\n}\n","import Image from '@tiptap/extension-image'\nimport { blockNodeView } from '../nodeviews/renderer'\nimport ImageView from '../nodeviews/ImageView.vue'\nimport { safeUrl } from '../safe-url'\nimport { uploadAttributes } from './upload-attrs'\n\nexport const ImageBlock = Image.extend({\n draggable: true,\n\n addAttributes() {\n const parent: Record<string, object> = this.parent?.() ?? {}\n return {\n ...parent,\n // Pasted / exported HTML never carries a `javascript:` or `data:text/html` source (KS-BUG-7).\n src: {\n ...parent.src,\n parseHTML: (el: HTMLElement) => safeUrl(el.getAttribute('src'), 'image'),\n renderHTML: (attrs: Record<string, unknown>) => ({ src: safeUrl(attrs.src, 'image') }),\n },\n width: {\n default: 100,\n parseHTML: el => Number(el.getAttribute('data-width')) || 100,\n renderHTML: attrs => ({ 'data-width': attrs.width }),\n },\n caption: {\n default: '',\n parseHTML: el => el.getAttribute('data-caption') || '',\n renderHTML: attrs => (attrs.caption ? { 'data-caption': attrs.caption } : {}),\n },\n /** Caption row shown (Notion hides it until \"Caption\" is clicked). Older docs: shown when there's text. */\n showCaption: {\n default: null,\n parseHTML: el => (el.hasAttribute('data-show-caption') ? el.getAttribute('data-show-caption') === 'true' : null),\n renderHTML: attrs => (attrs.showCaption === null ? {} : { 'data-show-caption': String(attrs.showCaption) }),\n },\n align: {\n default: 'center',\n parseHTML: el => el.getAttribute('data-align') || 'center',\n renderHTML: attrs => (attrs.align && attrs.align !== 'center' ? { 'data-align': attrs.align } : {}),\n },\n /** Non-destructive crop, see ImageCrop. */\n crop: {\n default: null,\n parseHTML: (el) => {\n try {\n return JSON.parse(el.getAttribute('data-crop') ?? 'null')\n }\n catch {\n return null\n }\n },\n renderHTML: attrs => (attrs.crop ? { 'data-crop': JSON.stringify(attrs.crop) } : {}),\n },\n ...uploadAttributes(),\n }\n },\n\n addNodeView() {\n return blockNodeView(ImageView)\n },\n}).configure({ inline: false, allowBase64: true })\n","import { Image, Video } from '@lucide/vue'\nimport { isNode } from '../block-items'\nimport { defineBlock } from '../define-block'\nimport { Embed } from '../extensions/embed'\nimport { ImageBlock } from '../extensions/image-block'\n\n/** Images: upload (see the `uploadImage` prop) or paste a link. */\nexport const image = defineBlock({\n name: 'image',\n nodes: ['image'],\n extensions: () => [ImageBlock],\n items: () => [{\n id: 'image',\n icon: Image,\n group: 'media',\n keywords: ['image', 'photo', 'picture', 'img', 'anh', 'hinh anh', '图片', '图像'],\n insert: c => c.insertContent({ type: 'image', attrs: { src: null } }),\n matches: isNode('image'),\n }],\n})\n\nexport const embed = defineBlock({\n name: 'embed',\n nodes: ['embed'],\n extensions: () => [Embed],\n items: () => [{\n id: 'embed',\n icon: Video,\n group: 'media',\n keywords: ['video', 'youtube', 'embed', 'iframe', 'vimeo', 'nhung', '视频', '嵌入'],\n insert: c => c.setEmbed({ src: null }),\n matches: isNode('embed'),\n }],\n})\n","<script setup lang=\"ts\">\nimport type { Editor } from '@tiptap/core'\nimport { nextTick, ref, watch } from 'vue'\nimport { useScope } from '../composables/useScope'\nimport type { EmojiEntry } from '../emoji-data'\nimport { usePointerMoved } from '../composables/usePointerMoved'\n\nconst props = defineProps<{ editor: Editor, items: EmojiEntry[], command: (item: EmojiEntry) => void }>()\nconst scope = useScope(() => props.editor)\nconst selected = ref(0)\nconst root = ref<HTMLElement | null>(null)\nconst COLS = 8\n\nwatch(() => props.items, () => (selected.value = 0))\nwatch(selected, async (i) => {\n await nextTick()\n root.value?.querySelector(`[data-index=\"${i}\"]`)?.scrollIntoView({ block: 'nearest' })\n})\n\nfunction onKeyDown(e: KeyboardEvent) {\n const n = props.items.length\n if (!n) return false\n const step = { ArrowRight: 1, ArrowLeft: -1, ArrowDown: COLS, ArrowUp: -COLS }[e.key]\n if (step) {\n selected.value = Math.min(n - 1, Math.max(0, selected.value + step))\n return true\n }\n if (e.key === 'Enter' || e.key === 'Tab') {\n const item = props.items[selected.value]\n if (item) props.command(item)\n return true\n }\n return false\n}\ndefineExpose({ onKeyDown })\n\n// Hover selects a row only after a real pointer move (KS-BUG-3).\nconst pointerMoved = usePointerMoved()\n</script>\n\n<template>\n <!-- Always render a root element (the popup positions it); hide it while empty. -->\n <div ref=\"root\" v-bind=\"scope\" class=\"me-popover me-emoji-menu\" :hidden=\"!items.length\">\n <div class=\"me-emoji-menu-grid\">\n <button\n v-for=\"(e, i) in items\"\n :key=\"e.unicode\"\n type=\"button\"\n class=\"me-emoji\"\n :class=\"{ 'is-active': i === selected }\"\n :data-index=\"i\"\n :title=\"e.label\"\n @mousemove=\"pointerMoved($event) && (selected = i)\"\n @mousedown.prevent=\"command(e)\"\n >\n {{ e.unicode }}\n </button>\n </div>\n <div class=\"me-menu-desc me-emoji-menu-label\">\n {{ items[selected]?.label }}\n </div>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport type { Editor } from '@tiptap/core'\nimport { nextTick, ref, watch } from 'vue'\nimport { useScope } from '../composables/useScope'\nimport type { EmojiEntry } from '../emoji-data'\nimport { usePointerMoved } from '../composables/usePointerMoved'\n\nconst props = defineProps<{ editor: Editor, items: EmojiEntry[], command: (item: EmojiEntry) => void }>()\nconst scope = useScope(() => props.editor)\nconst selected = ref(0)\nconst root = ref<HTMLElement | null>(null)\nconst COLS = 8\n\nwatch(() => props.items, () => (selected.value = 0))\nwatch(selected, async (i) => {\n await nextTick()\n root.value?.querySelector(`[data-index=\"${i}\"]`)?.scrollIntoView({ block: 'nearest' })\n})\n\nfunction onKeyDown(e: KeyboardEvent) {\n const n = props.items.length\n if (!n) return false\n const step = { ArrowRight: 1, ArrowLeft: -1, ArrowDown: COLS, ArrowUp: -COLS }[e.key]\n if (step) {\n selected.value = Math.min(n - 1, Math.max(0, selected.value + step))\n return true\n }\n if (e.key === 'Enter' || e.key === 'Tab') {\n const item = props.items[selected.value]\n if (item) props.command(item)\n return true\n }\n return false\n}\ndefineExpose({ onKeyDown })\n\n// Hover selects a row only after a real pointer move (KS-BUG-3).\nconst pointerMoved = usePointerMoved()\n</script>\n\n<template>\n <!-- Always render a root element (the popup positions it); hide it while empty. -->\n <div ref=\"root\" v-bind=\"scope\" class=\"me-popover me-emoji-menu\" :hidden=\"!items.length\">\n <div class=\"me-emoji-menu-grid\">\n <button\n v-for=\"(e, i) in items\"\n :key=\"e.unicode\"\n type=\"button\"\n class=\"me-emoji\"\n :class=\"{ 'is-active': i === selected }\"\n :data-index=\"i\"\n :title=\"e.label\"\n @mousemove=\"pointerMoved($event) && (selected = i)\"\n @mousedown.prevent=\"command(e)\"\n >\n {{ e.unicode }}\n </button>\n </div>\n <div class=\"me-menu-desc me-emoji-menu-label\">\n {{ items[selected]?.label }}\n </div>\n </div>\n</template>\n","/** Emoji search data, loaded on first use (≈600KB per locale, split into its own chunk). */\nexport interface EmojiEntry { unicode: string, label: string, terms: string[] }\n\nconst normalize = (s: string) => s.normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/đ/g, 'd').toLowerCase()\n\ninterface Compact { hexcode: string, label: string, unicode: string, tags?: string[], group?: number }\nconst LOCALES: Record<string, () => Promise<{ default: Compact[] }>> = {\n vi: () => import('emojibase-data/vi/compact.json'),\n zh: () => import('emojibase-data/zh/compact.json'),\n}\n\nlet cache: Promise<EmojiEntry[]> | null = null\nlet cachedLocale = ''\n\n/** English labels + GitHub shortcodes always; plus labels/tags in `locale` when available. */\nexport function loadEmojis(locale: string): Promise<EmojiEntry[]> {\n if (cache && cachedLocale === locale) return cache\n cachedLocale = locale\n cache = Promise.all([\n import('emojibase-data/en/compact.json'),\n import('emojibase-data/en/shortcodes/github.json'),\n LOCALES[locale]?.() ?? Promise.resolve({ default: [] as Compact[] }),\n ]).then(([en, shortcodes, local]) => {\n const localByHex = new Map(local.default.map(e => [e.hexcode, e]))\n const codes = shortcodes.default as Record<string, string | string[]>\n return (en.default as Compact[])\n // Skip regional indicators / components (no group).\n .filter(e => e.group !== undefined && e.group !== 2)\n .map((e) => {\n const loc = localByHex.get(e.hexcode)\n const sc = codes[e.hexcode]\n return {\n unicode: e.unicode,\n label: loc?.label ?? e.label,\n terms: [e.label, ...(e.tags ?? []), ...(loc ? [loc.label, ...(loc.tags ?? [])] : []), ...(Array.isArray(sc) ? sc : sc ? [sc] : [])].map(normalize),\n }\n })\n })\n return cache\n}\n\nexport function searchEmojis(list: EmojiEntry[], query: string, limit = 40): EmojiEntry[] {\n const q = normalize(query.trim())\n if (!q) return list.slice(0, limit)\n const starts: EmojiEntry[] = []\n const contains: EmojiEntry[] = []\n for (const e of list) {\n if (e.terms.some(t => t.startsWith(q))) starts.push(e)\n else if (e.terms.some(t => t.includes(q))) contains.push(e)\n if (starts.length >= limit) break\n }\n return [...starts, ...contains].slice(0, limit)\n}\n","import { Extension } from '@tiptap/core'\nimport { PluginKey } from '@tiptap/pm/state'\nimport Suggestion from '@tiptap/suggestion'\nimport EmojiMenu from '../components/EmojiMenu.vue'\nimport { type EmojiEntry, loadEmojis, searchEmojis } from '../emoji-data'\nimport { suggestionRenderer } from './suggestion-renderer'\n\nexport const emojiPluginKey = new PluginKey('emoji')\n\n/** Type `:` + a word (e.g. `:smile`, `:cười`) to insert an emoji as text. */\nexport const EmojiSuggestion = Extension.create({\n name: 'emojiSuggestion',\n\n addProseMirrorPlugins() {\n return [\n Suggestion<EmojiEntry>({\n editor: this.editor,\n pluginKey: emojiPluginKey,\n char: ':',\n allow: ({ state, range }) => !state.doc.resolve(range.from).parent.type.spec.code,\n items: async ({ query, editor }) => {\n // Wait for 2 letters so \"10:30\" or \"Note:\" doesn't pop the menu.\n if (query.length < 2) return []\n return searchEmojis(await loadEmojis(editor.storage.meiConfig.locale), query, 48)\n },\n command: ({ editor, range, props }) => {\n editor.chain().focus().insertContentAt(range, `${props.unicode} `).run()\n },\n // The menu hides itself while there are no matches; a space ends the suggestion.\n render: suggestionRenderer<EmojiEntry>(EmojiMenu, emojiPluginKey),\n }),\n ]\n },\n})\n","<script setup lang=\"ts\">\nimport { NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport { AudioLines, Download, File as FileIcon, Film, Link as LinkIcon, RefreshCw, Trash, Upload } from '@lucide/vue'\nimport { computed, ref } from 'vue'\nimport { useEditable } from '../composables/useEditable'\nimport { safeUrl } from '../safe-url'\nimport type { FileBlockOptions, FileKind } from '../extensions/file-block'\nimport { runUpload, type UploadError } from '../extensions/file-drop'\nimport { useUploadState } from '../composables/useUploadState'\n\nconst props = defineProps(nodeViewProps)\nconst editable = useEditable(props.editor)\n\nconst options = computed(() => props.extension.options as FileBlockOptions)\nconst kind = computed(() => (props.node.attrs.kind ?? 'file') as FileKind)\nconst m = computed(() => props.editor.storage.meiConfig.messages.file)\nconst tab = ref<'upload' | 'link'>('upload')\nconst link = ref('')\nconst error = ref('')\nconst uploading = ref(false)\nconst fileInput = ref<HTMLInputElement | null>(null)\n\n// Web, blob, data and same-origin paths (uploads like `/api/v1/files/<id>`, KS-BUG-15);\n// never `javascript:`: pasted content could carry such links.\nconst safeSrc = computed(() => safeUrl(props.node.attrs.src, 'any'))\nconst accept = computed(() => ({ file: '', audio: 'audio/*', video: 'video/*' })[kind.value])\nconst icon = computed(() => ({ file: FileIcon, audio: AudioLines, video: Film })[kind.value])\nconst title = computed(() => ({ file: m.value.chooseFile, audio: m.value.chooseAudio, video: m.value.chooseVideo })[kind.value])\n\nconst readAsDataUrl = (file: File) => new Promise<string>((resolve, reject) => {\n const reader = new FileReader()\n reader.onload = () => resolve(reader.result as string)\n reader.onerror = () => reject(reader.error)\n reader.readAsDataURL(file)\n})\n\nasync function handleFile(file: File) {\n error.value = ''\n if (kind.value !== 'file' && !file.type.startsWith(`${kind.value}/`)) return (error.value = m.value.wrongType)\n if (file.size > options.value.maxSize * 1024 * 1024) return (error.value = m.value.tooLarge(options.value.maxSize))\n uploading.value = true\n try {\n const src = options.value.upload ? await options.value.upload(file, kind.value) : await readAsDataUrl(file)\n props.updateAttributes({ src, name: file.name, size: file.size, mime: file.type })\n }\n catch {\n error.value = m.value.uploadFailed\n }\n finally {\n uploading.value = false\n }\n}\n\nfunction onDrop(e: DragEvent) {\n const file = e.dataTransfer?.files?.[0]\n if (!file) return\n e.preventDefault()\n e.stopPropagation()\n handleFile(file)\n}\n\nfunction submitLink() {\n try {\n const url = new URL(link.value.trim())\n if (!/^https?:$/.test(url.protocol)) throw new Error('protocol')\n props.updateAttributes({ src: url.toString(), name: decodeURIComponent(url.pathname.split('/').pop() || url.hostname) })\n }\n catch {\n error.value = m.value.invalidLink\n }\n}\n\n// --- Pasted / dropped file (FileDrop): progress, error + retry ---------------------------\n// `local`: this tab owns the file; `remote`: another tab uploads it; `interrupted`: stale (> 2 min, nobody here).\nconst { pending, state: uploadState } = useUploadState(props.editor, () => props.node)\nconst uploadError = computed(() => props.node.attrs.error as UploadError | null)\nconst isPending = computed(() => !props.node.attrs.src && (!!props.node.attrs.uploading || !!uploadError.value))\nconst progress = computed(() => `${Math.round((pending.value?.progress ?? 0) * 100)}%`)\nconst uploadErrorText = computed(() => {\n const e = uploadError.value\n return e === 'tooLarge' ? m.value.tooLarge(options.value.maxSize) : e === 'badType' ? m.value.wrongType : m.value.uploadFailed\n})\n\nconst sizeLabel = computed(() => {\n const bytes = Number(props.node.attrs.size)\n if (!bytes) return ''\n const units = ['B', 'KB', 'MB', 'GB']\n const i = Math.min(units.length - 1, Math.floor(Math.log(bytes) / Math.log(1024)))\n return `${(bytes / 1024 ** i).toFixed(i ? 1 : 0)} ${units[i]}`\n})\n</script>\n\n<template>\n <NodeViewWrapper class=\"me-media\" :class=\"{ 'is-readonly-empty': !editable && !node.attrs.src && !isPending }\">\n <div v-if=\"isPending\" class=\"me-file me-file--pending\" :class=\"{ 'is-failed': !!uploadError || uploadState === 'interrupted', 'is-selected': selected }\" contenteditable=\"false\">\n <div class=\"me-file-row\">\n <component :is=\"icon\" class=\"me-file-icon\" />\n <span class=\"me-file-name\">{{ node.attrs.name }}</span>\n <span v-if=\"sizeLabel\" class=\"me-file-size\">{{ sizeLabel }}</span>\n </div>\n <div class=\"me-media-status\" role=\"status\">\n <template v-if=\"uploadState === 'interrupted'\">\n <!-- Its tab went away mid-upload: any editor can remove it. -->\n <span class=\"me-error me-media-status-error\">{{ m.uploadInterrupted }}</span>\n <button v-if=\"editable\" type=\"button\" class=\"me-btn\" @click=\"deleteNode()\">\n <Trash /> {{ m.delete }}\n </button>\n </template>\n <template v-else-if=\"!uploadError\">\n <span>{{ m.uploading }}</span>\n <!-- Progress and Delete only in the tab that owns the file; others just see it uploading. -->\n <span v-if=\"pending\" class=\"me-media-progress\"><span class=\"me-media-progress-bar\" :style=\"{ width: progress }\" /></span>\n <button v-if=\"editable && pending\" type=\"button\" class=\"me-btn\" @click=\"deleteNode()\">\n <Trash /> {{ m.delete }}\n </button>\n </template>\n <template v-else>\n <span class=\"me-error me-media-status-error\">{{ uploadErrorText }}</span>\n <button v-if=\"editable && pending && uploadError === 'failed'\" type=\"button\" class=\"me-btn\" @click=\"runUpload(editor, node.attrs.uploadId)\">\n <RefreshCw /> {{ m.retry }}\n </button>\n <button v-if=\"editable\" type=\"button\" class=\"me-btn\" @click=\"deleteNode()\">\n <Trash /> {{ m.delete }}\n </button>\n </template>\n </div>\n </div>\n <div v-else-if=\"!node.attrs.src\" class=\"me-media-empty\" contenteditable=\"false\" @dragover.prevent @drop=\"onDrop\">\n <div class=\"me-tabs\">\n <button v-for=\"t in (['upload', 'link'] as const)\" :key=\"t\" type=\"button\" class=\"me-tab\" :class=\"{ 'is-active': tab === t }\" @click=\"tab = t\">\n <component :is=\"t === 'upload' ? Upload : LinkIcon\" />\n {{ t === 'upload' ? m.upload : m.link }}\n </button>\n </div>\n <div v-if=\"tab === 'upload'\" class=\"me-media-body\">\n <button type=\"button\" class=\"me-btn\" :disabled=\"uploading\" @click=\"fileInput?.click()\">\n <component :is=\"icon\" /> {{ uploading ? m.uploading : title }}\n </button>\n <p class=\"me-hint\">\n {{ m.dropHint(options.maxSize) }}\n </p>\n <input ref=\"fileInput\" type=\"file\" :accept=\"accept\" hidden @change=\"($event.target as HTMLInputElement).files?.[0] && handleFile(($event.target as HTMLInputElement).files![0]!)\">\n </div>\n <form v-else class=\"me-inline-form\" @submit.prevent=\"submitLink\">\n <input v-model=\"link\" class=\"me-input\" placeholder=\"https://...\" @keydown.stop>\n <button type=\"submit\" class=\"me-btn me-btn--primary\">\n {{ m.embed }}\n </button>\n </form>\n <p v-if=\"error\" class=\"me-error\">\n {{ error }}\n </p>\n </div>\n\n <div v-else class=\"me-file\" :class=\"[`me-file--${kind}`, { 'is-selected': selected }]\" contenteditable=\"false\">\n <audio v-if=\"kind === 'audio' && safeSrc\" class=\"me-file-player\" :src=\"safeSrc\" controls preload=\"metadata\" />\n <video v-else-if=\"kind === 'video' && safeSrc\" class=\"me-file-player\" :src=\"safeSrc\" controls preload=\"metadata\" />\n <div class=\"me-file-row\">\n <component :is=\"icon\" class=\"me-file-icon\" />\n <span class=\"me-file-name\">{{ node.attrs.name || node.attrs.src }}</span>\n <span v-if=\"sizeLabel\" class=\"me-file-size\">{{ sizeLabel }}</span>\n <a v-if=\"safeSrc\" class=\"me-tool-btn\" :href=\"safeSrc\" :download=\"node.attrs.name || true\" target=\"_blank\" rel=\"noopener noreferrer\" :title=\"m.download\">\n <Download />\n </a>\n </div>\n </div>\n </NodeViewWrapper>\n</template>\n","<script setup lang=\"ts\">\nimport { NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport { AudioLines, Download, File as FileIcon, Film, Link as LinkIcon, RefreshCw, Trash, Upload } from '@lucide/vue'\nimport { computed, ref } from 'vue'\nimport { useEditable } from '../composables/useEditable'\nimport { safeUrl } from '../safe-url'\nimport type { FileBlockOptions, FileKind } from '../extensions/file-block'\nimport { runUpload, type UploadError } from '../extensions/file-drop'\nimport { useUploadState } from '../composables/useUploadState'\n\nconst props = defineProps(nodeViewProps)\nconst editable = useEditable(props.editor)\n\nconst options = computed(() => props.extension.options as FileBlockOptions)\nconst kind = computed(() => (props.node.attrs.kind ?? 'file') as FileKind)\nconst m = computed(() => props.editor.storage.meiConfig.messages.file)\nconst tab = ref<'upload' | 'link'>('upload')\nconst link = ref('')\nconst error = ref('')\nconst uploading = ref(false)\nconst fileInput = ref<HTMLInputElement | null>(null)\n\n// Web, blob, data and same-origin paths (uploads like `/api/v1/files/<id>`, KS-BUG-15);\n// never `javascript:`: pasted content could carry such links.\nconst safeSrc = computed(() => safeUrl(props.node.attrs.src, 'any'))\nconst accept = computed(() => ({ file: '', audio: 'audio/*', video: 'video/*' })[kind.value])\nconst icon = computed(() => ({ file: FileIcon, audio: AudioLines, video: Film })[kind.value])\nconst title = computed(() => ({ file: m.value.chooseFile, audio: m.value.chooseAudio, video: m.value.chooseVideo })[kind.value])\n\nconst readAsDataUrl = (file: File) => new Promise<string>((resolve, reject) => {\n const reader = new FileReader()\n reader.onload = () => resolve(reader.result as string)\n reader.onerror = () => reject(reader.error)\n reader.readAsDataURL(file)\n})\n\nasync function handleFile(file: File) {\n error.value = ''\n if (kind.value !== 'file' && !file.type.startsWith(`${kind.value}/`)) return (error.value = m.value.wrongType)\n if (file.size > options.value.maxSize * 1024 * 1024) return (error.value = m.value.tooLarge(options.value.maxSize))\n uploading.value = true\n try {\n const src = options.value.upload ? await options.value.upload(file, kind.value) : await readAsDataUrl(file)\n props.updateAttributes({ src, name: file.name, size: file.size, mime: file.type })\n }\n catch {\n error.value = m.value.uploadFailed\n }\n finally {\n uploading.value = false\n }\n}\n\nfunction onDrop(e: DragEvent) {\n const file = e.dataTransfer?.files?.[0]\n if (!file) return\n e.preventDefault()\n e.stopPropagation()\n handleFile(file)\n}\n\nfunction submitLink() {\n try {\n const url = new URL(link.value.trim())\n if (!/^https?:$/.test(url.protocol)) throw new Error('protocol')\n props.updateAttributes({ src: url.toString(), name: decodeURIComponent(url.pathname.split('/').pop() || url.hostname) })\n }\n catch {\n error.value = m.value.invalidLink\n }\n}\n\n// --- Pasted / dropped file (FileDrop): progress, error + retry ---------------------------\n// `local`: this tab owns the file; `remote`: another tab uploads it; `interrupted`: stale (> 2 min, nobody here).\nconst { pending, state: uploadState } = useUploadState(props.editor, () => props.node)\nconst uploadError = computed(() => props.node.attrs.error as UploadError | null)\nconst isPending = computed(() => !props.node.attrs.src && (!!props.node.attrs.uploading || !!uploadError.value))\nconst progress = computed(() => `${Math.round((pending.value?.progress ?? 0) * 100)}%`)\nconst uploadErrorText = computed(() => {\n const e = uploadError.value\n return e === 'tooLarge' ? m.value.tooLarge(options.value.maxSize) : e === 'badType' ? m.value.wrongType : m.value.uploadFailed\n})\n\nconst sizeLabel = computed(() => {\n const bytes = Number(props.node.attrs.size)\n if (!bytes) return ''\n const units = ['B', 'KB', 'MB', 'GB']\n const i = Math.min(units.length - 1, Math.floor(Math.log(bytes) / Math.log(1024)))\n return `${(bytes / 1024 ** i).toFixed(i ? 1 : 0)} ${units[i]}`\n})\n</script>\n\n<template>\n <NodeViewWrapper class=\"me-media\" :class=\"{ 'is-readonly-empty': !editable && !node.attrs.src && !isPending }\">\n <div v-if=\"isPending\" class=\"me-file me-file--pending\" :class=\"{ 'is-failed': !!uploadError || uploadState === 'interrupted', 'is-selected': selected }\" contenteditable=\"false\">\n <div class=\"me-file-row\">\n <component :is=\"icon\" class=\"me-file-icon\" />\n <span class=\"me-file-name\">{{ node.attrs.name }}</span>\n <span v-if=\"sizeLabel\" class=\"me-file-size\">{{ sizeLabel }}</span>\n </div>\n <div class=\"me-media-status\" role=\"status\">\n <template v-if=\"uploadState === 'interrupted'\">\n <!-- Its tab went away mid-upload: any editor can remove it. -->\n <span class=\"me-error me-media-status-error\">{{ m.uploadInterrupted }}</span>\n <button v-if=\"editable\" type=\"button\" class=\"me-btn\" @click=\"deleteNode()\">\n <Trash /> {{ m.delete }}\n </button>\n </template>\n <template v-else-if=\"!uploadError\">\n <span>{{ m.uploading }}</span>\n <!-- Progress and Delete only in the tab that owns the file; others just see it uploading. -->\n <span v-if=\"pending\" class=\"me-media-progress\"><span class=\"me-media-progress-bar\" :style=\"{ width: progress }\" /></span>\n <button v-if=\"editable && pending\" type=\"button\" class=\"me-btn\" @click=\"deleteNode()\">\n <Trash /> {{ m.delete }}\n </button>\n </template>\n <template v-else>\n <span class=\"me-error me-media-status-error\">{{ uploadErrorText }}</span>\n <button v-if=\"editable && pending && uploadError === 'failed'\" type=\"button\" class=\"me-btn\" @click=\"runUpload(editor, node.attrs.uploadId)\">\n <RefreshCw /> {{ m.retry }}\n </button>\n <button v-if=\"editable\" type=\"button\" class=\"me-btn\" @click=\"deleteNode()\">\n <Trash /> {{ m.delete }}\n </button>\n </template>\n </div>\n </div>\n <div v-else-if=\"!node.attrs.src\" class=\"me-media-empty\" contenteditable=\"false\" @dragover.prevent @drop=\"onDrop\">\n <div class=\"me-tabs\">\n <button v-for=\"t in (['upload', 'link'] as const)\" :key=\"t\" type=\"button\" class=\"me-tab\" :class=\"{ 'is-active': tab === t }\" @click=\"tab = t\">\n <component :is=\"t === 'upload' ? Upload : LinkIcon\" />\n {{ t === 'upload' ? m.upload : m.link }}\n </button>\n </div>\n <div v-if=\"tab === 'upload'\" class=\"me-media-body\">\n <button type=\"button\" class=\"me-btn\" :disabled=\"uploading\" @click=\"fileInput?.click()\">\n <component :is=\"icon\" /> {{ uploading ? m.uploading : title }}\n </button>\n <p class=\"me-hint\">\n {{ m.dropHint(options.maxSize) }}\n </p>\n <input ref=\"fileInput\" type=\"file\" :accept=\"accept\" hidden @change=\"($event.target as HTMLInputElement).files?.[0] && handleFile(($event.target as HTMLInputElement).files![0]!)\">\n </div>\n <form v-else class=\"me-inline-form\" @submit.prevent=\"submitLink\">\n <input v-model=\"link\" class=\"me-input\" placeholder=\"https://...\" @keydown.stop>\n <button type=\"submit\" class=\"me-btn me-btn--primary\">\n {{ m.embed }}\n </button>\n </form>\n <p v-if=\"error\" class=\"me-error\">\n {{ error }}\n </p>\n </div>\n\n <div v-else class=\"me-file\" :class=\"[`me-file--${kind}`, { 'is-selected': selected }]\" contenteditable=\"false\">\n <audio v-if=\"kind === 'audio' && safeSrc\" class=\"me-file-player\" :src=\"safeSrc\" controls preload=\"metadata\" />\n <video v-else-if=\"kind === 'video' && safeSrc\" class=\"me-file-player\" :src=\"safeSrc\" controls preload=\"metadata\" />\n <div class=\"me-file-row\">\n <component :is=\"icon\" class=\"me-file-icon\" />\n <span class=\"me-file-name\">{{ node.attrs.name || node.attrs.src }}</span>\n <span v-if=\"sizeLabel\" class=\"me-file-size\">{{ sizeLabel }}</span>\n <a v-if=\"safeSrc\" class=\"me-tool-btn\" :href=\"safeSrc\" :download=\"node.attrs.name || true\" target=\"_blank\" rel=\"noopener noreferrer\" :title=\"m.download\">\n <Download />\n </a>\n </div>\n </div>\n </NodeViewWrapper>\n</template>\n","import { mergeAttributes, Node } from '@tiptap/core'\nimport { blockNodeView } from '../nodeviews/renderer'\nimport FileView from '../nodeviews/FileView.vue'\nimport { uploadAttributes } from './upload-attrs'\n\nexport type FileKind = 'file' | 'audio' | 'video'\n\nexport interface FileBlockOptions {\n /**\n * Uploads a file and resolves to its URL. Without it files are inlined as base64.\n * `onProgress` (0..1) is optional to call: the block shows it while the upload runs.\n */\n upload: ((file: File, kind: FileKind, onProgress?: (fraction: number) => void) => Promise<string>) | null\n /** Max size in MB. */\n maxSize: number\n}\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n fileBlock: { insertFileBlock: (kind?: FileKind) => ReturnType }\n }\n}\n\n/** Attachment, audio player or video player, uploaded or linked. */\nexport const FileBlock = Node.create<FileBlockOptions>({\n name: 'fileBlock',\n group: 'block',\n atom: true,\n draggable: true,\n\n addOptions: () => ({ upload: null, maxSize: 10 }),\n\n addAttributes() {\n const attr = (name: string, fallback: unknown = null) => ({\n default: fallback,\n parseHTML: (el: HTMLElement) => el.getAttribute(`data-${name}`) ?? fallback,\n renderHTML: (attrs: Record<string, any>) => (attrs[name] == null ? {} : { [`data-${name}`]: attrs[name] }),\n })\n return {\n src: attr('src'), name: attr('name'), size: attr('size'), mime: attr('mime'), kind: attr('kind', 'file'),\n ...uploadAttributes(),\n }\n },\n\n parseHTML: () => [{ tag: 'div[data-type=\"file\"]' }],\n renderHTML: ({ HTMLAttributes }) => ['div', mergeAttributes(HTMLAttributes, { 'data-type': 'file' })],\n\n addCommands() {\n return { insertFileBlock: (kind = 'file') => ({ commands }) => commands.insertContent({ type: this.name, attrs: { kind } }) }\n },\n\n addNodeView: () => blockNodeView(FileView),\n})\n","<script setup lang=\"ts\">\n/**\n * Notion-style HTML block. The page runs in a sandboxed iframe of fixed height; it only\n * takes clicks/scrolls after \"Interact\" (so scrolling the document isn't hijacked).\n * Editors can switch to Code to edit in place, upload an .html file, or drag the height.\n */\nimport { NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport { Code, CodeXml, Eye, Maximize2, Pointer, Upload, X } from '@lucide/vue'\nimport { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue'\nimport { useClickOutside } from '../composables/useClickOutside'\nimport { useEditable } from '../composables/useEditable'\nimport { useScope } from '../composables/useScope'\nimport { loadLanguage, lowlight } from '../extensions/code-block'\nimport { HTML_MAX_HEIGHT, HTML_MIN_HEIGHT, type HtmlBlockOptions, htmlBlockDocument } from '../extensions/html-block'\n\nconst props = defineProps(nodeViewProps)\n\nconst scope = useScope(() => props.editor)\nconst editable = useEditable(props.editor)\nconst m = computed(() => props.editor.storage.meiConfig.messages.html)\nconst options = computed(() => props.extension.options as HtmlBlockOptions)\nconst code = computed(() => (props.node.attrs.code as string) ?? '')\nconst height = computed(() => (props.node.attrs.height as number | null) ?? options.value.defaultHeight)\nconst name = computed(() => (props.node.attrs.fileName as string | null) || m.value.title)\nconst srcdoc = computed(() => htmlBlockDocument(code.value, options.value.network))\n\n// --- Modes ----------------------------------------------------------------------\nconst mode = ref<'preview' | 'code'>('preview')\nconst interacting = ref(false)\nconst fullscreen = ref(false)\nconst root = ref<HTMLElement | null>(null)\nuseClickOutside(root, interacting, () => (interacting.value = false))\n\nfunction showCode() {\n error.value = ''\n mode.value = 'code'\n interacting.value = false\n nextTick(() => textarea.value?.focus())\n}\nfunction showPreview() {\n error.value = ''\n commit()\n mode.value = 'preview'\n}\n\n// Read-only: back to the preview.\nwatch(editable, (value) => {\n if (!value && mode.value === 'code') showPreview()\n})\n\n// --- Code editor ----------------------------------------------------------------\nconst draft = ref(code.value)\nwatch(code, (value) => {\n if (value !== draft.value) draft.value = value\n})\nconst textarea = ref<HTMLTextAreaElement | null>(null)\nconst highlightEl = ref<HTMLElement | null>(null)\n\nlet timer: ReturnType<typeof setTimeout> | undefined\nfunction commit() {\n clearTimeout(timer)\n if (draft.value !== code.value) props.updateAttributes({ code: draft.value })\n}\nfunction onInput() {\n clearTimeout(timer)\n timer = setTimeout(commit, 400)\n}\nfunction onKeydown(e: KeyboardEvent) {\n if (e.key === 'Tab') {\n // Indent instead of leaving the editor.\n e.preventDefault()\n const el = e.target as HTMLTextAreaElement\n el.setRangeText(' ', el.selectionStart, el.selectionEnd, 'end')\n draft.value = el.value\n onInput()\n }\n else if (e.key === 'Escape' || (e.key === 'Enter' && (e.metaKey || e.ctrlKey))) {\n e.preventDefault()\n showPreview()\n }\n}\nfunction syncScroll() {\n if (highlightEl.value && textarea.value) {\n highlightEl.value.scrollTop = textarea.value.scrollTop\n highlightEl.value.scrollLeft = textarea.value.scrollLeft\n }\n}\n\n// Syntax colors: HTML grammar plus the CSS/JS it embeds, loaded on first use.\nconst grammarReady = ref(false)\nwatch(mode, (value) => {\n if (value === 'code' && !grammarReady.value) {\n Promise.all(['xml', 'css', 'javascript'].map(loadLanguage)).then(() => (grammarReady.value = true))\n }\n}, { immediate: true })\n\ntype HastNode = { type: string, value?: string, tagName?: string, properties?: { className?: string[] }, children?: HastNode[] }\nconst escapeHtml = (s: string) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')\nfunction toHtml(node: HastNode): string {\n if (node.type === 'text') return escapeHtml(node.value ?? '')\n const inner = (node.children ?? []).map(toHtml).join('')\n if (node.type === 'element') return `<span class=\"${(node.properties?.className ?? []).join(' ')}\">${inner}</span>`\n return inner\n}\nconst highlighted = computed(() => {\n // Trailing newline keeps the last line's height in sync with the textarea.\n const text = `${draft.value}\\n`\n if (!grammarReady.value || !lowlight.registered('xml')) return escapeHtml(text)\n return toHtml(lowlight.highlight('xml', text) as HastNode)\n})\n\n// --- Upload ---------------------------------------------------------------------\nconst fileInput = ref<HTMLInputElement | null>(null)\nconst error = ref('')\nasync function onFile(e: Event) {\n const input = e.target as HTMLInputElement\n const file = input.files?.[0]\n input.value = ''\n if (!file) return\n if (!/\\.html?$/i.test(file.name) && file.type !== 'text/html') {\n error.value = m.value.wrongType\n return\n }\n if (file.size > options.value.maxSize * 1024) {\n error.value = m.value.tooLarge(options.value.maxSize)\n return\n }\n error.value = ''\n const text = await file.text()\n draft.value = text\n props.updateAttributes({ code: text, fileName: file.name })\n mode.value = 'preview'\n}\n\n// --- Resize & fullscreen --------------------------------------------------------\nconst resizing = ref(false)\nfunction startResize(e: PointerEvent) {\n e.preventDefault()\n resizing.value = true\n const startY = e.clientY\n const startH = height.value\n const move = (ev: PointerEvent) => {\n props.updateAttributes({ height: Math.round(Math.min(HTML_MAX_HEIGHT, Math.max(HTML_MIN_HEIGHT, startH + ev.clientY - startY))) })\n }\n const up = () => {\n resizing.value = false\n window.removeEventListener('pointermove', move)\n window.removeEventListener('pointerup', up)\n }\n window.addEventListener('pointermove', move)\n window.addEventListener('pointerup', up)\n}\n\nfunction onFullscreenKey(e: KeyboardEvent) {\n if (e.key === 'Escape') fullscreen.value = false\n}\nwatch(fullscreen, (open) => {\n if (open) window.addEventListener('keydown', onFullscreenKey)\n else window.removeEventListener('keydown', onFullscreenKey)\n})\nonBeforeUnmount(() => {\n commit()\n window.removeEventListener('keydown', onFullscreenKey)\n})\n\n// Sandbox: scripts, forms and dialogs run, but never with the editor's origin.\nconst SANDBOX = 'allow-scripts allow-forms allow-modals allow-popups allow-pointer-lock allow-downloads'\n</script>\n\n<template>\n <NodeViewWrapper class=\"me-html\" :class=\"{ 'is-selected': selected, 'is-readonly-empty': !editable && !code }\">\n <div ref=\"root\" class=\"me-html-frame\" contenteditable=\"false\">\n <div class=\"me-block-bar me-html-bar\">\n <CodeXml />\n <span class=\"me-html-name\">{{ name }}</span>\n <div v-if=\"editable\" class=\"me-tabs me-tabs--inline\" role=\"tablist\">\n <button type=\"button\" class=\"me-tab\" :class=\"{ 'is-active': mode === 'code' }\" role=\"tab\" :aria-selected=\"mode === 'code'\" @click=\"showCode\">\n <Code /> {{ m.code }}\n </button>\n <button type=\"button\" class=\"me-tab\" :class=\"{ 'is-active': mode === 'preview' }\" role=\"tab\" :aria-selected=\"mode === 'preview'\" @click=\"showPreview\">\n <Eye /> {{ m.preview }}\n </button>\n </div>\n <button v-if=\"editable\" type=\"button\" class=\"me-tool-btn\" :title=\"m.upload\" @click=\"fileInput?.click()\">\n <Upload />\n </button>\n <button v-if=\"code\" type=\"button\" class=\"me-tool-btn\" :title=\"m.expand\" @click=\"commit(); fullscreen = true\">\n <Maximize2 />\n </button>\n <input ref=\"fileInput\" type=\"file\" accept=\".html,.htm,text/html\" hidden @change=\"onFile\">\n </div>\n\n <p v-if=\"error\" class=\"me-error me-html-error\">\n {{ error }}\n </p>\n\n <!-- Empty block: write or upload. -->\n <!-- Same layout and buttons as the image/file upload placeholders. -->\n <div v-if=\"mode === 'preview' && !code\" class=\"me-media-body me-html-empty\">\n <div v-if=\"editable\" class=\"me-inline-form\">\n <button type=\"button\" class=\"me-btn\" @click=\"showCode\">\n <Code /> {{ m.write }}\n </button>\n <button type=\"button\" class=\"me-btn\" @click=\"fileInput?.click()\">\n <Upload /> {{ m.uploadFile }}\n </button>\n </div>\n <p class=\"me-hint\">\n {{ m.emptyHint }}\n </p>\n </div>\n\n <div v-else-if=\"mode === 'preview'\" class=\"me-html-body\" :style=\"{ height: `${height}px` }\">\n <iframe\n class=\"me-html-iframe\"\n :class=\"{ 'is-live': interacting }\"\n :srcdoc=\"srcdoc\"\n :sandbox=\"SANDBOX\"\n :title=\"name\"\n loading=\"lazy\"\n referrerpolicy=\"no-referrer\"\n />\n <!-- Until \"Interact\", clicks and wheel go to the page, not the frame (like Notion). -->\n <div v-if=\"!interacting\" class=\"me-html-cover\" @dblclick=\"interacting = true\">\n <button type=\"button\" class=\"me-btn me-btn--floating\" @click=\"interacting = true\">\n <Pointer /> {{ m.interact }}\n </button>\n </div>\n </div>\n\n <div v-else class=\"me-html-editor\" :style=\"{ height: `${height}px` }\">\n <!-- A div, not <pre>: ProseMirror's unlayered `pre` styles would make it wrap. -->\n <div ref=\"highlightEl\" class=\"me-html-highlight\" aria-hidden=\"true\" v-html=\"highlighted\" />\n <textarea\n ref=\"textarea\"\n v-model=\"draft\"\n class=\"me-html-textarea\"\n spellcheck=\"false\"\n wrap=\"off\"\n autocapitalize=\"off\"\n autocomplete=\"off\"\n :placeholder=\"m.placeholder\"\n @input=\"onInput\"\n @blur=\"commit\"\n @scroll=\"syncScroll\"\n @keydown=\"onKeydown\"\n />\n </div>\n\n <!-- Iframes swallow pointer events; cover them while resizing. -->\n <div v-if=\"resizing\" class=\"me-embed-overlay\" />\n <span v-if=\"editable\" class=\"me-embed-resize\" @pointerdown=\"startResize\" />\n </div>\n\n <Teleport to=\"body\">\n <div v-if=\"fullscreen\" v-bind=\"scope\" class=\"me-html-modal\" @mousedown.self=\"fullscreen = false\">\n <div class=\"me-html-modal-panel\">\n <div class=\"me-block-bar me-html-bar\">\n <CodeXml />\n <span class=\"me-html-name\">{{ name }}</span>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.close\" @click=\"fullscreen = false\">\n <X />\n </button>\n </div>\n <iframe class=\"me-html-iframe is-live\" :srcdoc=\"srcdoc\" :sandbox=\"SANDBOX\" :title=\"name\" referrerpolicy=\"no-referrer\" />\n </div>\n </div>\n </Teleport>\n </NodeViewWrapper>\n</template>\n","<script setup lang=\"ts\">\n/**\n * Notion-style HTML block. The page runs in a sandboxed iframe of fixed height; it only\n * takes clicks/scrolls after \"Interact\" (so scrolling the document isn't hijacked).\n * Editors can switch to Code to edit in place, upload an .html file, or drag the height.\n */\nimport { NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport { Code, CodeXml, Eye, Maximize2, Pointer, Upload, X } from '@lucide/vue'\nimport { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue'\nimport { useClickOutside } from '../composables/useClickOutside'\nimport { useEditable } from '../composables/useEditable'\nimport { useScope } from '../composables/useScope'\nimport { loadLanguage, lowlight } from '../extensions/code-block'\nimport { HTML_MAX_HEIGHT, HTML_MIN_HEIGHT, type HtmlBlockOptions, htmlBlockDocument } from '../extensions/html-block'\n\nconst props = defineProps(nodeViewProps)\n\nconst scope = useScope(() => props.editor)\nconst editable = useEditable(props.editor)\nconst m = computed(() => props.editor.storage.meiConfig.messages.html)\nconst options = computed(() => props.extension.options as HtmlBlockOptions)\nconst code = computed(() => (props.node.attrs.code as string) ?? '')\nconst height = computed(() => (props.node.attrs.height as number | null) ?? options.value.defaultHeight)\nconst name = computed(() => (props.node.attrs.fileName as string | null) || m.value.title)\nconst srcdoc = computed(() => htmlBlockDocument(code.value, options.value.network))\n\n// --- Modes ----------------------------------------------------------------------\nconst mode = ref<'preview' | 'code'>('preview')\nconst interacting = ref(false)\nconst fullscreen = ref(false)\nconst root = ref<HTMLElement | null>(null)\nuseClickOutside(root, interacting, () => (interacting.value = false))\n\nfunction showCode() {\n error.value = ''\n mode.value = 'code'\n interacting.value = false\n nextTick(() => textarea.value?.focus())\n}\nfunction showPreview() {\n error.value = ''\n commit()\n mode.value = 'preview'\n}\n\n// Read-only: back to the preview.\nwatch(editable, (value) => {\n if (!value && mode.value === 'code') showPreview()\n})\n\n// --- Code editor ----------------------------------------------------------------\nconst draft = ref(code.value)\nwatch(code, (value) => {\n if (value !== draft.value) draft.value = value\n})\nconst textarea = ref<HTMLTextAreaElement | null>(null)\nconst highlightEl = ref<HTMLElement | null>(null)\n\nlet timer: ReturnType<typeof setTimeout> | undefined\nfunction commit() {\n clearTimeout(timer)\n if (draft.value !== code.value) props.updateAttributes({ code: draft.value })\n}\nfunction onInput() {\n clearTimeout(timer)\n timer = setTimeout(commit, 400)\n}\nfunction onKeydown(e: KeyboardEvent) {\n if (e.key === 'Tab') {\n // Indent instead of leaving the editor.\n e.preventDefault()\n const el = e.target as HTMLTextAreaElement\n el.setRangeText(' ', el.selectionStart, el.selectionEnd, 'end')\n draft.value = el.value\n onInput()\n }\n else if (e.key === 'Escape' || (e.key === 'Enter' && (e.metaKey || e.ctrlKey))) {\n e.preventDefault()\n showPreview()\n }\n}\nfunction syncScroll() {\n if (highlightEl.value && textarea.value) {\n highlightEl.value.scrollTop = textarea.value.scrollTop\n highlightEl.value.scrollLeft = textarea.value.scrollLeft\n }\n}\n\n// Syntax colors: HTML grammar plus the CSS/JS it embeds, loaded on first use.\nconst grammarReady = ref(false)\nwatch(mode, (value) => {\n if (value === 'code' && !grammarReady.value) {\n Promise.all(['xml', 'css', 'javascript'].map(loadLanguage)).then(() => (grammarReady.value = true))\n }\n}, { immediate: true })\n\ntype HastNode = { type: string, value?: string, tagName?: string, properties?: { className?: string[] }, children?: HastNode[] }\nconst escapeHtml = (s: string) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')\nfunction toHtml(node: HastNode): string {\n if (node.type === 'text') return escapeHtml(node.value ?? '')\n const inner = (node.children ?? []).map(toHtml).join('')\n if (node.type === 'element') return `<span class=\"${(node.properties?.className ?? []).join(' ')}\">${inner}</span>`\n return inner\n}\nconst highlighted = computed(() => {\n // Trailing newline keeps the last line's height in sync with the textarea.\n const text = `${draft.value}\\n`\n if (!grammarReady.value || !lowlight.registered('xml')) return escapeHtml(text)\n return toHtml(lowlight.highlight('xml', text) as HastNode)\n})\n\n// --- Upload ---------------------------------------------------------------------\nconst fileInput = ref<HTMLInputElement | null>(null)\nconst error = ref('')\nasync function onFile(e: Event) {\n const input = e.target as HTMLInputElement\n const file = input.files?.[0]\n input.value = ''\n if (!file) return\n if (!/\\.html?$/i.test(file.name) && file.type !== 'text/html') {\n error.value = m.value.wrongType\n return\n }\n if (file.size > options.value.maxSize * 1024) {\n error.value = m.value.tooLarge(options.value.maxSize)\n return\n }\n error.value = ''\n const text = await file.text()\n draft.value = text\n props.updateAttributes({ code: text, fileName: file.name })\n mode.value = 'preview'\n}\n\n// --- Resize & fullscreen --------------------------------------------------------\nconst resizing = ref(false)\nfunction startResize(e: PointerEvent) {\n e.preventDefault()\n resizing.value = true\n const startY = e.clientY\n const startH = height.value\n const move = (ev: PointerEvent) => {\n props.updateAttributes({ height: Math.round(Math.min(HTML_MAX_HEIGHT, Math.max(HTML_MIN_HEIGHT, startH + ev.clientY - startY))) })\n }\n const up = () => {\n resizing.value = false\n window.removeEventListener('pointermove', move)\n window.removeEventListener('pointerup', up)\n }\n window.addEventListener('pointermove', move)\n window.addEventListener('pointerup', up)\n}\n\nfunction onFullscreenKey(e: KeyboardEvent) {\n if (e.key === 'Escape') fullscreen.value = false\n}\nwatch(fullscreen, (open) => {\n if (open) window.addEventListener('keydown', onFullscreenKey)\n else window.removeEventListener('keydown', onFullscreenKey)\n})\nonBeforeUnmount(() => {\n commit()\n window.removeEventListener('keydown', onFullscreenKey)\n})\n\n// Sandbox: scripts, forms and dialogs run, but never with the editor's origin.\nconst SANDBOX = 'allow-scripts allow-forms allow-modals allow-popups allow-pointer-lock allow-downloads'\n</script>\n\n<template>\n <NodeViewWrapper class=\"me-html\" :class=\"{ 'is-selected': selected, 'is-readonly-empty': !editable && !code }\">\n <div ref=\"root\" class=\"me-html-frame\" contenteditable=\"false\">\n <div class=\"me-block-bar me-html-bar\">\n <CodeXml />\n <span class=\"me-html-name\">{{ name }}</span>\n <div v-if=\"editable\" class=\"me-tabs me-tabs--inline\" role=\"tablist\">\n <button type=\"button\" class=\"me-tab\" :class=\"{ 'is-active': mode === 'code' }\" role=\"tab\" :aria-selected=\"mode === 'code'\" @click=\"showCode\">\n <Code /> {{ m.code }}\n </button>\n <button type=\"button\" class=\"me-tab\" :class=\"{ 'is-active': mode === 'preview' }\" role=\"tab\" :aria-selected=\"mode === 'preview'\" @click=\"showPreview\">\n <Eye /> {{ m.preview }}\n </button>\n </div>\n <button v-if=\"editable\" type=\"button\" class=\"me-tool-btn\" :title=\"m.upload\" @click=\"fileInput?.click()\">\n <Upload />\n </button>\n <button v-if=\"code\" type=\"button\" class=\"me-tool-btn\" :title=\"m.expand\" @click=\"commit(); fullscreen = true\">\n <Maximize2 />\n </button>\n <input ref=\"fileInput\" type=\"file\" accept=\".html,.htm,text/html\" hidden @change=\"onFile\">\n </div>\n\n <p v-if=\"error\" class=\"me-error me-html-error\">\n {{ error }}\n </p>\n\n <!-- Empty block: write or upload. -->\n <!-- Same layout and buttons as the image/file upload placeholders. -->\n <div v-if=\"mode === 'preview' && !code\" class=\"me-media-body me-html-empty\">\n <div v-if=\"editable\" class=\"me-inline-form\">\n <button type=\"button\" class=\"me-btn\" @click=\"showCode\">\n <Code /> {{ m.write }}\n </button>\n <button type=\"button\" class=\"me-btn\" @click=\"fileInput?.click()\">\n <Upload /> {{ m.uploadFile }}\n </button>\n </div>\n <p class=\"me-hint\">\n {{ m.emptyHint }}\n </p>\n </div>\n\n <div v-else-if=\"mode === 'preview'\" class=\"me-html-body\" :style=\"{ height: `${height}px` }\">\n <iframe\n class=\"me-html-iframe\"\n :class=\"{ 'is-live': interacting }\"\n :srcdoc=\"srcdoc\"\n :sandbox=\"SANDBOX\"\n :title=\"name\"\n loading=\"lazy\"\n referrerpolicy=\"no-referrer\"\n />\n <!-- Until \"Interact\", clicks and wheel go to the page, not the frame (like Notion). -->\n <div v-if=\"!interacting\" class=\"me-html-cover\" @dblclick=\"interacting = true\">\n <button type=\"button\" class=\"me-btn me-btn--floating\" @click=\"interacting = true\">\n <Pointer /> {{ m.interact }}\n </button>\n </div>\n </div>\n\n <div v-else class=\"me-html-editor\" :style=\"{ height: `${height}px` }\">\n <!-- A div, not <pre>: ProseMirror's unlayered `pre` styles would make it wrap. -->\n <div ref=\"highlightEl\" class=\"me-html-highlight\" aria-hidden=\"true\" v-html=\"highlighted\" />\n <textarea\n ref=\"textarea\"\n v-model=\"draft\"\n class=\"me-html-textarea\"\n spellcheck=\"false\"\n wrap=\"off\"\n autocapitalize=\"off\"\n autocomplete=\"off\"\n :placeholder=\"m.placeholder\"\n @input=\"onInput\"\n @blur=\"commit\"\n @scroll=\"syncScroll\"\n @keydown=\"onKeydown\"\n />\n </div>\n\n <!-- Iframes swallow pointer events; cover them while resizing. -->\n <div v-if=\"resizing\" class=\"me-embed-overlay\" />\n <span v-if=\"editable\" class=\"me-embed-resize\" @pointerdown=\"startResize\" />\n </div>\n\n <Teleport to=\"body\">\n <div v-if=\"fullscreen\" v-bind=\"scope\" class=\"me-html-modal\" @mousedown.self=\"fullscreen = false\">\n <div class=\"me-html-modal-panel\">\n <div class=\"me-block-bar me-html-bar\">\n <CodeXml />\n <span class=\"me-html-name\">{{ name }}</span>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.close\" @click=\"fullscreen = false\">\n <X />\n </button>\n </div>\n <iframe class=\"me-html-iframe is-live\" :srcdoc=\"srcdoc\" :sandbox=\"SANDBOX\" :title=\"name\" referrerpolicy=\"no-referrer\" />\n </div>\n </div>\n </Teleport>\n </NodeViewWrapper>\n</template>\n","import { Node } from '@tiptap/core'\nimport { blockNodeView } from '../nodeviews/renderer'\nimport HtmlView from '../nodeviews/HtmlView.vue'\nimport type { HtmlBlockOptions } from './html-document'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n htmlBlock: {\n insertHtmlBlock: (attrs?: { code?: string, fileName?: string | null }) => ReturnType\n }\n }\n}\n\nexport { HTML_MAX_HEIGHT, HTML_MIN_HEIGHT, htmlBlockCsp, htmlBlockDocument, type HtmlBlockOptions } from './html-document'\n\n/** Notion-style HTML block: your own HTML/CSS/JS, running in a sandboxed frame. */\nexport const HtmlBlock = Node.create<HtmlBlockOptions>({\n name: 'htmlBlock',\n group: 'block',\n atom: true,\n draggable: true,\n\n addOptions: () => ({ network: false, maxSize: 1024, defaultHeight: 400 }),\n\n addAttributes() {\n return {\n code: { default: '' },\n fileName: { default: null },\n height: { default: null },\n }\n },\n\n parseHTML() {\n return [{\n tag: 'div[data-type=\"html-block\"]',\n getAttrs: el => ({\n code: el.getAttribute('data-code') ?? '',\n fileName: el.getAttribute('data-file-name'),\n height: Number(el.getAttribute('data-height')) || null,\n }),\n }]\n },\n\n // The code is kept in an attribute, so exported HTML never runs it.\n renderHTML({ node }) {\n return ['div', {\n 'data-type': 'html-block',\n 'data-code': node.attrs.code ?? '',\n ...(node.attrs.fileName ? { 'data-file-name': node.attrs.fileName } : {}),\n ...(node.attrs.height ? { 'data-height': node.attrs.height } : {}),\n }]\n },\n\n renderText: ({ node }) => node.attrs.code ?? '',\n\n addCommands() {\n return {\n insertHtmlBlock: attrs => ({ commands }) => commands.insertContent({ type: this.name, attrs: { height: this.options.defaultHeight, ...attrs } }),\n }\n },\n\n addNodeView() {\n return blockNodeView(HtmlView)\n },\n})\n","<script setup lang=\"ts\">\nimport { NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'\nimport { useClickOutside } from '../composables/useClickOutside'\nimport { useEditable } from '../composables/useEditable'\nimport { loadKatex } from '../lazy'\n\nconst props = defineProps(nodeViewProps)\nconst editable = useEditable(props.editor)\n\nconst m = computed(() => props.editor.storage.meiConfig.messages.math)\nconst inline = computed(() => props.node.type.name === 'mathInline')\nconst rendered = ref('')\nconst error = ref('')\nconst editing = ref(false)\nconst draft = ref(props.node.attrs.latex as string)\nconst root = ref<HTMLElement | null>(null)\nconst input = ref<HTMLTextAreaElement | null>(null)\n\nasync function render(latex: string) {\n if (!latex.trim()) {\n rendered.value = ''\n return\n }\n try {\n const katex = await loadKatex()\n rendered.value = katex.renderToString(latex, { displayMode: !inline.value, throwOnError: false })\n error.value = ''\n }\n catch {\n error.value = m.value.missing\n }\n}\n\nwatch(() => props.node.attrs.latex, latex => render(latex), { immediate: true })\nwatch(draft, latex => render(latex))\n\nfunction open() {\n if (!props.editor.isEditable) return\n draft.value = props.node.attrs.latex\n editing.value = true\n nextTick(() => input.value?.focus())\n}\nfunction commit() {\n if (!editing.value) return\n editing.value = false\n if (draft.value !== props.node.attrs.latex) props.updateAttributes({ latex: draft.value })\n if (!draft.value.trim() && inline.value) props.deleteNode()\n}\nfunction onKeydown(e: KeyboardEvent) {\n e.stopPropagation()\n if (e.key === 'Escape' || (e.key === 'Enter' && (inline.value || e.metaKey || e.ctrlKey))) {\n e.preventDefault()\n commit()\n props.editor.commands.focus()\n }\n}\nuseClickOutside(root, editing, commit)\n\n// Switching to read-only closes the editor, keeping what was typed (no deletes then).\nwatch(editable, (value) => {\n if (value || !editing.value) return\n editing.value = false\n if (draft.value !== props.node.attrs.latex) props.updateAttributes({ latex: draft.value })\n})\n\n// A freshly inserted empty equation opens straight into editing.\nonMounted(() => {\n if (!props.node.attrs.latex) open()\n})\nonBeforeUnmount(commit)\n</script>\n\n<template>\n <NodeViewWrapper\n ref=\"root\"\n :as=\"inline ? 'span' : 'div'\"\n :class=\"[inline ? 'me-math-inline' : 'me-math-block', { 'is-selected': selected, 'is-editing': editing, 'is-readonly-empty': !editable && !node.attrs.latex }]\"\n contenteditable=\"false\"\n >\n <span v-if=\"rendered\" class=\"me-math-render\" @click=\"open\" v-html=\"rendered\" />\n <span v-else class=\"me-math-empty\" @click=\"open\">{{ m.placeholder }}</span>\n <span v-if=\"error\" class=\"me-error\">{{ error }}</span>\n <span v-if=\"editing\" class=\"me-popover me-math-editor\">\n <textarea\n ref=\"input\"\n v-model=\"draft\"\n class=\"me-input me-math-input\"\n :rows=\"inline ? 1 : 3\"\n :placeholder=\"m.inputPlaceholder\"\n spellcheck=\"false\"\n @keydown=\"onKeydown\"\n />\n <span class=\"me-hint\">{{ inline ? m.hintInline : m.hintBlock }}</span>\n </span>\n </NodeViewWrapper>\n</template>\n","<script setup lang=\"ts\">\nimport { NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'\nimport { useClickOutside } from '../composables/useClickOutside'\nimport { useEditable } from '../composables/useEditable'\nimport { loadKatex } from '../lazy'\n\nconst props = defineProps(nodeViewProps)\nconst editable = useEditable(props.editor)\n\nconst m = computed(() => props.editor.storage.meiConfig.messages.math)\nconst inline = computed(() => props.node.type.name === 'mathInline')\nconst rendered = ref('')\nconst error = ref('')\nconst editing = ref(false)\nconst draft = ref(props.node.attrs.latex as string)\nconst root = ref<HTMLElement | null>(null)\nconst input = ref<HTMLTextAreaElement | null>(null)\n\nasync function render(latex: string) {\n if (!latex.trim()) {\n rendered.value = ''\n return\n }\n try {\n const katex = await loadKatex()\n rendered.value = katex.renderToString(latex, { displayMode: !inline.value, throwOnError: false })\n error.value = ''\n }\n catch {\n error.value = m.value.missing\n }\n}\n\nwatch(() => props.node.attrs.latex, latex => render(latex), { immediate: true })\nwatch(draft, latex => render(latex))\n\nfunction open() {\n if (!props.editor.isEditable) return\n draft.value = props.node.attrs.latex\n editing.value = true\n nextTick(() => input.value?.focus())\n}\nfunction commit() {\n if (!editing.value) return\n editing.value = false\n if (draft.value !== props.node.attrs.latex) props.updateAttributes({ latex: draft.value })\n if (!draft.value.trim() && inline.value) props.deleteNode()\n}\nfunction onKeydown(e: KeyboardEvent) {\n e.stopPropagation()\n if (e.key === 'Escape' || (e.key === 'Enter' && (inline.value || e.metaKey || e.ctrlKey))) {\n e.preventDefault()\n commit()\n props.editor.commands.focus()\n }\n}\nuseClickOutside(root, editing, commit)\n\n// Switching to read-only closes the editor, keeping what was typed (no deletes then).\nwatch(editable, (value) => {\n if (value || !editing.value) return\n editing.value = false\n if (draft.value !== props.node.attrs.latex) props.updateAttributes({ latex: draft.value })\n})\n\n// A freshly inserted empty equation opens straight into editing.\nonMounted(() => {\n if (!props.node.attrs.latex) open()\n})\nonBeforeUnmount(commit)\n</script>\n\n<template>\n <NodeViewWrapper\n ref=\"root\"\n :as=\"inline ? 'span' : 'div'\"\n :class=\"[inline ? 'me-math-inline' : 'me-math-block', { 'is-selected': selected, 'is-editing': editing, 'is-readonly-empty': !editable && !node.attrs.latex }]\"\n contenteditable=\"false\"\n >\n <span v-if=\"rendered\" class=\"me-math-render\" @click=\"open\" v-html=\"rendered\" />\n <span v-else class=\"me-math-empty\" @click=\"open\">{{ m.placeholder }}</span>\n <span v-if=\"error\" class=\"me-error\">{{ error }}</span>\n <span v-if=\"editing\" class=\"me-popover me-math-editor\">\n <textarea\n ref=\"input\"\n v-model=\"draft\"\n class=\"me-input me-math-input\"\n :rows=\"inline ? 1 : 3\"\n :placeholder=\"m.inputPlaceholder\"\n spellcheck=\"false\"\n @keydown=\"onKeydown\"\n />\n <span class=\"me-hint\">{{ inline ? m.hintInline : m.hintBlock }}</span>\n </span>\n </NodeViewWrapper>\n</template>\n","import { InputRule, mergeAttributes, Node } from '@tiptap/core'\nimport { blockNodeView } from '../nodeviews/renderer'\nimport MathView from '../nodeviews/MathView.vue'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n math: {\n insertMathBlock: (latex?: string) => ReturnType\n insertMathInline: (latex?: string) => ReturnType\n }\n }\n}\n\nconst latexAttr = {\n latex: {\n default: '',\n parseHTML: (el: HTMLElement) => el.getAttribute('data-latex') ?? '',\n renderHTML: (attrs: Record<string, any>) => ({ 'data-latex': attrs.latex }),\n },\n}\n\n/** Display equation (KaTeX, loaded on first render). Type `$$ ` on an empty line. */\nexport const MathBlock = Node.create({\n name: 'mathBlock',\n group: 'block',\n atom: true,\n draggable: true,\n addAttributes: () => latexAttr,\n parseHTML: () => [{ tag: 'div[data-type=\"math-block\"]' }],\n renderHTML: ({ HTMLAttributes }) => ['div', mergeAttributes(HTMLAttributes, { 'data-type': 'math-block' })],\n addCommands() {\n return { insertMathBlock: (latex = '') => ({ commands }) => commands.insertContent({ type: this.name, attrs: { latex } }) }\n },\n addInputRules() {\n return [new InputRule({\n find: /^\\$\\$\\s$/,\n handler: ({ range, chain }) => {\n chain().deleteRange(range).insertMathBlock().run()\n },\n })]\n },\n addNodeView: () => blockNodeView(MathView),\n})\n\n/** Inline equation. Type `$$x^2$$` (single `$` would catch prices like $5). */\nexport const MathInline = Node.create({\n name: 'mathInline',\n group: 'inline',\n inline: true,\n atom: true,\n addAttributes: () => latexAttr,\n parseHTML: () => [{ tag: 'span[data-type=\"math-inline\"]' }],\n renderHTML: ({ HTMLAttributes }) => ['span', mergeAttributes(HTMLAttributes, { 'data-type': 'math-inline' })],\n renderText: ({ node }) => `$${node.attrs.latex}$`,\n addCommands() {\n return { insertMathInline: (latex = '') => ({ commands }) => commands.insertContent({ type: this.name, attrs: { latex } }) }\n },\n addInputRules() {\n return [new InputRule({\n find: /\\$\\$([^$\\n]+)\\$\\$$/,\n handler: ({ state, range, match }) => {\n state.tr.replaceWith(range.from, range.to, this.type.create({ latex: match[1]!.trim() }))\n },\n })]\n },\n addNodeView: () => blockNodeView(MathView),\n})\n","<script setup lang=\"ts\">\nimport type { Editor } from '@tiptap/core'\nimport { Calendar, FileText, User } from '@lucide/vue'\nimport { computed, nextTick, ref, watch } from 'vue'\nimport { useScope } from '../composables/useScope'\nimport type { MentionItem } from '../extensions/mention'\nimport { usePointerMoved } from '../composables/usePointerMoved'\n\nconst props = defineProps<{ editor: Editor, items: MentionItem[], command: (item: MentionItem) => void }>()\nconst scope = useScope(() => props.editor)\nconst m = computed(() => props.editor.storage.meiConfig.messages.mention)\nconst selected = ref(0)\nconst root = ref<HTMLElement | null>(null)\nconst ICONS = { user: User, page: FileText, date: Calendar }\n\nconst groups = computed(() => {\n const order: MentionItem['kind'][] = ['user', 'page', 'date']\n const label = { user: m.value.people, page: m.value.pages, date: m.value.dates }\n return order\n .map(kind => ({ kind, label: label[kind], entries: props.items.map((item, index) => ({ item, index })).filter(e => e.item.kind === kind) }))\n .filter(g => g.entries.length)\n})\n\nwatch(() => props.items, () => (selected.value = 0))\nwatch(selected, async (i) => {\n await nextTick()\n root.value?.querySelector(`[data-index=\"${i}\"]`)?.scrollIntoView({ block: 'nearest' })\n})\n\nfunction onKeyDown(e: KeyboardEvent) {\n const n = props.items.length\n if (!n) return false\n if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {\n selected.value = (selected.value + (e.key === 'ArrowDown' ? 1 : n - 1)) % n\n return true\n }\n if (e.key === 'Enter' || e.key === 'Tab') {\n const item = props.items[selected.value]\n if (item) props.command(item)\n return true\n }\n return false\n}\ndefineExpose({ onKeyDown })\n\n// Hover selects a row only after a real pointer move (KS-BUG-3).\nconst pointerMoved = usePointerMoved()\n</script>\n\n<template>\n <div ref=\"root\" v-bind=\"scope\" class=\"me-popover me-menu\">\n <div v-for=\"g in groups\" :key=\"g.kind\">\n <div class=\"me-menu-label\">\n {{ g.label }}\n </div>\n <button\n v-for=\"{ item, index } in g.entries\"\n :key=\"`${item.kind}-${item.id}`\"\n type=\"button\"\n class=\"me-menu-item\"\n :class=\"{ 'is-active': index === selected }\"\n :data-index=\"index\"\n @mousemove=\"pointerMoved($event) && (selected = index)\"\n @mousedown.prevent=\"command(item)\"\n >\n <img v-if=\"item.avatar\" class=\"me-menu-icon me-avatar\" :src=\"item.avatar\" alt=\"\">\n <span v-else class=\"me-menu-icon\"><component :is=\"ICONS[item.kind]\" /></span>\n <span class=\"me-menu-text\">\n <span class=\"me-menu-title\">{{ item.label }}</span>\n <span v-if=\"item.description\" class=\"me-menu-desc\">{{ item.description }}</span>\n </span>\n </button>\n </div>\n <div v-if=\"!items.length\" class=\"me-menu-empty\">\n {{ m.empty }}\n </div>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport type { Editor } from '@tiptap/core'\nimport { Calendar, FileText, User } from '@lucide/vue'\nimport { computed, nextTick, ref, watch } from 'vue'\nimport { useScope } from '../composables/useScope'\nimport type { MentionItem } from '../extensions/mention'\nimport { usePointerMoved } from '../composables/usePointerMoved'\n\nconst props = defineProps<{ editor: Editor, items: MentionItem[], command: (item: MentionItem) => void }>()\nconst scope = useScope(() => props.editor)\nconst m = computed(() => props.editor.storage.meiConfig.messages.mention)\nconst selected = ref(0)\nconst root = ref<HTMLElement | null>(null)\nconst ICONS = { user: User, page: FileText, date: Calendar }\n\nconst groups = computed(() => {\n const order: MentionItem['kind'][] = ['user', 'page', 'date']\n const label = { user: m.value.people, page: m.value.pages, date: m.value.dates }\n return order\n .map(kind => ({ kind, label: label[kind], entries: props.items.map((item, index) => ({ item, index })).filter(e => e.item.kind === kind) }))\n .filter(g => g.entries.length)\n})\n\nwatch(() => props.items, () => (selected.value = 0))\nwatch(selected, async (i) => {\n await nextTick()\n root.value?.querySelector(`[data-index=\"${i}\"]`)?.scrollIntoView({ block: 'nearest' })\n})\n\nfunction onKeyDown(e: KeyboardEvent) {\n const n = props.items.length\n if (!n) return false\n if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {\n selected.value = (selected.value + (e.key === 'ArrowDown' ? 1 : n - 1)) % n\n return true\n }\n if (e.key === 'Enter' || e.key === 'Tab') {\n const item = props.items[selected.value]\n if (item) props.command(item)\n return true\n }\n return false\n}\ndefineExpose({ onKeyDown })\n\n// Hover selects a row only after a real pointer move (KS-BUG-3).\nconst pointerMoved = usePointerMoved()\n</script>\n\n<template>\n <div ref=\"root\" v-bind=\"scope\" class=\"me-popover me-menu\">\n <div v-for=\"g in groups\" :key=\"g.kind\">\n <div class=\"me-menu-label\">\n {{ g.label }}\n </div>\n <button\n v-for=\"{ item, index } in g.entries\"\n :key=\"`${item.kind}-${item.id}`\"\n type=\"button\"\n class=\"me-menu-item\"\n :class=\"{ 'is-active': index === selected }\"\n :data-index=\"index\"\n @mousemove=\"pointerMoved($event) && (selected = index)\"\n @mousedown.prevent=\"command(item)\"\n >\n <img v-if=\"item.avatar\" class=\"me-menu-icon me-avatar\" :src=\"item.avatar\" alt=\"\">\n <span v-else class=\"me-menu-icon\"><component :is=\"ICONS[item.kind]\" /></span>\n <span class=\"me-menu-text\">\n <span class=\"me-menu-title\">{{ item.label }}</span>\n <span v-if=\"item.description\" class=\"me-menu-desc\">{{ item.description }}</span>\n </span>\n </button>\n </div>\n <div v-if=\"!items.length\" class=\"me-menu-empty\">\n {{ m.empty }}\n </div>\n </div>\n</template>\n","<script setup lang=\"ts\">\n/**\n * Notion-style date picker for date mentions: typed date/time inputs, month calendar,\n * end date (range), date & time formats, reminders, clear.\n */\nimport { Check, ChevronLeft, ChevronRight, CircleQuestionMark } from '@lucide/vue'\nimport { computed, ref, watch } from 'vue'\nimport {\n DATE_FORMATS, type DateFormat, type DateValue, formatDate, formatTime, isoDate, parseDateInput, parseIsoDate,\n parseTimeInput, REMINDERS_DATE, REMINDERS_TIME, type TimeFormat,\n} from '../date-utils'\nimport type { EditorMessages } from '../locale'\n\nconst props = defineProps<{\n value: DateValue\n locale: string\n messages: EditorMessages['datePicker']\n relative: { today: string, tomorrow: string, yesterday: string }\n helpUrl?: string | null\n}>()\nconst emit = defineEmits<{ change: [value: DateValue], clear: [] }>()\n\nconst m = computed(() => props.messages)\nconst v = computed(() => props.value)\nconst update = (patch: Partial<DateValue>) => emit('change', { ...props.value, ...patch })\n\n// --- Typed inputs -------------------------------------------------------------\n/** Which input the next calendar click fills (Notion alternates start → end). */\nconst editing = ref<'start' | 'end'>('start')\nconst inputFmt = (id: string | null | undefined) => (id ? formatDate(id, props.locale, 'short') : '')\nconst draft = ref({ start: '', end: '', time: '', endTime: '' })\nwatch(() => props.value, (val) => {\n draft.value = {\n start: inputFmt(val.start),\n end: inputFmt(val.end),\n time: val.time ? formatTime(val.time, props.locale, val.timeFormat ?? '24') : '',\n endTime: val.endTime ? formatTime(val.endTime, props.locale, val.timeFormat ?? '24') : '',\n }\n}, { immediate: true, deep: true })\n\nfunction commitDate(which: 'start' | 'end') {\n const parsed = parseDateInput(draft.value[which], props.locale)\n if (!parsed) {\n draft.value[which] = inputFmt(which === 'start' ? v.value.start : v.value.end)\n return\n }\n if (which === 'start') update({ start: parsed })\n else update({ end: parsed })\n view.value = monthOf(parsed)\n}\nfunction commitTime(which: 'time' | 'endTime') {\n const parsed = parseTimeInput(draft.value[which])\n if (parsed) update({ [which]: parsed })\n else draft.value[which] = v.value[which] ? formatTime(v.value[which]!, props.locale, v.value.timeFormat ?? '24') : ''\n}\n\n// --- Calendar -----------------------------------------------------------------\nconst monthOf = (id: string) => {\n const d = parseIsoDate(id) ?? new Date()\n return new Date(d.getFullYear(), d.getMonth(), 1)\n}\nconst view = ref(monthOf(props.value.start))\nconst today = isoDate(new Date())\n// \"Oct 2026\" / \"Tháng 11 2026\": month + year only, short enough for one line.\nconst monthLabel = computed(() => {\n // Chinese / Japanese / Korean read year first: \"2026年10月\".\n if (/^(zh|ja|ko)/.test(props.locale)) return new Intl.DateTimeFormat(props.locale, { year: 'numeric', month: 'long' }).format(view.value)\n const month = new Intl.DateTimeFormat(props.locale, { month: props.locale.startsWith('en') ? 'short' : 'long' }).format(view.value)\n return `${month.charAt(0).toUpperCase()}${month.slice(1)} ${view.value.getFullYear()}`\n})\n// Weeks start on Monday (like Notion's default).\nconst weekdays = computed(() => {\n const fmt = new Intl.DateTimeFormat(props.locale, { weekday: /^(vi|zh)/.test(props.locale) ? 'narrow' : 'short' })\n return Array.from({ length: 7 }, (_, i) => fmt.format(new Date(2023, 0, 2 + i)).slice(0, 2))\n})\nconst days = computed(() => {\n const first = view.value\n const offset = (first.getDay() + 6) % 7\n return Array.from({ length: 42 }, (_, i) => {\n const d = new Date(first.getFullYear(), first.getMonth(), 1 - offset + i)\n return { id: isoDate(d), day: d.getDate(), inMonth: d.getMonth() === first.getMonth() }\n })\n})\nconst inRange = (id: string) => !!v.value.end && id > v.value.start && id < v.value.end\n\nfunction pick(id: string) {\n if (!v.value.end || editing.value === 'start') {\n // With a range, keep start ≤ end.\n if (v.value.end && id > v.value.end) update({ start: id, end: id })\n else update({ start: id })\n if (v.value.end) editing.value = 'end'\n }\n else {\n if (id < v.value.start) update({ start: id, end: v.value.start })\n else update({ end: id })\n editing.value = 'start'\n }\n}\nfunction goToday() {\n view.value = monthOf(today)\n}\n\n// --- Options ------------------------------------------------------------------\nconst submenu = ref<'format' | 'timeFormat' | 'remind' | null>(null)\nconst reminders = computed(() => (v.value.time ? REMINDERS_TIME : REMINDERS_DATE))\nconst formatLabel = (f: DateFormat) => m.value.formats[f]\n\nfunction toggleEnd() {\n if (v.value.end) update({ end: null, endTime: null })\n else {\n update({ end: v.value.start, endTime: v.value.time ?? null })\n editing.value = 'end'\n }\n}\nfunction toggleTime() {\n // Date-only and timed reminders differ; reset an incompatible reminder.\n const remind = v.value.remind && v.value.remind !== 'none' ? null : v.value.remind\n if (v.value.time) update({ time: null, endTime: null, remind })\n else update({ time: '09:00', endTime: v.value.end ? '10:00' : null, remind })\n}\nfunction setFormat(format: DateFormat) {\n update({ format })\n submenu.value = null\n}\nfunction setTimeFormat(timeFormat: TimeFormat) {\n update({ timeFormat })\n submenu.value = null\n}\nfunction setRemind(remind: string) {\n update({ remind: remind === 'none' ? null : remind })\n submenu.value = null\n}\n</script>\n\n<template>\n <div class=\"me-datepicker\" @mouseleave=\"submenu = null\">\n <!-- Start and end side by side; stacked once times are shown too (like Notion). -->\n <div class=\"me-datepicker-inputs\" :class=\"{ 'is-split': !!value.end && !value.time }\">\n <div class=\"me-datepicker-field\" :class=\"{ 'is-active': editing === 'start' && !!value.end }\">\n <input v-model=\"draft.start\" class=\"me-datepicker-input\" @focus=\"editing = 'start'\" @keydown.enter.prevent=\"commitDate('start')\" @blur=\"commitDate('start')\">\n <input v-if=\"value.time\" v-model=\"draft.time\" class=\"me-datepicker-input me-datepicker-time\" @keydown.enter.prevent=\"commitTime('time')\" @blur=\"commitTime('time')\">\n </div>\n <div v-if=\"value.end\" class=\"me-datepicker-field\" :class=\"{ 'is-active': editing === 'end' }\">\n <input v-model=\"draft.end\" class=\"me-datepicker-input\" @focus=\"editing = 'end'\" @keydown.enter.prevent=\"commitDate('end')\" @blur=\"commitDate('end')\">\n <input v-if=\"value.time\" v-model=\"draft.endTime\" class=\"me-datepicker-input me-datepicker-time\" @keydown.enter.prevent=\"commitTime('endTime')\" @blur=\"commitTime('endTime')\">\n </div>\n </div>\n\n <div class=\"me-datepicker-head\">\n <span class=\"me-datepicker-month\">{{ monthLabel }}</span>\n <button type=\"button\" class=\"me-datepicker-today\" @click=\"goToday\">\n {{ relative.today }}\n </button>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.prevMonth\" @click=\"view = new Date(view.getFullYear(), view.getMonth() - 1, 1)\">\n <ChevronLeft />\n </button>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.nextMonth\" @click=\"view = new Date(view.getFullYear(), view.getMonth() + 1, 1)\">\n <ChevronRight />\n </button>\n </div>\n <div class=\"me-datepicker-grid\">\n <span v-for=\"(w, i) in weekdays\" :key=\"i\" class=\"me-datepicker-weekday\">{{ w }}</span>\n <button\n v-for=\"d in days\"\n :key=\"d.id\"\n type=\"button\"\n class=\"me-datepicker-day\"\n :class=\"{\n 'is-outside': !d.inMonth,\n 'is-today': d.id === today,\n 'is-selected': d.id === value.start || d.id === value.end,\n 'is-in-range': inRange(d.id),\n }\"\n @click=\"pick(d.id)\"\n >\n {{ d.day }}\n </button>\n </div>\n\n <div class=\"me-datepicker-options\">\n <button type=\"button\" class=\"me-menu-item\" @click=\"toggleEnd\" @mouseenter=\"submenu = null\">\n <span class=\"me-menu-title me-menu-text\">{{ m.endDate }}</span>\n <span class=\"me-switch\" :class=\"{ 'is-on': !!value.end }\" role=\"switch\" :aria-checked=\"!!value.end\" />\n </button>\n <div class=\"me-submenu-anchor\" @mouseenter=\"submenu = 'format'\">\n <button type=\"button\" class=\"me-menu-item\" :class=\"{ 'is-active': submenu === 'format' }\" @click=\"submenu = 'format'\">\n <span class=\"me-menu-title me-menu-text\">{{ m.dateFormat }}</span>\n <span class=\"me-menu-shortcut\">{{ formatLabel(value.format ?? 'relative') }}</span>\n <ChevronRight class=\"me-menu-chevron\" />\n </button>\n <div v-if=\"submenu === 'format'\" class=\"me-popover me-submenu\">\n <button v-for=\"f in DATE_FORMATS\" :key=\"f\" type=\"button\" class=\"me-menu-item\" @click=\"setFormat(f)\">\n <span class=\"me-menu-title me-menu-text\">{{ formatLabel(f) }}</span>\n <Check v-if=\"(value.format ?? 'relative') === f\" class=\"me-menu-check\" />\n </button>\n </div>\n </div>\n <button type=\"button\" class=\"me-menu-item\" @click=\"toggleTime\" @mouseenter=\"submenu = null\">\n <span class=\"me-menu-title me-menu-text\">{{ m.includeTime }}</span>\n <span class=\"me-switch\" :class=\"{ 'is-on': !!value.time }\" role=\"switch\" :aria-checked=\"!!value.time\" />\n </button>\n <div v-if=\"value.time\" class=\"me-submenu-anchor\" @mouseenter=\"submenu = 'timeFormat'\">\n <button type=\"button\" class=\"me-menu-item\" :class=\"{ 'is-active': submenu === 'timeFormat' }\" @click=\"submenu = 'timeFormat'\">\n <span class=\"me-menu-title me-menu-text\">{{ m.timeFormat }}</span>\n <span class=\"me-menu-shortcut\">{{ (value.timeFormat ?? '24') === '12' ? m.hour12 : m.hour24 }}</span>\n <ChevronRight class=\"me-menu-chevron\" />\n </button>\n <div v-if=\"submenu === 'timeFormat'\" class=\"me-popover me-submenu\">\n <button v-for=\"t in (['12', '24'] as const)\" :key=\"t\" type=\"button\" class=\"me-menu-item\" @click=\"setTimeFormat(t)\">\n <span class=\"me-menu-title me-menu-text\">{{ t === '12' ? m.hour12 : m.hour24 }}</span>\n <Check v-if=\"(value.timeFormat ?? '24') === t\" class=\"me-menu-check\" />\n </button>\n </div>\n </div>\n <div class=\"me-submenu-anchor\" @mouseenter=\"submenu = 'remind'\">\n <button type=\"button\" class=\"me-menu-item\" :class=\"{ 'is-active': submenu === 'remind' }\" @click=\"submenu = 'remind'\">\n <span class=\"me-menu-title me-menu-text\">{{ m.remind }}</span>\n <span class=\"me-menu-shortcut\">{{ m.reminders[value.remind ?? 'none'] ?? m.reminders.none }}</span>\n <ChevronRight class=\"me-menu-chevron\" />\n </button>\n <div v-if=\"submenu === 'remind'\" class=\"me-popover me-submenu\">\n <button v-for=\"r in reminders\" :key=\"r\" type=\"button\" class=\"me-menu-item\" @click=\"setRemind(r)\">\n <span class=\"me-menu-title me-menu-text\">{{ m.reminders[r] }}</span>\n <Check v-if=\"(value.remind ?? 'none') === r\" class=\"me-menu-check\" />\n </button>\n </div>\n </div>\n </div>\n\n <div class=\"me-datepicker-options\">\n <button type=\"button\" class=\"me-menu-item\" @click=\"emit('clear')\" @mouseenter=\"submenu = null\">\n <span class=\"me-menu-title me-menu-text\">{{ m.clear }}</span>\n </button>\n </div>\n <a v-if=\"helpUrl\" class=\"me-menu-item me-datepicker-help\" :href=\"helpUrl\" target=\"_blank\" rel=\"noopener noreferrer\">\n <CircleQuestionMark class=\"me-menu-chevron\" />\n <span class=\"me-menu-title me-menu-text\">{{ m.learnReminders }}</span>\n </a>\n </div>\n</template>\n","<script setup lang=\"ts\">\n/**\n * Notion-style date picker for date mentions: typed date/time inputs, month calendar,\n * end date (range), date & time formats, reminders, clear.\n */\nimport { Check, ChevronLeft, ChevronRight, CircleQuestionMark } from '@lucide/vue'\nimport { computed, ref, watch } from 'vue'\nimport {\n DATE_FORMATS, type DateFormat, type DateValue, formatDate, formatTime, isoDate, parseDateInput, parseIsoDate,\n parseTimeInput, REMINDERS_DATE, REMINDERS_TIME, type TimeFormat,\n} from '../date-utils'\nimport type { EditorMessages } from '../locale'\n\nconst props = defineProps<{\n value: DateValue\n locale: string\n messages: EditorMessages['datePicker']\n relative: { today: string, tomorrow: string, yesterday: string }\n helpUrl?: string | null\n}>()\nconst emit = defineEmits<{ change: [value: DateValue], clear: [] }>()\n\nconst m = computed(() => props.messages)\nconst v = computed(() => props.value)\nconst update = (patch: Partial<DateValue>) => emit('change', { ...props.value, ...patch })\n\n// --- Typed inputs -------------------------------------------------------------\n/** Which input the next calendar click fills (Notion alternates start → end). */\nconst editing = ref<'start' | 'end'>('start')\nconst inputFmt = (id: string | null | undefined) => (id ? formatDate(id, props.locale, 'short') : '')\nconst draft = ref({ start: '', end: '', time: '', endTime: '' })\nwatch(() => props.value, (val) => {\n draft.value = {\n start: inputFmt(val.start),\n end: inputFmt(val.end),\n time: val.time ? formatTime(val.time, props.locale, val.timeFormat ?? '24') : '',\n endTime: val.endTime ? formatTime(val.endTime, props.locale, val.timeFormat ?? '24') : '',\n }\n}, { immediate: true, deep: true })\n\nfunction commitDate(which: 'start' | 'end') {\n const parsed = parseDateInput(draft.value[which], props.locale)\n if (!parsed) {\n draft.value[which] = inputFmt(which === 'start' ? v.value.start : v.value.end)\n return\n }\n if (which === 'start') update({ start: parsed })\n else update({ end: parsed })\n view.value = monthOf(parsed)\n}\nfunction commitTime(which: 'time' | 'endTime') {\n const parsed = parseTimeInput(draft.value[which])\n if (parsed) update({ [which]: parsed })\n else draft.value[which] = v.value[which] ? formatTime(v.value[which]!, props.locale, v.value.timeFormat ?? '24') : ''\n}\n\n// --- Calendar -----------------------------------------------------------------\nconst monthOf = (id: string) => {\n const d = parseIsoDate(id) ?? new Date()\n return new Date(d.getFullYear(), d.getMonth(), 1)\n}\nconst view = ref(monthOf(props.value.start))\nconst today = isoDate(new Date())\n// \"Oct 2026\" / \"Tháng 11 2026\": month + year only, short enough for one line.\nconst monthLabel = computed(() => {\n // Chinese / Japanese / Korean read year first: \"2026年10月\".\n if (/^(zh|ja|ko)/.test(props.locale)) return new Intl.DateTimeFormat(props.locale, { year: 'numeric', month: 'long' }).format(view.value)\n const month = new Intl.DateTimeFormat(props.locale, { month: props.locale.startsWith('en') ? 'short' : 'long' }).format(view.value)\n return `${month.charAt(0).toUpperCase()}${month.slice(1)} ${view.value.getFullYear()}`\n})\n// Weeks start on Monday (like Notion's default).\nconst weekdays = computed(() => {\n const fmt = new Intl.DateTimeFormat(props.locale, { weekday: /^(vi|zh)/.test(props.locale) ? 'narrow' : 'short' })\n return Array.from({ length: 7 }, (_, i) => fmt.format(new Date(2023, 0, 2 + i)).slice(0, 2))\n})\nconst days = computed(() => {\n const first = view.value\n const offset = (first.getDay() + 6) % 7\n return Array.from({ length: 42 }, (_, i) => {\n const d = new Date(first.getFullYear(), first.getMonth(), 1 - offset + i)\n return { id: isoDate(d), day: d.getDate(), inMonth: d.getMonth() === first.getMonth() }\n })\n})\nconst inRange = (id: string) => !!v.value.end && id > v.value.start && id < v.value.end\n\nfunction pick(id: string) {\n if (!v.value.end || editing.value === 'start') {\n // With a range, keep start ≤ end.\n if (v.value.end && id > v.value.end) update({ start: id, end: id })\n else update({ start: id })\n if (v.value.end) editing.value = 'end'\n }\n else {\n if (id < v.value.start) update({ start: id, end: v.value.start })\n else update({ end: id })\n editing.value = 'start'\n }\n}\nfunction goToday() {\n view.value = monthOf(today)\n}\n\n// --- Options ------------------------------------------------------------------\nconst submenu = ref<'format' | 'timeFormat' | 'remind' | null>(null)\nconst reminders = computed(() => (v.value.time ? REMINDERS_TIME : REMINDERS_DATE))\nconst formatLabel = (f: DateFormat) => m.value.formats[f]\n\nfunction toggleEnd() {\n if (v.value.end) update({ end: null, endTime: null })\n else {\n update({ end: v.value.start, endTime: v.value.time ?? null })\n editing.value = 'end'\n }\n}\nfunction toggleTime() {\n // Date-only and timed reminders differ; reset an incompatible reminder.\n const remind = v.value.remind && v.value.remind !== 'none' ? null : v.value.remind\n if (v.value.time) update({ time: null, endTime: null, remind })\n else update({ time: '09:00', endTime: v.value.end ? '10:00' : null, remind })\n}\nfunction setFormat(format: DateFormat) {\n update({ format })\n submenu.value = null\n}\nfunction setTimeFormat(timeFormat: TimeFormat) {\n update({ timeFormat })\n submenu.value = null\n}\nfunction setRemind(remind: string) {\n update({ remind: remind === 'none' ? null : remind })\n submenu.value = null\n}\n</script>\n\n<template>\n <div class=\"me-datepicker\" @mouseleave=\"submenu = null\">\n <!-- Start and end side by side; stacked once times are shown too (like Notion). -->\n <div class=\"me-datepicker-inputs\" :class=\"{ 'is-split': !!value.end && !value.time }\">\n <div class=\"me-datepicker-field\" :class=\"{ 'is-active': editing === 'start' && !!value.end }\">\n <input v-model=\"draft.start\" class=\"me-datepicker-input\" @focus=\"editing = 'start'\" @keydown.enter.prevent=\"commitDate('start')\" @blur=\"commitDate('start')\">\n <input v-if=\"value.time\" v-model=\"draft.time\" class=\"me-datepicker-input me-datepicker-time\" @keydown.enter.prevent=\"commitTime('time')\" @blur=\"commitTime('time')\">\n </div>\n <div v-if=\"value.end\" class=\"me-datepicker-field\" :class=\"{ 'is-active': editing === 'end' }\">\n <input v-model=\"draft.end\" class=\"me-datepicker-input\" @focus=\"editing = 'end'\" @keydown.enter.prevent=\"commitDate('end')\" @blur=\"commitDate('end')\">\n <input v-if=\"value.time\" v-model=\"draft.endTime\" class=\"me-datepicker-input me-datepicker-time\" @keydown.enter.prevent=\"commitTime('endTime')\" @blur=\"commitTime('endTime')\">\n </div>\n </div>\n\n <div class=\"me-datepicker-head\">\n <span class=\"me-datepicker-month\">{{ monthLabel }}</span>\n <button type=\"button\" class=\"me-datepicker-today\" @click=\"goToday\">\n {{ relative.today }}\n </button>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.prevMonth\" @click=\"view = new Date(view.getFullYear(), view.getMonth() - 1, 1)\">\n <ChevronLeft />\n </button>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.nextMonth\" @click=\"view = new Date(view.getFullYear(), view.getMonth() + 1, 1)\">\n <ChevronRight />\n </button>\n </div>\n <div class=\"me-datepicker-grid\">\n <span v-for=\"(w, i) in weekdays\" :key=\"i\" class=\"me-datepicker-weekday\">{{ w }}</span>\n <button\n v-for=\"d in days\"\n :key=\"d.id\"\n type=\"button\"\n class=\"me-datepicker-day\"\n :class=\"{\n 'is-outside': !d.inMonth,\n 'is-today': d.id === today,\n 'is-selected': d.id === value.start || d.id === value.end,\n 'is-in-range': inRange(d.id),\n }\"\n @click=\"pick(d.id)\"\n >\n {{ d.day }}\n </button>\n </div>\n\n <div class=\"me-datepicker-options\">\n <button type=\"button\" class=\"me-menu-item\" @click=\"toggleEnd\" @mouseenter=\"submenu = null\">\n <span class=\"me-menu-title me-menu-text\">{{ m.endDate }}</span>\n <span class=\"me-switch\" :class=\"{ 'is-on': !!value.end }\" role=\"switch\" :aria-checked=\"!!value.end\" />\n </button>\n <div class=\"me-submenu-anchor\" @mouseenter=\"submenu = 'format'\">\n <button type=\"button\" class=\"me-menu-item\" :class=\"{ 'is-active': submenu === 'format' }\" @click=\"submenu = 'format'\">\n <span class=\"me-menu-title me-menu-text\">{{ m.dateFormat }}</span>\n <span class=\"me-menu-shortcut\">{{ formatLabel(value.format ?? 'relative') }}</span>\n <ChevronRight class=\"me-menu-chevron\" />\n </button>\n <div v-if=\"submenu === 'format'\" class=\"me-popover me-submenu\">\n <button v-for=\"f in DATE_FORMATS\" :key=\"f\" type=\"button\" class=\"me-menu-item\" @click=\"setFormat(f)\">\n <span class=\"me-menu-title me-menu-text\">{{ formatLabel(f) }}</span>\n <Check v-if=\"(value.format ?? 'relative') === f\" class=\"me-menu-check\" />\n </button>\n </div>\n </div>\n <button type=\"button\" class=\"me-menu-item\" @click=\"toggleTime\" @mouseenter=\"submenu = null\">\n <span class=\"me-menu-title me-menu-text\">{{ m.includeTime }}</span>\n <span class=\"me-switch\" :class=\"{ 'is-on': !!value.time }\" role=\"switch\" :aria-checked=\"!!value.time\" />\n </button>\n <div v-if=\"value.time\" class=\"me-submenu-anchor\" @mouseenter=\"submenu = 'timeFormat'\">\n <button type=\"button\" class=\"me-menu-item\" :class=\"{ 'is-active': submenu === 'timeFormat' }\" @click=\"submenu = 'timeFormat'\">\n <span class=\"me-menu-title me-menu-text\">{{ m.timeFormat }}</span>\n <span class=\"me-menu-shortcut\">{{ (value.timeFormat ?? '24') === '12' ? m.hour12 : m.hour24 }}</span>\n <ChevronRight class=\"me-menu-chevron\" />\n </button>\n <div v-if=\"submenu === 'timeFormat'\" class=\"me-popover me-submenu\">\n <button v-for=\"t in (['12', '24'] as const)\" :key=\"t\" type=\"button\" class=\"me-menu-item\" @click=\"setTimeFormat(t)\">\n <span class=\"me-menu-title me-menu-text\">{{ t === '12' ? m.hour12 : m.hour24 }}</span>\n <Check v-if=\"(value.timeFormat ?? '24') === t\" class=\"me-menu-check\" />\n </button>\n </div>\n </div>\n <div class=\"me-submenu-anchor\" @mouseenter=\"submenu = 'remind'\">\n <button type=\"button\" class=\"me-menu-item\" :class=\"{ 'is-active': submenu === 'remind' }\" @click=\"submenu = 'remind'\">\n <span class=\"me-menu-title me-menu-text\">{{ m.remind }}</span>\n <span class=\"me-menu-shortcut\">{{ m.reminders[value.remind ?? 'none'] ?? m.reminders.none }}</span>\n <ChevronRight class=\"me-menu-chevron\" />\n </button>\n <div v-if=\"submenu === 'remind'\" class=\"me-popover me-submenu\">\n <button v-for=\"r in reminders\" :key=\"r\" type=\"button\" class=\"me-menu-item\" @click=\"setRemind(r)\">\n <span class=\"me-menu-title me-menu-text\">{{ m.reminders[r] }}</span>\n <Check v-if=\"(value.remind ?? 'none') === r\" class=\"me-menu-check\" />\n </button>\n </div>\n </div>\n </div>\n\n <div class=\"me-datepicker-options\">\n <button type=\"button\" class=\"me-menu-item\" @click=\"emit('clear')\" @mouseenter=\"submenu = null\">\n <span class=\"me-menu-title me-menu-text\">{{ m.clear }}</span>\n </button>\n </div>\n <a v-if=\"helpUrl\" class=\"me-menu-item me-datepicker-help\" :href=\"helpUrl\" target=\"_blank\" rel=\"noopener noreferrer\">\n <CircleQuestionMark class=\"me-menu-chevron\" />\n <span class=\"me-menu-title me-menu-text\">{{ m.learnReminders }}</span>\n </a>\n </div>\n</template>\n","<script setup lang=\"ts\">\n/**\n * @mention chip. Click (when editable):\n * - date → calendar to change the date\n * - person/page → searchable list to switch to someone/something else\n * Read-only: calls the block's `onClick`, or opens a page's link.\n */\nimport { NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport { autoUpdate, computePosition, flip, offset, shift } from '@floating-ui/dom'\nimport { Calendar, ExternalLink, FileText, User } from '@lucide/vue'\nimport { computed, nextTick, onBeforeUnmount, onMounted, ref, shallowRef, watch } from 'vue'\nimport DatePicker from '../components/DatePicker.vue'\nimport { useScope } from '../composables/useScope'\nimport { type DateValue, formatDateValue, reminderTime } from '../date-utils'\nimport type { MentionItem, MentionOptions } from '../extensions/mention'\nimport { readTokenPx } from '../theme/read'\nimport { safeUrl } from '../safe-url'\n\nconst props = defineProps(nodeViewProps)\n\nconst scope = useScope(() => props.editor)\nconst config = computed(() => props.editor.storage.meiConfig)\nconst m = computed(() => config.value.messages.mention)\nconst options = computed(() => props.extension.options as MentionOptions)\nconst kind = computed(() => (props.node.attrs.kind ?? 'user') as MentionItem['kind'])\n\n/** A date mention's value, from its attributes (id = start date). */\nconst dateValue = computed<DateValue>(() => {\n const a = props.node.attrs\n return { start: a.id, end: a.end, time: a.time, endTime: a.endTime, format: a.format ?? 'relative', timeFormat: a.timeFormat, remind: a.remind }\n})\n/** Dates render from the stored value, so relative labels and locale stay current. */\nconst label = computed(() => (kind.value === 'date'\n ? formatDateValue(dateValue.value, config.value.locale, m.value)\n : props.node.attrs.label ?? props.node.attrs.id))\n\n// --- Popover ------------------------------------------------------------------\nconst open = ref(false)\nconst chip = ref<HTMLElement | null>(null)\nconst panel = ref<HTMLElement | null>(null)\nlet cleanup: (() => void) | null = null\n\n// Close on clicks outside the popover — but not on the chip itself (it toggles).\nfunction onDocPointer(e: PointerEvent) {\n if (!open.value) return\n const t = e.target as Node\n if (panel.value?.contains(t) || chip.value?.contains(t)) return\n close()\n}\nonMounted(() => document.addEventListener('pointerdown', onDocPointer, true))\n\nfunction position() {\n const el = panel.value\n const ref = chip.value\n if (!el || !ref) return\n const gap = readTokenPx(props.editor.view.dom, 'popover.offset')\n cleanup?.()\n cleanup = autoUpdate(ref, el, () => {\n computePosition(ref, el, { placement: 'bottom-start', strategy: 'fixed', middleware: [offset(gap), flip({ padding: gap }), shift({ padding: gap })] })\n .then(({ x, y }) => Object.assign(el.style, { left: `${x}px`, top: `${y}px` }))\n })\n}\n\n/** Link and avatar from the document, only if safe (never `javascript:`). */\nconst href = computed(() => safeUrl(props.node.attrs.href))\nconst avatar = computed(() => safeUrl(props.node.attrs.avatar, 'image'))\n\nfunction onClick(e: MouseEvent) {\n if (!props.editor.isEditable) {\n const item = props.node.attrs as MentionItem\n if (options.value.onClick) options.value.onClick(item)\n else if (href.value) window.open(href.value, '_blank', 'noopener')\n return\n }\n e.preventDefault()\n if (open.value) return close()\n open.value = true\n query.value = ''\n nextTick(() => {\n position()\n searchInput.value?.focus()\n })\n}\n\nfunction close() {\n open.value = false\n cleanup?.()\n cleanup = null\n}\n\nfunction apply(attrs: Record<string, unknown>) {\n props.updateAttributes(attrs)\n close()\n props.editor.commands.focus()\n}\n\n// --- Date ---------------------------------------------------------------------\n/** Saves changes right away and keeps the picker open (like Notion). */\nfunction changeDate(next: DateValue) {\n const before = dateValue.value.remind ?? null\n props.updateAttributes({\n id: next.start,\n end: next.end ?? null,\n time: next.time ?? null,\n endTime: next.endTime ?? null,\n format: next.format ?? 'relative',\n timeFormat: next.timeFormat ?? null,\n remind: next.remind ?? null,\n // Plain-text label (copy/export): absolute, so it doesn't go stale.\n label: formatDateValue({ ...next, format: next.format === 'relative' ? 'short' : next.format }, config.value.locale),\n })\n if ((next.remind ?? null) !== before || (next.remind && (next.start !== dateValue.value.start || next.time !== dateValue.value.time))) {\n const fireAt = reminderTime(next)\n options.value.onRemind?.(fireAt && next.remind ? { date: next.start, time: next.time ?? null, remind: next.remind, fireAt } : null, next)\n }\n}\nfunction clearDate() {\n close()\n props.deleteNode()\n props.editor.commands.focus()\n}\n\n// --- People / pages -------------------------------------------------------------\nconst query = ref('')\nconst results = shallowRef<MentionItem[]>([])\nconst active = ref(0)\nconst searchInput = ref<HTMLInputElement | null>(null)\nlet searchToken = 0\n\nwatch([query, open], async () => {\n if (!open.value || kind.value === 'date') return\n const token = ++searchToken\n const found = options.value.search ? await options.value.search(query.value) : []\n if (token !== searchToken) return\n results.value = found.filter(r => r.kind !== 'date')\n active.value = 0\n})\n\nfunction pickItem(item: MentionItem) {\n apply({ id: item.id, label: item.label, kind: item.kind, href: item.href ?? null, avatar: item.avatar ?? null })\n}\n\nfunction onKeydown(e: KeyboardEvent) {\n e.stopPropagation()\n const n = results.value.length\n if (e.key === 'Escape') {\n close()\n props.editor.commands.focus()\n }\n else if (n && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {\n e.preventDefault()\n active.value = (active.value + (e.key === 'ArrowDown' ? 1 : n - 1)) % n\n }\n else if (e.key === 'Enter' && results.value[active.value]) {\n e.preventDefault()\n pickItem(results.value[active.value]!)\n }\n}\n\nconst ICONS = { user: User, page: FileText, date: Calendar }\nonBeforeUnmount(() => {\n cleanup?.()\n document.removeEventListener('pointerdown', onDocPointer, true)\n})\n</script>\n\n<template>\n <NodeViewWrapper as=\"span\" class=\"me-mention-wrap\">\n <span\n ref=\"chip\"\n class=\"me-mention\"\n :class=\"[`me-mention--${kind}`, { 'is-selected': selected, 'is-open': open }]\"\n :data-kind=\"kind\"\n @click=\"onClick\"\n >\n <img v-if=\"kind === 'user' && avatar\" class=\"me-mention-avatar\" :src=\"avatar\" alt=\"\">\n <FileText v-else-if=\"kind === 'page'\" class=\"me-mention-icon\" />\n <span>{{ kind === 'page' ? '' : '@' }}{{ label }}</span>\n </span>\n\n <Teleport to=\"body\">\n <div\n v-if=\"open\"\n ref=\"panel\"\n v-bind=\"scope\"\n class=\"me-popover me-mention-popover\"\n :class=\"{ 'me-mention-popover--date': kind === 'date' }\"\n contenteditable=\"false\"\n @mousedown.stop\n @keydown=\"onKeydown\"\n >\n <DatePicker\n v-if=\"kind === 'date'\"\n :value=\"dateValue\"\n :locale=\"config.locale\"\n :messages=\"config.messages.datePicker\"\n :relative=\"m\"\n :help-url=\"options.reminderHelpUrl\"\n @change=\"changeDate\"\n @clear=\"clearDate\"\n />\n <template v-else>\n <input ref=\"searchInput\" v-model=\"query\" class=\"me-input me-mention-search\" :placeholder=\"m.searchPlaceholder\">\n <div class=\"me-mention-results\">\n <button\n v-for=\"(item, i) in results\"\n :key=\"`${item.kind}-${item.id}`\"\n type=\"button\"\n class=\"me-menu-item\"\n :class=\"{ 'is-active': i === active, 'is-current': item.id === node.attrs.id }\"\n @mouseenter=\"active = i\"\n @click=\"pickItem(item)\"\n >\n <img v-if=\"safeUrl(item.avatar, 'image')\" class=\"me-menu-icon me-avatar\" :src=\"safeUrl(item.avatar, 'image')!\" alt=\"\">\n <span v-else class=\"me-menu-icon\"><component :is=\"ICONS[item.kind]\" /></span>\n <span class=\"me-menu-text\">\n <span class=\"me-menu-title\">{{ item.label }}</span>\n <span v-if=\"item.description\" class=\"me-menu-desc\">{{ item.description }}</span>\n </span>\n </button>\n <div v-if=\"!results.length\" class=\"me-menu-empty\">\n {{ options.search ? m.empty : m.noSearch }}\n </div>\n </div>\n <a v-if=\"kind === 'page' && href\" class=\"me-menu-item me-mention-open\" :href=\"href\" target=\"_blank\" rel=\"noopener noreferrer\">\n <span class=\"me-menu-icon\"><ExternalLink /></span>\n <span class=\"me-menu-title me-menu-text\">{{ m.openPage }}</span>\n </a>\n </template>\n </div>\n </Teleport>\n </NodeViewWrapper>\n</template>\n","<script setup lang=\"ts\">\n/**\n * @mention chip. Click (when editable):\n * - date → calendar to change the date\n * - person/page → searchable list to switch to someone/something else\n * Read-only: calls the block's `onClick`, or opens a page's link.\n */\nimport { NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport { autoUpdate, computePosition, flip, offset, shift } from '@floating-ui/dom'\nimport { Calendar, ExternalLink, FileText, User } from '@lucide/vue'\nimport { computed, nextTick, onBeforeUnmount, onMounted, ref, shallowRef, watch } from 'vue'\nimport DatePicker from '../components/DatePicker.vue'\nimport { useScope } from '../composables/useScope'\nimport { type DateValue, formatDateValue, reminderTime } from '../date-utils'\nimport type { MentionItem, MentionOptions } from '../extensions/mention'\nimport { readTokenPx } from '../theme/read'\nimport { safeUrl } from '../safe-url'\n\nconst props = defineProps(nodeViewProps)\n\nconst scope = useScope(() => props.editor)\nconst config = computed(() => props.editor.storage.meiConfig)\nconst m = computed(() => config.value.messages.mention)\nconst options = computed(() => props.extension.options as MentionOptions)\nconst kind = computed(() => (props.node.attrs.kind ?? 'user') as MentionItem['kind'])\n\n/** A date mention's value, from its attributes (id = start date). */\nconst dateValue = computed<DateValue>(() => {\n const a = props.node.attrs\n return { start: a.id, end: a.end, time: a.time, endTime: a.endTime, format: a.format ?? 'relative', timeFormat: a.timeFormat, remind: a.remind }\n})\n/** Dates render from the stored value, so relative labels and locale stay current. */\nconst label = computed(() => (kind.value === 'date'\n ? formatDateValue(dateValue.value, config.value.locale, m.value)\n : props.node.attrs.label ?? props.node.attrs.id))\n\n// --- Popover ------------------------------------------------------------------\nconst open = ref(false)\nconst chip = ref<HTMLElement | null>(null)\nconst panel = ref<HTMLElement | null>(null)\nlet cleanup: (() => void) | null = null\n\n// Close on clicks outside the popover — but not on the chip itself (it toggles).\nfunction onDocPointer(e: PointerEvent) {\n if (!open.value) return\n const t = e.target as Node\n if (panel.value?.contains(t) || chip.value?.contains(t)) return\n close()\n}\nonMounted(() => document.addEventListener('pointerdown', onDocPointer, true))\n\nfunction position() {\n const el = panel.value\n const ref = chip.value\n if (!el || !ref) return\n const gap = readTokenPx(props.editor.view.dom, 'popover.offset')\n cleanup?.()\n cleanup = autoUpdate(ref, el, () => {\n computePosition(ref, el, { placement: 'bottom-start', strategy: 'fixed', middleware: [offset(gap), flip({ padding: gap }), shift({ padding: gap })] })\n .then(({ x, y }) => Object.assign(el.style, { left: `${x}px`, top: `${y}px` }))\n })\n}\n\n/** Link and avatar from the document, only if safe (never `javascript:`). */\nconst href = computed(() => safeUrl(props.node.attrs.href))\nconst avatar = computed(() => safeUrl(props.node.attrs.avatar, 'image'))\n\nfunction onClick(e: MouseEvent) {\n if (!props.editor.isEditable) {\n const item = props.node.attrs as MentionItem\n if (options.value.onClick) options.value.onClick(item)\n else if (href.value) window.open(href.value, '_blank', 'noopener')\n return\n }\n e.preventDefault()\n if (open.value) return close()\n open.value = true\n query.value = ''\n nextTick(() => {\n position()\n searchInput.value?.focus()\n })\n}\n\nfunction close() {\n open.value = false\n cleanup?.()\n cleanup = null\n}\n\nfunction apply(attrs: Record<string, unknown>) {\n props.updateAttributes(attrs)\n close()\n props.editor.commands.focus()\n}\n\n// --- Date ---------------------------------------------------------------------\n/** Saves changes right away and keeps the picker open (like Notion). */\nfunction changeDate(next: DateValue) {\n const before = dateValue.value.remind ?? null\n props.updateAttributes({\n id: next.start,\n end: next.end ?? null,\n time: next.time ?? null,\n endTime: next.endTime ?? null,\n format: next.format ?? 'relative',\n timeFormat: next.timeFormat ?? null,\n remind: next.remind ?? null,\n // Plain-text label (copy/export): absolute, so it doesn't go stale.\n label: formatDateValue({ ...next, format: next.format === 'relative' ? 'short' : next.format }, config.value.locale),\n })\n if ((next.remind ?? null) !== before || (next.remind && (next.start !== dateValue.value.start || next.time !== dateValue.value.time))) {\n const fireAt = reminderTime(next)\n options.value.onRemind?.(fireAt && next.remind ? { date: next.start, time: next.time ?? null, remind: next.remind, fireAt } : null, next)\n }\n}\nfunction clearDate() {\n close()\n props.deleteNode()\n props.editor.commands.focus()\n}\n\n// --- People / pages -------------------------------------------------------------\nconst query = ref('')\nconst results = shallowRef<MentionItem[]>([])\nconst active = ref(0)\nconst searchInput = ref<HTMLInputElement | null>(null)\nlet searchToken = 0\n\nwatch([query, open], async () => {\n if (!open.value || kind.value === 'date') return\n const token = ++searchToken\n const found = options.value.search ? await options.value.search(query.value) : []\n if (token !== searchToken) return\n results.value = found.filter(r => r.kind !== 'date')\n active.value = 0\n})\n\nfunction pickItem(item: MentionItem) {\n apply({ id: item.id, label: item.label, kind: item.kind, href: item.href ?? null, avatar: item.avatar ?? null })\n}\n\nfunction onKeydown(e: KeyboardEvent) {\n e.stopPropagation()\n const n = results.value.length\n if (e.key === 'Escape') {\n close()\n props.editor.commands.focus()\n }\n else if (n && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {\n e.preventDefault()\n active.value = (active.value + (e.key === 'ArrowDown' ? 1 : n - 1)) % n\n }\n else if (e.key === 'Enter' && results.value[active.value]) {\n e.preventDefault()\n pickItem(results.value[active.value]!)\n }\n}\n\nconst ICONS = { user: User, page: FileText, date: Calendar }\nonBeforeUnmount(() => {\n cleanup?.()\n document.removeEventListener('pointerdown', onDocPointer, true)\n})\n</script>\n\n<template>\n <NodeViewWrapper as=\"span\" class=\"me-mention-wrap\">\n <span\n ref=\"chip\"\n class=\"me-mention\"\n :class=\"[`me-mention--${kind}`, { 'is-selected': selected, 'is-open': open }]\"\n :data-kind=\"kind\"\n @click=\"onClick\"\n >\n <img v-if=\"kind === 'user' && avatar\" class=\"me-mention-avatar\" :src=\"avatar\" alt=\"\">\n <FileText v-else-if=\"kind === 'page'\" class=\"me-mention-icon\" />\n <span>{{ kind === 'page' ? '' : '@' }}{{ label }}</span>\n </span>\n\n <Teleport to=\"body\">\n <div\n v-if=\"open\"\n ref=\"panel\"\n v-bind=\"scope\"\n class=\"me-popover me-mention-popover\"\n :class=\"{ 'me-mention-popover--date': kind === 'date' }\"\n contenteditable=\"false\"\n @mousedown.stop\n @keydown=\"onKeydown\"\n >\n <DatePicker\n v-if=\"kind === 'date'\"\n :value=\"dateValue\"\n :locale=\"config.locale\"\n :messages=\"config.messages.datePicker\"\n :relative=\"m\"\n :help-url=\"options.reminderHelpUrl\"\n @change=\"changeDate\"\n @clear=\"clearDate\"\n />\n <template v-else>\n <input ref=\"searchInput\" v-model=\"query\" class=\"me-input me-mention-search\" :placeholder=\"m.searchPlaceholder\">\n <div class=\"me-mention-results\">\n <button\n v-for=\"(item, i) in results\"\n :key=\"`${item.kind}-${item.id}`\"\n type=\"button\"\n class=\"me-menu-item\"\n :class=\"{ 'is-active': i === active, 'is-current': item.id === node.attrs.id }\"\n @mouseenter=\"active = i\"\n @click=\"pickItem(item)\"\n >\n <img v-if=\"safeUrl(item.avatar, 'image')\" class=\"me-menu-icon me-avatar\" :src=\"safeUrl(item.avatar, 'image')!\" alt=\"\">\n <span v-else class=\"me-menu-icon\"><component :is=\"ICONS[item.kind]\" /></span>\n <span class=\"me-menu-text\">\n <span class=\"me-menu-title\">{{ item.label }}</span>\n <span v-if=\"item.description\" class=\"me-menu-desc\">{{ item.description }}</span>\n </span>\n </button>\n <div v-if=\"!results.length\" class=\"me-menu-empty\">\n {{ options.search ? m.empty : m.noSearch }}\n </div>\n </div>\n <a v-if=\"kind === 'page' && href\" class=\"me-menu-item me-mention-open\" :href=\"href\" target=\"_blank\" rel=\"noopener noreferrer\">\n <span class=\"me-menu-icon\"><ExternalLink /></span>\n <span class=\"me-menu-title me-menu-text\">{{ m.openPage }}</span>\n </a>\n </template>\n </div>\n </Teleport>\n </NodeViewWrapper>\n</template>\n","import Mention from '@tiptap/extension-mention'\nimport { type JSONContent, mergeAttributes } from '@tiptap/core'\nimport { PluginKey } from '@tiptap/pm/state'\nimport type { SuggestionOptions } from '@tiptap/suggestion'\nimport MentionMenu from '../components/MentionMenu.vue'\nimport { blockNodeView } from '../nodeviews/renderer'\nimport MentionView from '../nodeviews/MentionView.vue'\nimport { type DateValue, isoDate, reminderTime } from '../date-utils'\n\nexport { formatDateValue, formatMentionDate, isoDate, parseIsoDate, reminderTime, type DateFormat, type DateValue, type TimeFormat } from '../date-utils'\nimport { suggestionRenderer } from './suggestion-renderer'\nimport { safeUrl } from '../safe-url'\n\nexport type MentionKind = 'user' | 'page' | 'date'\n\nexport interface MentionItem {\n id: string\n label: string\n kind: MentionKind\n /** Avatar image URL (users) — optional. */\n avatar?: string\n /** Link for pages — opened on ⌘/Ctrl+click when no `onClick` is given. */\n href?: string\n /** Secondary text in the menu (email, path…). */\n description?: string\n}\n\nexport interface MentionReminder {\n /** Start date of the mention (`YYYY-MM-DD`). */\n date: string\n time: string | null\n /** Preset, e.g. `'1d'`, `'30m'`. */\n remind: string\n /** When to notify. */\n fireAt: Date\n}\n\nexport interface MentionOptions {\n /** Finds people/pages for `@query`. Dates (today, tomorrow…) are built in. */\n search: ((query: string) => MentionItem[] | Promise<MentionItem[]>) | null\n /** Called when a mention is clicked (read-only editors). */\n onClick: ((item: MentionItem) => void) | null\n /**\n * Called when a date mention's reminder is set or cleared. The editor can't send\n * notifications itself — schedule them on your backend (see `getMentionReminders`).\n */\n onRemind: ((reminder: MentionReminder | null, value: DateValue) => void) | null\n /** \"Learn about reminders\" link in the date picker (hidden when not set). */\n reminderHelpUrl: string | null\n}\n\n/** All reminders in a document, for scheduling notifications server-side. */\nexport function getMentionReminders(doc: JSONContent): MentionReminder[] {\n const out: MentionReminder[] = []\n const visit = (node: JSONContent) => {\n const a = node.attrs ?? {}\n if (node.type === 'mention' && a.kind === 'date' && a.remind && a.remind !== 'none') {\n const fireAt = reminderTime({ start: a.id, time: a.time, remind: a.remind })\n if (fireAt) out.push({ date: a.id, time: a.time ?? null, remind: a.remind, fireAt })\n }\n node.content?.forEach(visit)\n }\n visit(doc)\n return out\n}\n\nexport const mentionPluginKey = new PluginKey('mention')\n\nconst iso = isoDate\n\n/** Date suggestions: today/tomorrow/yesterday, plus a typed date like 25/12 or 2026-12-25. */\nfunction dateItems(query: string, labels: { today: string, tomorrow: string, yesterday: string }, locale: string): MentionItem[] {\n const day = (offset: number) => {\n const d = new Date()\n d.setDate(d.getDate() + offset)\n return d\n }\n const fmt = new Intl.DateTimeFormat(locale, { day: 'numeric', month: 'short', year: 'numeric' })\n const make = (d: Date, label: string): MentionItem => ({ id: iso(d), kind: 'date', label, description: fmt.format(d) })\n const items = [make(day(0), labels.today), make(day(1), labels.tomorrow), make(day(-1), labels.yesterday)]\n\n const typed = query.match(/^(\\d{1,2})[/.-](\\d{1,2})(?:[/.-](\\d{2,4}))?$/) ?? query.match(/^(\\d{4})-(\\d{1,2})-(\\d{1,2})$/)\n if (typed) {\n const [, a, b, c] = typed\n const d = query.includes('-') && a!.length === 4\n ? new Date(Number(a), Number(b) - 1, Number(c))\n : new Date(c ? Number(c.length === 2 ? `20${c}` : c) : new Date().getFullYear(), Number(b) - 1, Number(a))\n if (!Number.isNaN(d.getTime())) items.unshift(make(d, fmt.format(d)))\n }\n const norm = (t: string) => t.normalize('NFD').replace(/[\\u0300-\\u036F]/g, '').replace(/đ/g, 'd').toLowerCase()\n const q = norm(query)\n return typed ? items : items.filter(i => !q || norm(i.label).includes(q) || i.id.includes(q))\n}\n\n/** `@` mentions of people, pages and dates. */\nexport const MentionNode = Mention.extend<MentionOptions & Record<string, any>>({\n addOptions() {\n return { ...this.parent?.(), search: null, onClick: null, onRemind: null, reminderHelpUrl: null }\n },\n\n addAttributes() {\n // `key` is the attribute name in JSON, `data` its `data-*` name in HTML.\n const attr = (key: string, data = key) => ({\n default: null,\n parseHTML: (el: HTMLElement) => el.getAttribute(`data-${data}`),\n renderHTML: (attrs: Record<string, any>) => (attrs[key] ? { [`data-${data}`]: attrs[key] } : {}),\n })\n return {\n ...this.parent?.(),\n kind: attr('kind'),\n // Pasted HTML can carry any data-href / data-avatar: only web, blob and relative URLs.\n href: { ...attr('href'), parseHTML: (el: HTMLElement) => safeUrl(el.getAttribute('data-href')) },\n avatar: { ...attr('avatar'), parseHTML: (el: HTMLElement) => safeUrl(el.getAttribute('data-avatar'), 'image') },\n // Date mentions (id = start date): see DateValue.\n end: attr('end'),\n time: attr('time'),\n endTime: attr('endTime', 'end-time'),\n format: attr('format'),\n timeFormat: attr('timeFormat', 'time-format'),\n remind: attr('remind'),\n }\n },\n\n renderHTML({ node, HTMLAttributes }) {\n const prefix = node.attrs.kind === 'page' ? '' : '@'\n return ['span', mergeAttributes({ 'data-type': 'mention', 'class': `me-mention me-mention--${node.attrs.kind ?? 'user'}` }, HTMLAttributes), `${prefix}${node.attrs.label ?? node.attrs.id}`]\n },\n\n renderText({ node }) {\n return `${node.attrs.kind === 'page' ? '' : '@'}${node.attrs.label ?? node.attrs.id}`\n },\n\n // Clickable chip: date picker for dates, people/page picker otherwise (read-only: onClick/href).\n addNodeView() {\n return blockNodeView(MentionView)\n },\n}).configure({ suggestion: mentionSuggestion() })\n\nfunction mentionSuggestion(): Omit<SuggestionOptions<MentionItem>, 'editor'> {\n return {\n char: '@',\n pluginKey: mentionPluginKey,\n allowSpaces: true,\n items: async ({ query, editor }) => {\n const ext = editor.extensionManager.extensions.find(e => e.name === 'mention')\n const search = ext?.options.search as MentionOptions['search']\n const { messages, locale } = editor.storage.meiConfig\n const people = search ? await search(query) : []\n return [...people, ...dateItems(query, messages.mention, locale)].slice(0, 12)\n },\n command: ({ editor, range, props: item }) => {\n editor.chain().focus().insertContentAt(range, [\n // Dates show the actual date, not \"Today\", which would be wrong tomorrow.\n { type: 'mention', attrs: { id: item.id, label: item.kind === 'date' ? item.description : item.label, kind: item.kind, href: item.href ?? null, avatar: item.avatar ?? null } },\n { type: 'text', text: ' ' },\n ]).run()\n },\n render: suggestionRenderer<MentionItem>(MentionMenu, mentionPluginKey, {\n // Close once the query clearly isn't a name anymore.\n onUpdate: props => (props.query.split(' ').length > 3 ? false : undefined),\n }),\n }\n}\n","import { Extension } from '@tiptap/core'\n\n/** Marker: when loaded, code blocks in the `mermaid` language show a live diagram. */\nexport const MermaidPreview = Extension.create({ name: 'mermaidPreview' })\n\nexport const SAMPLE_MERMAID = 'flowchart LR\\n A[Ý tưởng] --> B{Duyệt?}\\n B -- Có --> C[Làm]\\n B -- Không --> A'\n","<script setup lang=\"ts\">\nimport { NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport { TextSelection } from '@tiptap/pm/state'\nimport { computed, onBeforeUnmount, shallowRef } from 'vue'\n\nconst props = defineProps(nodeViewProps)\nconst m = computed(() => props.editor.storage.meiConfig.messages.toc)\n\ninterface Entry { pos: number, level: number, text: string }\nconst entries = shallowRef<Entry[]>([])\n\nfunction collect() {\n const list: Entry[] = []\n props.editor.state.doc.descendants((node, pos) => {\n if (node.type.name === 'heading') list.push({ pos, level: node.attrs.level, text: node.textContent })\n else if (node.type.name === 'details' && node.attrs.level) list.push({ pos, level: node.attrs.level, text: node.firstChild?.textContent ?? '' })\n return node.type.name !== 'heading'\n })\n entries.value = list\n}\ncollect()\nprops.editor.on('update', collect)\nonBeforeUnmount(() => props.editor.off('update', collect))\n\nconst minLevel = computed(() => Math.min(...entries.value.map(e => e.level), 4))\n\nfunction go(entry: Entry) {\n const { view } = props.editor\n ;(view.nodeDOM(entry.pos) as HTMLElement | null)?.scrollIntoView({ behavior: 'smooth', block: 'start' })\n view.dispatch(view.state.tr.setSelection(TextSelection.near(view.state.doc.resolve(entry.pos + 1))))\n view.focus()\n}\n</script>\n\n<template>\n <NodeViewWrapper class=\"me-toc\" :class=\"{ 'is-selected': selected }\" contenteditable=\"false\">\n <button\n v-for=\"e in entries\"\n :key=\"e.pos\"\n type=\"button\"\n class=\"me-toc-item\"\n :data-depth=\"e.level - minLevel\"\n @click=\"go(e)\"\n >\n {{ e.text || m.untitled }}\n </button>\n <p v-if=\"!entries.length\" class=\"me-hint\">\n {{ m.empty }}\n </p>\n </NodeViewWrapper>\n</template>\n","<script setup lang=\"ts\">\nimport { NodeViewWrapper, nodeViewProps } from '@tiptap/vue-3'\nimport { TextSelection } from '@tiptap/pm/state'\nimport { computed, onBeforeUnmount, shallowRef } from 'vue'\n\nconst props = defineProps(nodeViewProps)\nconst m = computed(() => props.editor.storage.meiConfig.messages.toc)\n\ninterface Entry { pos: number, level: number, text: string }\nconst entries = shallowRef<Entry[]>([])\n\nfunction collect() {\n const list: Entry[] = []\n props.editor.state.doc.descendants((node, pos) => {\n if (node.type.name === 'heading') list.push({ pos, level: node.attrs.level, text: node.textContent })\n else if (node.type.name === 'details' && node.attrs.level) list.push({ pos, level: node.attrs.level, text: node.firstChild?.textContent ?? '' })\n return node.type.name !== 'heading'\n })\n entries.value = list\n}\ncollect()\nprops.editor.on('update', collect)\nonBeforeUnmount(() => props.editor.off('update', collect))\n\nconst minLevel = computed(() => Math.min(...entries.value.map(e => e.level), 4))\n\nfunction go(entry: Entry) {\n const { view } = props.editor\n ;(view.nodeDOM(entry.pos) as HTMLElement | null)?.scrollIntoView({ behavior: 'smooth', block: 'start' })\n view.dispatch(view.state.tr.setSelection(TextSelection.near(view.state.doc.resolve(entry.pos + 1))))\n view.focus()\n}\n</script>\n\n<template>\n <NodeViewWrapper class=\"me-toc\" :class=\"{ 'is-selected': selected }\" contenteditable=\"false\">\n <button\n v-for=\"e in entries\"\n :key=\"e.pos\"\n type=\"button\"\n class=\"me-toc-item\"\n :data-depth=\"e.level - minLevel\"\n @click=\"go(e)\"\n >\n {{ e.text || m.untitled }}\n </button>\n <p v-if=\"!entries.length\" class=\"me-hint\">\n {{ m.empty }}\n </p>\n </NodeViewWrapper>\n</template>\n","import { Node } from '@tiptap/core'\nimport { blockNodeView } from '../nodeviews/renderer'\nimport TocView from '../nodeviews/TocView.vue'\n\ndeclare module '@tiptap/core' {\n interface Commands<ReturnType> {\n tableOfContents: { insertTableOfContents: () => ReturnType }\n }\n}\n\n/** Table of contents built live from the document's headings and toggle headings. */\nexport const TableOfContents = Node.create({\n name: 'tableOfContents',\n group: 'block',\n atom: true,\n draggable: true,\n parseHTML: () => [{ tag: 'div[data-type=\"table-of-contents\"]' }],\n renderHTML: ({ HTMLAttributes }) => ['div', { ...HTMLAttributes, 'data-type': 'table-of-contents' }],\n addCommands() {\n return { insertTableOfContents: () => ({ commands }) => commands.insertContent({ type: this.name }) }\n },\n addNodeView: () => blockNodeView(TocView),\n})\n","import { AudioLines, AtSign, CodeXml, File, Film, Radical, Sigma, TableOfContents, Workflow } from '@lucide/vue'\nimport { type BlockType, isNode } from '../block-items'\nimport { defineBlock } from '../define-block'\nimport { CodeBlock } from '../extensions/code-block'\nimport { EmojiSuggestion } from '../extensions/emoji'\nimport { FileBlock, type FileBlockOptions, type FileKind } from '../extensions/file-block'\nimport { HtmlBlock, type HtmlBlockOptions } from '../extensions/html-block'\nimport { MathBlock, MathInline } from '../extensions/math'\nimport { MentionNode, type MentionOptions } from '../extensions/mention'\nimport { MermaidPreview, SAMPLE_MERMAID } from '../extensions/mermaid'\nimport { TableOfContents as TocNode } from '../extensions/toc'\n\n/** Table of contents from the document's headings. */\nexport const toc = defineBlock({\n name: 'toc',\n nodes: ['tableOfContents'],\n extensions: () => [TocNode],\n items: () => [{\n id: 'toc',\n icon: TableOfContents,\n group: 'advanced',\n keywords: ['toc', 'table of contents', 'outline', 'muc luc', '目录'],\n insert: c => c.insertTableOfContents(),\n matches: isNode('tableOfContents'),\n }],\n})\n\n/**\n * Equations with KaTeX (peer dependency `katex`, loaded on first use). `$$ ` → block, `$$x$$` → inline.\n * Vue apps also import 'katex/dist/katex.min.css' (the Nuxt module adds it automatically).\n */\nexport const math = defineBlock({\n name: 'math',\n nodes: ['mathBlock'],\n extensions: () => [MathBlock, MathInline],\n items: () => [\n { id: 'mathBlock', icon: Sigma, group: 'advanced', keywords: ['math', 'equation', 'latex', 'katex', 'cong thuc', 'toan', '公式', '数学'], shortcut: '$$', insert: c => c.insertMathBlock(), matches: isNode('mathBlock') },\n { id: 'mathInline', icon: Radical, group: 'advanced', keywords: ['inline math', 'equation', 'latex', 'cong thuc', '行内公式', '公式'], insert: c => c.insertMathInline() },\n ],\n})\n\n/** Mermaid diagrams: code blocks in `mermaid` with a live preview (peer dependency `mermaid`). */\nexport const mermaid = defineBlock({\n name: 'mermaid',\n nodes: ['codeBlock'],\n extensions: () => [CodeBlock, MermaidPreview],\n items: () => [{\n id: 'mermaid',\n icon: Workflow,\n group: 'advanced',\n keywords: ['mermaid', 'diagram', 'flowchart', 'chart', 'so do', '图表', '流程图'],\n insert: c => c.setCodeBlock({ language: 'mermaid' }).insertContent(SAMPLE_MERMAID),\n matches: n => n.type.name === 'codeBlock' && n.attrs.language === 'mermaid',\n }],\n})\n\n/** `:` emoji picker (inserts unicode text). */\nexport const emoji = defineBlock({\n name: 'emoji',\n extensions: () => [EmojiSuggestion],\n})\n\nconst FILE_ICONS = { file: File, audio: AudioLines, video: Film } as const\n\n/** File attachments, audio and video. `file.configure({ upload, maxSize })`. */\nexport const file = defineBlock<FileBlockOptions>({\n name: 'file',\n defaults: { upload: null, maxSize: 10 },\n nodes: ['fileBlock'],\n extensions: o => [FileBlock.configure(o)],\n items: () => (['file', 'audio', 'video'] as FileKind[]).map((kind): BlockType => ({\n id: `file-${kind}`,\n icon: FILE_ICONS[kind],\n group: 'media',\n keywords: kind === 'file' ? ['file', 'attachment', 'upload', 'tep', 'dinh kem', '文件', '附件'] : kind === 'audio' ? ['audio', 'sound', 'music', 'am thanh', '音频', '音乐'] : ['video', 'upload', 'mp4', 'tai len', '视频', '上传'],\n insert: c => c.insertFileBlock(kind),\n matches: n => n.type.name === 'fileBlock' && n.attrs.kind === kind,\n })),\n})\n\n/** `@` mentions: dates built in; people/pages via `mention.configure({ search })`. */\nexport const mention = defineBlock<MentionOptions>({\n name: 'mention',\n defaults: { search: null, onClick: null, onRemind: null, reminderHelpUrl: null },\n extensions: o => [MentionNode.configure(o)],\n items: () => [{\n id: 'mention',\n icon: AtSign,\n group: 'basic',\n keywords: ['mention', 'person', 'page', 'date', 'nhac', 'ngay', '提及', '日期', '成员'],\n insert: c => c.insertContent('@'),\n }],\n})\n\n\n/**\n * Notion-style HTML block: HTML/CSS/JS in a sandboxed frame (edit in place or upload a\n * file). Network access is off by default; `html.configure({ network: ['https://cdn.jsdelivr.net'] })`.\n */\nexport const html = defineBlock<HtmlBlockOptions>({\n name: 'html',\n defaults: { network: false, maxSize: 1024, defaultHeight: 400 },\n nodes: ['htmlBlock'],\n extensions: o => [HtmlBlock.configure(o)],\n items: () => [{\n id: 'html',\n icon: CodeXml,\n group: 'advanced',\n keywords: ['html', 'code', 'widget', 'interactive', 'prototype', 'nhung', 'tuong tac', '网页', '交互'],\n insert: c => c.insertHtmlBlock(),\n matches: isNode('htmlBlock'),\n }],\n})\n","/**\n * Built-in blocks. Pass the ones you want to `<MeiEditor :blocks>`:\n * [...defaultBlocks, math, toc, file.configure({ upload })]\n * Heavy libraries (code grammars, KaTeX, Mermaid, emoji data) load on first use.\n */\nimport type { BlockDefinition } from '../define-block'\nimport { callout, codeBlock, columns, table, toggle, toggleHeading } from './advanced'\nimport { bulletList, divider, heading, orderedList, quote, taskList, text } from './basic'\nimport { embed, image } from './media'\n\nexport { callout, codeBlock, columns, table, toggle, toggleHeading } from './advanced'\nexport { bulletList, divider, heading, orderedList, quote, taskList, text } from './basic'\nexport { emoji, file, html, math, mention, mermaid, toc } from './extras'\nexport { embed, image } from './media'\n\n/** What `<MeiEditor>` loads when `blocks` isn't given. */\nexport const defaultBlocks: BlockDefinition[] = [\n heading, bulletList, orderedList, taskList, quote, divider, codeBlock,\n image, embed, callout, toggle, toggleHeading, table, columns,\n]\n\nexport { BLOCK_NAMES, type BlockName } from '../block-names'\n","import type { Schema } from '@tiptap/pm/model'\nimport type { JSONContent } from '@tiptap/vue-3'\n\n/** What happened while loading a document (see the `content-error` event). */\nexport interface ContentIssue {\n kind: 'unknown' | 'repaired' | 'invalid'\n /** Node type of the affected block. */\n type: string\n message?: string\n}\n\nexport class ContentError extends Error {\n constructor(message: string, public content: unknown) {\n super(message)\n this.name = 'ContentError'\n }\n}\n\n/**\n * Wraps nodes the schema doesn't know into `unknownBlock` / `unknownInline` so the\n * editor can load documents written with other blocks enabled. Unknown marks are dropped.\n */\nexport function wrapUnknown(doc: JSONContent | null | undefined, schema: Schema, issues: ContentIssue[] = []): JSONContent | null {\n if (!doc) return null\n const visit = (node: JSONContent, inline: boolean): JSONContent => {\n const type = node.type && schema.nodes[node.type]\n if (!type) {\n issues.push({ kind: 'unknown', type: String(node.type) })\n return { type: inline ? 'unknownInline' : 'unknownBlock', attrs: { data: node } }\n }\n const out: JSONContent = { ...node }\n if (node.marks) out.marks = node.marks.filter(m => schema.marks[m.type])\n if (node.content) out.content = node.content.map(child => visit(child, type.inlineContent))\n return out\n }\n return visit(doc, false)\n}\n\n/** Light repairs for common invalid JSON: empty text nodes, missing text. */\nfunction repair(node: JSONContent): JSONContent {\n if (!node.content) return node\n const content = node.content\n .filter(child => !(child.type === 'text' && !child.text))\n .map(repair)\n return { ...node, content }\n}\n\n/**\n * Validates a document block by block so one broken block never blanks the editor\n * (Tiptap shows an empty doc on invalid content, and the next save would overwrite it).\n * Fixable blocks are repaired; others are kept verbatim inside `unknownBlock`.\n * Throws {@link ContentError} only when the input isn't a document at all.\n */\nexport function sanitizeContent(doc: unknown, schema: Schema, issues: ContentIssue[] = []): JSONContent | null {\n if (doc == null || doc === '') return null\n if (typeof doc !== 'object' || (doc as JSONContent).type !== 'doc' || !Array.isArray((doc as JSONContent).content ?? [])) {\n throw new ContentError('Content is not a document ({ type: \"doc\", content: [...] })', doc)\n }\n\n const wrapped = wrapUnknown(doc as JSONContent, schema, issues)!\n const valid = (json: JSONContent) => {\n try {\n schema.nodeFromJSON(json).check()\n return true\n }\n catch {\n return false\n }\n }\n\n // Fast path: the whole document is valid (the normal case) — one parse, no per-block work.\n if (valid(wrapped)) return wrapped\n\n const blocks = (wrapped.content ?? []).map((block) => {\n if (valid(block)) return block\n const fixed = repair(block)\n if (valid(fixed)) {\n issues.push({ kind: 'repaired', type: String(block.type) })\n return fixed\n }\n issues.push({ kind: 'invalid', type: String(block.type) })\n return { type: 'unknownBlock', attrs: { data: block, invalid: true } }\n })\n return { ...wrapped, content: blocks }\n}\n\n/** Reverses {@link wrapUnknown}: puts the original JSON back. */\nexport function unwrapUnknown(doc: JSONContent): JSONContent {\n if (doc.type === 'unknownBlock' || doc.type === 'unknownInline') return doc.attrs?.data ?? { type: 'paragraph' }\n return doc.content ? { ...doc, content: doc.content.map(unwrapUnknown) } : doc\n}\n","export { component, PALETTE_NAMES, primitive, semanticBase, semanticDark, semanticLight, type PaletteName, type ThemeTokens } from './tokens'\nexport { baseTokensCss, installBaseTokens, injectStyle, LAYER, overridesCss } from './css'\nexport { cssVar, ref } from './define'\n\n/** Light / dark mode of an editor. `auto` follows `<html class=\"dark\">`. */\nexport type ThemeMode = 'light' | 'dark' | 'auto'\n\n/** Identity helper for typed token overrides: `defineTokens({ color: { accent: '#7c3aed' } })`. */\nexport const defineTokens = <T extends import('./tokens').ThemeTokens>(tokens: T) => tokens\n","import { PALETTE_NAMES } from './theme/tokens'\n\n/** Color names offered in menus. `default` removes the color. Actual colors come from theme tokens. */\nexport const COLORS = ['default', ...PALETTE_NAMES] as const\nexport type ColorName = typeof COLORS[number]\n","<script lang=\"ts\">\nimport { COLORS, type ColorName } from '../colors'\nimport type { RecentColor } from '../recent'\n\nexport interface ColorRow { section: 'recent' | 'text' | 'bg', kind: 'text' | 'bg', color: ColorName }\n\n/** Rows in display order, so parents can drive keyboard navigation by index. */\nexport function colorRows(recent: RecentColor[]): ColorRow[] {\n return [\n ...recent.map(r => ({ section: 'recent' as const, ...r })),\n ...COLORS.map(color => ({ section: 'text' as const, kind: 'text' as const, color })),\n ...COLORS.map(color => ({ section: 'bg' as const, kind: 'bg' as const, color })),\n ]\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Check } from '@lucide/vue'\nimport { computed } from 'vue'\nimport type { EditorMessages } from '../locale'\n\nconst props = defineProps<{\n messages: EditorMessages\n recent: RecentColor[]\n /** Colors currently applied (null = mixed / none). */\n current?: { text: string | null, bg: string | null }\n activeIndex?: number\n}>()\ndefineEmits<{ pick: [kind: 'text' | 'bg', color: ColorName], hover: [index: number] }>()\n\nconst rows = computed(() => colorRows(props.recent))\nconst label = (s: ColorRow['section']) => ({ recent: props.messages.blockMenu.recent, text: props.messages.blockMenu.textColor, bg: props.messages.blockMenu.backgroundColor })[s]\n/** `default` has no data-color, so it falls back to the normal text/background. */\nconst attr = (c: ColorName) => (c === 'default' ? undefined : c)\nconst isCurrent = (row: ColorRow) => row.section !== 'recent' && props.current?.[row.kind] === row.color\nconst name = (row: ColorRow) => {\n const color = props.messages.colors[row.color] ?? row.color\n if (row.section !== 'recent') return color\n return row.kind === 'text' ? props.messages.slash.textColor(color) : props.messages.slash.bgColor(color)\n}\n</script>\n\n<template>\n <template v-for=\"(row, i) in rows\" :key=\"`${row.section}-${row.kind}-${row.color}`\">\n <div v-if=\"i === 0 || rows[i - 1]!.section !== row.section\" class=\"me-menu-label\">\n {{ label(row.section) }}\n </div>\n <button\n type=\"button\"\n class=\"me-menu-item\"\n :class=\"{ 'is-active': i === activeIndex }\"\n :data-index=\"i\"\n @mouseenter=\"$emit('hover', i)\"\n @click=\"$emit('pick', row.kind, row.color)\"\n >\n <span class=\"me-menu-icon\" :class=\"row.kind === 'text' ? 'me-swatch--text' : 'me-swatch--bg'\" :data-color=\"attr(row.color)\">A</span>\n <span class=\"me-menu-title me-menu-text\">{{ name(row) }}</span>\n <Check v-if=\"isCurrent(row)\" class=\"me-menu-check\" />\n </button>\n </template>\n</template>\n","<script lang=\"ts\">\nimport { COLORS, type ColorName } from '../colors'\nimport type { RecentColor } from '../recent'\n\nexport interface ColorRow { section: 'recent' | 'text' | 'bg', kind: 'text' | 'bg', color: ColorName }\n\n/** Rows in display order, so parents can drive keyboard navigation by index. */\nexport function colorRows(recent: RecentColor[]): ColorRow[] {\n return [\n ...recent.map(r => ({ section: 'recent' as const, ...r })),\n ...COLORS.map(color => ({ section: 'text' as const, kind: 'text' as const, color })),\n ...COLORS.map(color => ({ section: 'bg' as const, kind: 'bg' as const, color })),\n ]\n}\n</script>\n\n<script setup lang=\"ts\">\nimport { Check } from '@lucide/vue'\nimport { computed } from 'vue'\nimport type { EditorMessages } from '../locale'\n\nconst props = defineProps<{\n messages: EditorMessages\n recent: RecentColor[]\n /** Colors currently applied (null = mixed / none). */\n current?: { text: string | null, bg: string | null }\n activeIndex?: number\n}>()\ndefineEmits<{ pick: [kind: 'text' | 'bg', color: ColorName], hover: [index: number] }>()\n\nconst rows = computed(() => colorRows(props.recent))\nconst label = (s: ColorRow['section']) => ({ recent: props.messages.blockMenu.recent, text: props.messages.blockMenu.textColor, bg: props.messages.blockMenu.backgroundColor })[s]\n/** `default` has no data-color, so it falls back to the normal text/background. */\nconst attr = (c: ColorName) => (c === 'default' ? undefined : c)\nconst isCurrent = (row: ColorRow) => row.section !== 'recent' && props.current?.[row.kind] === row.color\nconst name = (row: ColorRow) => {\n const color = props.messages.colors[row.color] ?? row.color\n if (row.section !== 'recent') return color\n return row.kind === 'text' ? props.messages.slash.textColor(color) : props.messages.slash.bgColor(color)\n}\n</script>\n\n<template>\n <template v-for=\"(row, i) in rows\" :key=\"`${row.section}-${row.kind}-${row.color}`\">\n <div v-if=\"i === 0 || rows[i - 1]!.section !== row.section\" class=\"me-menu-label\">\n {{ label(row.section) }}\n </div>\n <button\n type=\"button\"\n class=\"me-menu-item\"\n :class=\"{ 'is-active': i === activeIndex }\"\n :data-index=\"i\"\n @mouseenter=\"$emit('hover', i)\"\n @click=\"$emit('pick', row.kind, row.color)\"\n >\n <span class=\"me-menu-icon\" :class=\"row.kind === 'text' ? 'me-swatch--text' : 'me-swatch--bg'\" :data-color=\"attr(row.color)\">A</span>\n <span class=\"me-menu-title me-menu-text\">{{ name(row) }}</span>\n <Check v-if=\"isCurrent(row)\" class=\"me-menu-check\" />\n </button>\n </template>\n</template>\n","<script setup lang=\"ts\">\nimport type { Editor } from '@tiptap/vue-3'\nimport type { Component } from 'vue'\nimport { ArrowDown, ArrowUp, Check, ChevronRight, Copy, Link2, Palette, Repeat2, Search, Trash } from '@lucide/vue'\nimport { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'\nimport { type BlockType, blockTitle, turnIntoBlocks } from '../block-items'\nimport {\n type BlockRange, blocksIn, colorBlocks, deleteBlocks, duplicateBlocks, moveBlocks, rangeColors, turnBlocksInto,\n} from '../block-ops'\nimport type { ColorName } from '../colors'\nimport { useClickOutside } from '../composables/useClickOutside'\nimport { useScope } from '../composables/useScope'\nimport { TURN_INTO_SHORTCUTS } from '../extensions/block-selection'\nimport { isMod, kbd } from '../keys'\nimport { pushRecentColor, recent } from '../recent'\nimport { readTokenPx } from '../theme/read'\nimport ColorList, { colorRows } from './ColorList.vue'\n\nconst props = defineProps<{\n editor: Editor\n range: BlockRange\n anchor: DOMRect\n}>()\nconst emit = defineEmits<{ close: [], copyLink: [id: string] }>()\n\nconst root = ref<HTMLElement | null>(null)\nconst input = ref<HTMLInputElement | null>(null)\nuseClickOutside(root, ref(true), () => emit('close'))\n\nconst m = computed(() => props.editor.storage.meiConfig.messages)\nconst scope = useScope(() => props.editor)\nconst blocks = computed(() => blocksIn(props.editor.state.doc, props.range))\nconst targets = computed(() => turnIntoBlocks(props.editor))\n/** Current type when every selected block has the same one. */\nconst current = computed(() => {\n const types = blocks.value.map(b => targets.value.find(t => t.matches?.(b.node))?.id)\n return types.every(t => t && t === types[0]) ? targets.value.find(t => t.id === types[0]) : undefined\n})\nconst canTurnInto = computed(() => blocks.value.every(b => targets.value.some(t => t.matches?.(b.node)) || b.node.type.name === 'callout'))\nconst hasText = computed(() => blocks.value.some(b => b.node.textContent.length > 0 || b.node.isTextblock))\nconst colors = computed(() => rangeColors(props.editor.state, props.range))\nconst blockId = computed(() => (blocks.value.length === 1 ? blocks.value[0]!.node.attrs.id as string | undefined : undefined))\n\n// --- Rows ------------------------------------------------------------------\ninterface Row {\n key: string\n label: string\n icon?: Component\n /** Swatch for color rows. */\n swatch?: { kind: 'text' | 'bg', color: ColorName }\n hint?: string\n checked?: boolean\n submenu?: 'turn' | 'color'\n group?: string\n run?: () => void\n}\n\nfunction done(fn: () => void) {\n emit('close')\n fn()\n}\nconst shortcutFor = (b: BlockType) => {\n const key = Object.entries(TURN_INTO_SHORTCUTS).find(([, id]) => id === b.id)?.[0]\n return key ? kbd(`Mod-Alt-${key}`) : undefined\n}\nconst turnInto = (b: BlockType) => done(() => turnBlocksInto(props.editor, props.range, b))\nfunction pickColor(kind: 'text' | 'bg', color: ColorName) {\n if (color !== 'default') pushRecentColor({ kind, color })\n done(() => colorBlocks(props.editor, props.range, kind, color))\n}\n\nconst actions = computed<Row[]>(() => [\n { key: 'delete', label: m.value.blockMenu.delete, icon: Trash, hint: kbd('Delete'), run: () => done(() => deleteBlocks(props.editor, props.range)) },\n { key: 'duplicate', label: m.value.blockMenu.duplicate, icon: Copy, hint: kbd('Mod-d'), run: () => done(() => duplicateBlocks(props.editor, props.range)) },\n ...(blockId.value ? [{ key: 'link', label: m.value.blockMenu.copyLink, icon: Link2, run: () => done(() => emit('copyLink', blockId.value!)) }] : []),\n { key: 'up', label: m.value.blockMenu.moveUp, icon: ArrowUp, hint: kbd('Mod-Shift-ArrowUp'), run: () => done(() => moveBlocks(props.editor, props.range, 'up')) },\n { key: 'down', label: m.value.blockMenu.moveDown, icon: ArrowDown, hint: kbd('Mod-Shift-ArrowDown'), run: () => done(() => moveBlocks(props.editor, props.range, 'down')) },\n ...(canTurnInto.value ? [{ key: 'turn', label: m.value.blockMenu.turnInto, icon: Repeat2, submenu: 'turn' as const }] : []),\n ...(hasText.value ? [{ key: 'color', label: m.value.blockMenu.color, icon: Palette, submenu: 'color' as const }] : []),\n])\n\nconst turnRows = computed<Row[]>(() => targets.value.map(b => ({\n key: `turn-${b.id}`,\n label: blockTitle(m.value, b),\n icon: b.icon,\n hint: shortcutFor(b),\n checked: current.value?.id === b.id,\n group: m.value.blockMenu.turnInto,\n run: () => turnInto(b),\n})))\nconst colorRowList = computed(() => colorRows(recent.value.colors))\n\n// --- Search ----------------------------------------------------------------\nconst query = ref('')\nconst normalize = (s: string) => s.normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/đ/g, 'd').toLowerCase()\n\n/** Main list: actions; while searching, also matching turn-into types and colors. */\nconst rows = computed<Row[]>(() => {\n const q = normalize(query.value.trim())\n if (!q) return actions.value\n const match = (r: Row) => normalize(`${r.group ?? ''} ${r.label}`).includes(q)\n const colorMatches: Row[] = hasText.value\n ? colorRowList.value.filter(r => r.section !== 'recent').map(r => ({\n key: `color-${r.kind}-${r.color}`,\n label: r.kind === 'text' ? m.value.slash.textColor(m.value.colors[r.color] ?? r.color) : m.value.slash.bgColor(m.value.colors[r.color] ?? r.color),\n swatch: { kind: r.kind, color: r.color },\n group: m.value.blockMenu.color,\n run: () => pickColor(r.kind, r.color),\n }))\n : []\n return [\n ...actions.value.filter(r => !r.submenu).map(r => ({ ...r, group: m.value.blockMenu.actions })),\n ...(canTurnInto.value ? turnRows.value : []),\n ...colorMatches,\n ].filter(match)\n})\n\n// --- Navigation --------------------------------------------------------------\nconst active = ref(0)\nconst submenu = ref<'turn' | 'color' | null>(null)\nconst subActive = ref(-1)\nconst subCount = computed(() => (submenu.value === 'turn' ? turnRows.value.length : submenu.value === 'color' ? colorRowList.value.length : 0))\n\nwatch(query, () => {\n active.value = 0\n submenu.value = null\n})\n\nfunction scrollActive() {\n nextTick(() => root.value?.querySelector('.me-menu-item.is-active:not(.has-submenu-open), .me-submenu .me-menu-item.is-active')?.scrollIntoView({ block: 'nearest' }))\n}\n\nfunction openSubmenu(which: 'turn' | 'color', focusFirst = false) {\n submenu.value = which\n subActive.value = focusFirst ? 0 : -1\n}\n\nfunction runRow(row: Row | undefined) {\n if (!row) return\n if (row.submenu) return openSubmenu(row.submenu, true)\n row.run?.()\n}\n\nfunction runSubmenuItem(index: number) {\n if (submenu.value === 'turn') return runRow(turnRows.value[index])\n const row = colorRowList.value[index]\n if (row) pickColor(row.kind, row.color)\n}\n\nfunction onKeydown(e: KeyboardEvent) {\n const inSub = submenu.value && subActive.value >= 0\n const count = inSub ? subCount.value : rows.value.length\n const move = (delta: number) => {\n e.preventDefault()\n if (!count) return\n if (inSub) subActive.value = (subActive.value + delta + count) % count\n else active.value = (active.value + delta + count) % count\n scrollActive()\n }\n\n if (e.key === 'ArrowDown') return move(1)\n if (e.key === 'ArrowUp' && !e.shiftKey && !isMod(e)) return move(-1)\n if (e.key === 'ArrowRight' && !inSub && rows.value[active.value]?.submenu) {\n e.preventDefault()\n return openSubmenu(rows.value[active.value]!.submenu!, true)\n }\n if ((e.key === 'ArrowLeft' || e.key === 'Escape') && submenu.value) {\n e.preventDefault()\n submenu.value = null\n return\n }\n if (e.key === 'Escape') {\n e.preventDefault()\n return emit('close')\n }\n if (e.key === 'Enter') {\n e.preventDefault()\n return inSub ? runSubmenuItem(subActive.value) : runRow(rows.value[active.value])\n }\n // Menu shortcuts (only when not editing the search text).\n if ((e.key === 'Delete' || e.key === 'Backspace') && !query.value) {\n e.preventDefault()\n return done(() => deleteBlocks(props.editor, props.range))\n }\n if (isMod(e) && e.key.toLowerCase() === 'd') {\n e.preventDefault()\n return done(() => duplicateBlocks(props.editor, props.range))\n }\n if (isMod(e) && e.shiftKey && (e.key === 'ArrowUp' || e.key === 'ArrowDown')) {\n e.preventDefault()\n return done(() => moveBlocks(props.editor, props.range, e.key === 'ArrowUp' ? 'up' : 'down'))\n }\n}\n\n// Hover intent: submenus open/close after a short delay so diagonal mouse moves don't flicker.\nlet timer: ReturnType<typeof setTimeout> | undefined\nfunction hoverRow(index: number) {\n active.value = index\n clearTimeout(timer)\n const target = rows.value[index]?.submenu ?? null\n if (target === submenu.value) return\n timer = setTimeout(() => {\n if (target) openSubmenu(target)\n else submenu.value = null\n }, 150)\n}\nconst keepSubmenu = () => clearTimeout(timer)\n\n// --- Position --------------------------------------------------------------\n// Below the handle, kept inside the viewport (the menu is at most ~420px tall).\nconst gap = readTokenPx(props.editor.view.dom, 'popover.offset')\nconst style = computed(() => {\n const top = Math.min(props.anchor.bottom + gap, window.innerHeight - 420)\n return { left: `${Math.max(gap, props.anchor.left)}px`, top: `${Math.max(gap, top)}px` }\n})\n// Open submenus to the left when there's no room on the right.\nconst flipSubmenu = computed(() => {\n const el = props.editor.view.dom\n const width = readTokenPx(el, 'menu.width') + readTokenPx(el, 'menu.submenuWidth') + gap * 2\n return props.anchor.left + width > window.innerWidth\n})\n\nonMounted(() => input.value?.focus({ preventScroll: true }))\nonBeforeUnmount(() => clearTimeout(timer))\n</script>\n\n<template>\n <Teleport to=\"body\">\n <div\n ref=\"root\"\n v-bind=\"scope\"\n class=\"me-popover me-floating me-block-menu\"\n :class=\"{ 'is-flipped': flipSubmenu }\"\n :style=\"style\"\n @keydown=\"onKeydown\"\n >\n <label class=\"me-menu-search\">\n <Search />\n <input ref=\"input\" v-model=\"query\" class=\"me-menu-search-input\" :placeholder=\"m.blockMenu.search\">\n </label>\n <div v-if=\"blocks.length > 1\" class=\"me-menu-label\">\n {{ m.blockMenu.selected(blocks.length) }}\n </div>\n\n <!-- Scrolls only while searching: in the action list, submenus sit outside the box. -->\n <div class=\"me-block-menu-list\" :class=\"{ 'is-scroll': query }\">\n <template v-for=\"(row, i) in rows\" :key=\"row.key\">\n <div v-if=\"query && row.group && (i === 0 || rows[i - 1]!.group !== row.group)\" class=\"me-menu-label\">\n {{ row.group }}\n </div>\n <div class=\"me-submenu-anchor\" @mouseenter=\"hoverRow(i)\">\n <button\n type=\"button\"\n class=\"me-menu-item\"\n :class=\"{ 'is-active': i === active, 'has-submenu-open': row.submenu && submenu === row.submenu }\"\n @mousedown.prevent\n @click=\"runRow(row)\"\n >\n <span v-if=\"row.swatch\" class=\"me-menu-icon\" :class=\"row.swatch.kind === 'text' ? 'me-swatch--text' : 'me-swatch--bg'\" :data-color=\"row.swatch.color === 'default' ? undefined : row.swatch.color\">A</span>\n <span v-else class=\"me-menu-icon\"><component :is=\"row.icon\" /></span>\n <span class=\"me-menu-title me-menu-text\">{{ row.label }}</span>\n <Check v-if=\"row.checked\" class=\"me-menu-check\" />\n <span v-if=\"row.hint\" class=\"me-menu-shortcut\">{{ row.hint }}</span>\n <ChevronRight v-if=\"row.submenu\" class=\"me-menu-chevron\" />\n </button>\n\n <div v-if=\"row.submenu && submenu === row.submenu\" class=\"me-popover me-submenu\" @mouseenter=\"keepSubmenu\" @mousedown.prevent>\n <template v-if=\"row.submenu === 'turn'\">\n <button\n v-for=\"(t, ti) in turnRows\"\n :key=\"t.key\"\n type=\"button\"\n class=\"me-menu-item\"\n :class=\"{ 'is-active': ti === subActive }\"\n @mouseenter=\"subActive = ti\"\n @click=\"t.run?.()\"\n >\n <span class=\"me-menu-icon\"><component :is=\"t.icon\" /></span>\n <span class=\"me-menu-title me-menu-text\">{{ t.label }}</span>\n <Check v-if=\"t.checked\" class=\"me-menu-check\" />\n <span v-if=\"t.hint\" class=\"me-menu-shortcut\">{{ t.hint }}</span>\n </button>\n </template>\n <ColorList\n v-else\n :messages=\"m\"\n :recent=\"recent.colors\"\n :current=\"colors\"\n :active-index=\"subActive\"\n @hover=\"subActive = $event\"\n @pick=\"pickColor\"\n />\n </div>\n </div>\n </template>\n </div>\n <div v-if=\"!rows.length\" class=\"me-menu-empty\">\n {{ m.blockMenu.noResults }}\n </div>\n </div>\n </Teleport>\n</template>\n","<script setup lang=\"ts\">\nimport type { Editor } from '@tiptap/vue-3'\nimport type { Component } from 'vue'\nimport { ArrowDown, ArrowUp, Check, ChevronRight, Copy, Link2, Palette, Repeat2, Search, Trash } from '@lucide/vue'\nimport { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'\nimport { type BlockType, blockTitle, turnIntoBlocks } from '../block-items'\nimport {\n type BlockRange, blocksIn, colorBlocks, deleteBlocks, duplicateBlocks, moveBlocks, rangeColors, turnBlocksInto,\n} from '../block-ops'\nimport type { ColorName } from '../colors'\nimport { useClickOutside } from '../composables/useClickOutside'\nimport { useScope } from '../composables/useScope'\nimport { TURN_INTO_SHORTCUTS } from '../extensions/block-selection'\nimport { isMod, kbd } from '../keys'\nimport { pushRecentColor, recent } from '../recent'\nimport { readTokenPx } from '../theme/read'\nimport ColorList, { colorRows } from './ColorList.vue'\n\nconst props = defineProps<{\n editor: Editor\n range: BlockRange\n anchor: DOMRect\n}>()\nconst emit = defineEmits<{ close: [], copyLink: [id: string] }>()\n\nconst root = ref<HTMLElement | null>(null)\nconst input = ref<HTMLInputElement | null>(null)\nuseClickOutside(root, ref(true), () => emit('close'))\n\nconst m = computed(() => props.editor.storage.meiConfig.messages)\nconst scope = useScope(() => props.editor)\nconst blocks = computed(() => blocksIn(props.editor.state.doc, props.range))\nconst targets = computed(() => turnIntoBlocks(props.editor))\n/** Current type when every selected block has the same one. */\nconst current = computed(() => {\n const types = blocks.value.map(b => targets.value.find(t => t.matches?.(b.node))?.id)\n return types.every(t => t && t === types[0]) ? targets.value.find(t => t.id === types[0]) : undefined\n})\nconst canTurnInto = computed(() => blocks.value.every(b => targets.value.some(t => t.matches?.(b.node)) || b.node.type.name === 'callout'))\nconst hasText = computed(() => blocks.value.some(b => b.node.textContent.length > 0 || b.node.isTextblock))\nconst colors = computed(() => rangeColors(props.editor.state, props.range))\nconst blockId = computed(() => (blocks.value.length === 1 ? blocks.value[0]!.node.attrs.id as string | undefined : undefined))\n\n// --- Rows ------------------------------------------------------------------\ninterface Row {\n key: string\n label: string\n icon?: Component\n /** Swatch for color rows. */\n swatch?: { kind: 'text' | 'bg', color: ColorName }\n hint?: string\n checked?: boolean\n submenu?: 'turn' | 'color'\n group?: string\n run?: () => void\n}\n\nfunction done(fn: () => void) {\n emit('close')\n fn()\n}\nconst shortcutFor = (b: BlockType) => {\n const key = Object.entries(TURN_INTO_SHORTCUTS).find(([, id]) => id === b.id)?.[0]\n return key ? kbd(`Mod-Alt-${key}`) : undefined\n}\nconst turnInto = (b: BlockType) => done(() => turnBlocksInto(props.editor, props.range, b))\nfunction pickColor(kind: 'text' | 'bg', color: ColorName) {\n if (color !== 'default') pushRecentColor({ kind, color })\n done(() => colorBlocks(props.editor, props.range, kind, color))\n}\n\nconst actions = computed<Row[]>(() => [\n { key: 'delete', label: m.value.blockMenu.delete, icon: Trash, hint: kbd('Delete'), run: () => done(() => deleteBlocks(props.editor, props.range)) },\n { key: 'duplicate', label: m.value.blockMenu.duplicate, icon: Copy, hint: kbd('Mod-d'), run: () => done(() => duplicateBlocks(props.editor, props.range)) },\n ...(blockId.value ? [{ key: 'link', label: m.value.blockMenu.copyLink, icon: Link2, run: () => done(() => emit('copyLink', blockId.value!)) }] : []),\n { key: 'up', label: m.value.blockMenu.moveUp, icon: ArrowUp, hint: kbd('Mod-Shift-ArrowUp'), run: () => done(() => moveBlocks(props.editor, props.range, 'up')) },\n { key: 'down', label: m.value.blockMenu.moveDown, icon: ArrowDown, hint: kbd('Mod-Shift-ArrowDown'), run: () => done(() => moveBlocks(props.editor, props.range, 'down')) },\n ...(canTurnInto.value ? [{ key: 'turn', label: m.value.blockMenu.turnInto, icon: Repeat2, submenu: 'turn' as const }] : []),\n ...(hasText.value ? [{ key: 'color', label: m.value.blockMenu.color, icon: Palette, submenu: 'color' as const }] : []),\n])\n\nconst turnRows = computed<Row[]>(() => targets.value.map(b => ({\n key: `turn-${b.id}`,\n label: blockTitle(m.value, b),\n icon: b.icon,\n hint: shortcutFor(b),\n checked: current.value?.id === b.id,\n group: m.value.blockMenu.turnInto,\n run: () => turnInto(b),\n})))\nconst colorRowList = computed(() => colorRows(recent.value.colors))\n\n// --- Search ----------------------------------------------------------------\nconst query = ref('')\nconst normalize = (s: string) => s.normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/đ/g, 'd').toLowerCase()\n\n/** Main list: actions; while searching, also matching turn-into types and colors. */\nconst rows = computed<Row[]>(() => {\n const q = normalize(query.value.trim())\n if (!q) return actions.value\n const match = (r: Row) => normalize(`${r.group ?? ''} ${r.label}`).includes(q)\n const colorMatches: Row[] = hasText.value\n ? colorRowList.value.filter(r => r.section !== 'recent').map(r => ({\n key: `color-${r.kind}-${r.color}`,\n label: r.kind === 'text' ? m.value.slash.textColor(m.value.colors[r.color] ?? r.color) : m.value.slash.bgColor(m.value.colors[r.color] ?? r.color),\n swatch: { kind: r.kind, color: r.color },\n group: m.value.blockMenu.color,\n run: () => pickColor(r.kind, r.color),\n }))\n : []\n return [\n ...actions.value.filter(r => !r.submenu).map(r => ({ ...r, group: m.value.blockMenu.actions })),\n ...(canTurnInto.value ? turnRows.value : []),\n ...colorMatches,\n ].filter(match)\n})\n\n// --- Navigation --------------------------------------------------------------\nconst active = ref(0)\nconst submenu = ref<'turn' | 'color' | null>(null)\nconst subActive = ref(-1)\nconst subCount = computed(() => (submenu.value === 'turn' ? turnRows.value.length : submenu.value === 'color' ? colorRowList.value.length : 0))\n\nwatch(query, () => {\n active.value = 0\n submenu.value = null\n})\n\nfunction scrollActive() {\n nextTick(() => root.value?.querySelector('.me-menu-item.is-active:not(.has-submenu-open), .me-submenu .me-menu-item.is-active')?.scrollIntoView({ block: 'nearest' }))\n}\n\nfunction openSubmenu(which: 'turn' | 'color', focusFirst = false) {\n submenu.value = which\n subActive.value = focusFirst ? 0 : -1\n}\n\nfunction runRow(row: Row | undefined) {\n if (!row) return\n if (row.submenu) return openSubmenu(row.submenu, true)\n row.run?.()\n}\n\nfunction runSubmenuItem(index: number) {\n if (submenu.value === 'turn') return runRow(turnRows.value[index])\n const row = colorRowList.value[index]\n if (row) pickColor(row.kind, row.color)\n}\n\nfunction onKeydown(e: KeyboardEvent) {\n const inSub = submenu.value && subActive.value >= 0\n const count = inSub ? subCount.value : rows.value.length\n const move = (delta: number) => {\n e.preventDefault()\n if (!count) return\n if (inSub) subActive.value = (subActive.value + delta + count) % count\n else active.value = (active.value + delta + count) % count\n scrollActive()\n }\n\n if (e.key === 'ArrowDown') return move(1)\n if (e.key === 'ArrowUp' && !e.shiftKey && !isMod(e)) return move(-1)\n if (e.key === 'ArrowRight' && !inSub && rows.value[active.value]?.submenu) {\n e.preventDefault()\n return openSubmenu(rows.value[active.value]!.submenu!, true)\n }\n if ((e.key === 'ArrowLeft' || e.key === 'Escape') && submenu.value) {\n e.preventDefault()\n submenu.value = null\n return\n }\n if (e.key === 'Escape') {\n e.preventDefault()\n return emit('close')\n }\n if (e.key === 'Enter') {\n e.preventDefault()\n return inSub ? runSubmenuItem(subActive.value) : runRow(rows.value[active.value])\n }\n // Menu shortcuts (only when not editing the search text).\n if ((e.key === 'Delete' || e.key === 'Backspace') && !query.value) {\n e.preventDefault()\n return done(() => deleteBlocks(props.editor, props.range))\n }\n if (isMod(e) && e.key.toLowerCase() === 'd') {\n e.preventDefault()\n return done(() => duplicateBlocks(props.editor, props.range))\n }\n if (isMod(e) && e.shiftKey && (e.key === 'ArrowUp' || e.key === 'ArrowDown')) {\n e.preventDefault()\n return done(() => moveBlocks(props.editor, props.range, e.key === 'ArrowUp' ? 'up' : 'down'))\n }\n}\n\n// Hover intent: submenus open/close after a short delay so diagonal mouse moves don't flicker.\nlet timer: ReturnType<typeof setTimeout> | undefined\nfunction hoverRow(index: number) {\n active.value = index\n clearTimeout(timer)\n const target = rows.value[index]?.submenu ?? null\n if (target === submenu.value) return\n timer = setTimeout(() => {\n if (target) openSubmenu(target)\n else submenu.value = null\n }, 150)\n}\nconst keepSubmenu = () => clearTimeout(timer)\n\n// --- Position --------------------------------------------------------------\n// Below the handle, kept inside the viewport (the menu is at most ~420px tall).\nconst gap = readTokenPx(props.editor.view.dom, 'popover.offset')\nconst style = computed(() => {\n const top = Math.min(props.anchor.bottom + gap, window.innerHeight - 420)\n return { left: `${Math.max(gap, props.anchor.left)}px`, top: `${Math.max(gap, top)}px` }\n})\n// Open submenus to the left when there's no room on the right.\nconst flipSubmenu = computed(() => {\n const el = props.editor.view.dom\n const width = readTokenPx(el, 'menu.width') + readTokenPx(el, 'menu.submenuWidth') + gap * 2\n return props.anchor.left + width > window.innerWidth\n})\n\nonMounted(() => input.value?.focus({ preventScroll: true }))\nonBeforeUnmount(() => clearTimeout(timer))\n</script>\n\n<template>\n <Teleport to=\"body\">\n <div\n ref=\"root\"\n v-bind=\"scope\"\n class=\"me-popover me-floating me-block-menu\"\n :class=\"{ 'is-flipped': flipSubmenu }\"\n :style=\"style\"\n @keydown=\"onKeydown\"\n >\n <label class=\"me-menu-search\">\n <Search />\n <input ref=\"input\" v-model=\"query\" class=\"me-menu-search-input\" :placeholder=\"m.blockMenu.search\">\n </label>\n <div v-if=\"blocks.length > 1\" class=\"me-menu-label\">\n {{ m.blockMenu.selected(blocks.length) }}\n </div>\n\n <!-- Scrolls only while searching: in the action list, submenus sit outside the box. -->\n <div class=\"me-block-menu-list\" :class=\"{ 'is-scroll': query }\">\n <template v-for=\"(row, i) in rows\" :key=\"row.key\">\n <div v-if=\"query && row.group && (i === 0 || rows[i - 1]!.group !== row.group)\" class=\"me-menu-label\">\n {{ row.group }}\n </div>\n <div class=\"me-submenu-anchor\" @mouseenter=\"hoverRow(i)\">\n <button\n type=\"button\"\n class=\"me-menu-item\"\n :class=\"{ 'is-active': i === active, 'has-submenu-open': row.submenu && submenu === row.submenu }\"\n @mousedown.prevent\n @click=\"runRow(row)\"\n >\n <span v-if=\"row.swatch\" class=\"me-menu-icon\" :class=\"row.swatch.kind === 'text' ? 'me-swatch--text' : 'me-swatch--bg'\" :data-color=\"row.swatch.color === 'default' ? undefined : row.swatch.color\">A</span>\n <span v-else class=\"me-menu-icon\"><component :is=\"row.icon\" /></span>\n <span class=\"me-menu-title me-menu-text\">{{ row.label }}</span>\n <Check v-if=\"row.checked\" class=\"me-menu-check\" />\n <span v-if=\"row.hint\" class=\"me-menu-shortcut\">{{ row.hint }}</span>\n <ChevronRight v-if=\"row.submenu\" class=\"me-menu-chevron\" />\n </button>\n\n <div v-if=\"row.submenu && submenu === row.submenu\" class=\"me-popover me-submenu\" @mouseenter=\"keepSubmenu\" @mousedown.prevent>\n <template v-if=\"row.submenu === 'turn'\">\n <button\n v-for=\"(t, ti) in turnRows\"\n :key=\"t.key\"\n type=\"button\"\n class=\"me-menu-item\"\n :class=\"{ 'is-active': ti === subActive }\"\n @mouseenter=\"subActive = ti\"\n @click=\"t.run?.()\"\n >\n <span class=\"me-menu-icon\"><component :is=\"t.icon\" /></span>\n <span class=\"me-menu-title me-menu-text\">{{ t.label }}</span>\n <Check v-if=\"t.checked\" class=\"me-menu-check\" />\n <span v-if=\"t.hint\" class=\"me-menu-shortcut\">{{ t.hint }}</span>\n </button>\n </template>\n <ColorList\n v-else\n :messages=\"m\"\n :recent=\"recent.colors\"\n :current=\"colors\"\n :active-index=\"subActive\"\n @hover=\"subActive = $event\"\n @pick=\"pickColor\"\n />\n </div>\n </div>\n </template>\n </div>\n <div v-if=\"!rows.length\" class=\"me-menu-empty\">\n {{ m.blockMenu.noResults }}\n </div>\n </div>\n </Teleport>\n</template>\n","<script setup lang=\"ts\">\nimport type { Editor as CoreEditor } from '@tiptap/core'\nimport type { Editor } from '@tiptap/vue-3'\nimport { BubbleMenu } from '@tiptap/vue-3/menus'\nimport { type EditorState, NodeSelection } from '@tiptap/pm/state'\nimport { CellSelection } from '@tiptap/pm/tables'\nimport { Baseline, Bold, Check, ChevronDown, Code, Italic, Link, Strikethrough, Underline, Unlink } from '@lucide/vue'\nimport { computed, nextTick, ref } from 'vue'\nimport { blockTitle, turnIntoBlocks } from '../block-items'\nimport type { ColorName } from '../colors'\nimport { useScope } from '../composables/useScope'\nimport { readTokenPx } from '../theme/read'\nimport { pushRecentColor, recent } from '../recent'\nimport { blocksIn, currentRange, isBlockSelection, rangeColors, turnBlocksInto } from '../block-ops'\nimport type { FormatAction } from '../define-block'\nimport ColorList from './ColorList.vue'\n\nconst props = defineProps<{ editor: Editor }>()\n\nconst panel = ref<'turn' | 'color' | 'link' | null>(null)\nconst linkUrl = ref('')\nconst linkInput = ref<HTMLInputElement | null>(null)\nconst m = computed(() => props.editor.storage.meiConfig.messages)\nconst scope = useScope(() => props.editor)\nconst offset = readTokenPx(props.editor.view.dom, 'popover.offset')\n\n/** Bubble-menu buttons from blocks (e.g. \"Comment\"); read-only editors show only `readOnly` ones. */\nconst actionsFor = (editor: CoreEditor) => (editor.storage.meiConfig?.formatActions ?? [])\n .filter(a => (editor.isEditable || a.readOnly) && (a.isVisible?.(editor) ?? true))\n\nconst shouldShow = ({ editor, state, from, to }: { editor: CoreEditor, state: EditorState, from: number, to: number }) => {\n if (from === to) return false\n if (!editor.isEditable && !actionsFor(editor).length) return false\n // Whole-block selections use the ⋮⋮ menu instead, like Notion.\n // Whole cells use the table toolbar.\n if (state.selection instanceof NodeSelection || state.selection instanceof CellSelection || isBlockSelection(state)) return false\n if (editor.isActive('codeBlock')) return false\n return state.doc.textBetween(from, to).length > 0\n}\n\n// `isEditable` isn't reactive; reading the (reactive) state re-evaluates it on each transaction.\nconst editable = computed(() => {\n void props.editor.state\n return props.editor.isEditable\n})\n// Re-read on every render of the menu (selection changes re-render it).\nconst actions = computed(() => {\n void props.editor.state.selection\n return actionsFor(props.editor as CoreEditor)\n})\nconst actionTitle = (a: FormatAction) => (typeof a.title === 'function' ? a.title(props.editor as CoreEditor) : a.title)\nfunction runAction(a: FormatAction) {\n panel.value = null\n a.run(props.editor as CoreEditor)\n}\n\nconst targets = computed(() => turnIntoBlocks(props.editor))\nconst current = computed(() => {\n const range = currentRange(props.editor.state)\n const first = range && blocksIn(props.editor.state.doc, range)[0]\n return first ? targets.value.find(b => b.matches?.(first.node)) : undefined\n})\n\nconst marks = computed(() => [\n { name: 'bold', icon: Bold, title: `${m.value.format.bold} (⌘B)`, run: () => props.editor.chain().focus().toggleBold().run() },\n { name: 'italic', icon: Italic, title: `${m.value.format.italic} (⌘I)`, run: () => props.editor.chain().focus().toggleItalic().run() },\n { name: 'underline', icon: Underline, title: `${m.value.format.underline} (⌘U)`, run: () => props.editor.chain().focus().toggleUnderline().run() },\n { name: 'strike', icon: Strikethrough, title: `${m.value.format.strike} (⌘⇧S)`, run: () => props.editor.chain().focus().toggleStrike().run() },\n { name: 'code', icon: Code, title: `${m.value.format.code} (⌘E)`, run: () => props.editor.chain().focus().toggleCode().run() },\n])\n\nfunction toggle(p: typeof panel.value) {\n panel.value = panel.value === p ? null : p\n if (p === 'link' && panel.value === 'link') {\n linkUrl.value = props.editor.getAttributes('link').href ?? ''\n nextTick(() => linkInput.value?.focus())\n }\n}\n\nfunction turnInto(id: string) {\n const range = currentRange(props.editor.state)\n const target = targets.value.find(b => b.id === id)\n if (range && target) turnBlocksInto(props.editor, range, target)\n panel.value = null\n}\n\nfunction applyLink(href = linkUrl.value.trim()) {\n const chain = props.editor.chain().focus().extendMarkRange('link')\n if (!href) chain.unsetLink().run()\n else chain.setLink({ href: /^[a-z]+:/i.test(href) ? href : `https://${href}` }).run()\n panel.value = null\n}\n\nfunction setColor(kind: 'text' | 'bg', color: ColorName) {\n if (color !== 'default') pushRecentColor({ kind, color })\n const chain = props.editor.chain().focus()\n ;(kind === 'text' ? chain.setTextColor(color) : chain.setBgColor(color)).run()\n panel.value = null\n}\n\n// Colors of the selected text, to tick them in the menu.\nconst selectionColors = computed(() => {\n const { from, to } = props.editor.state.selection\n return rangeColors(props.editor.state, { from, to, depth: 0 })\n})\nconst activeTextColor = computed(() => props.editor.getAttributes('textColor').color as string | undefined)\n</script>\n\n<template>\n <BubbleMenu\n :editor=\"editor\"\n :should-show=\"shouldShow\"\n :options=\"{ placement: 'top-start', offset, onHide: () => (panel = null) }\"\n plugin-key=\"formatMenu\"\n >\n <div v-bind=\"scope\" class=\"me-popover me-toolbar\" @mousedown=\"panel !== 'link' && $event.preventDefault()\">\n <template v-if=\"!editable\">\n <button v-for=\"a in actions\" :key=\"a.id\" type=\"button\" class=\"me-tool-btn\" :title=\"actionTitle(a)\" @click=\"runAction(a)\">\n <component :is=\"a.icon\" /> {{ actionTitle(a) }}\n </button>\n </template>\n <template v-else>\n <template v-if=\"current\">\n <button type=\"button\" class=\"me-tool-btn\" @click=\"toggle('turn')\">\n {{ blockTitle(m, current) }} <ChevronDown class=\"me-chevron\" />\n </button>\n <span class=\"me-toolbar-divider\" />\n </template>\n\n <button\n v-for=\"mark in marks\"\n :key=\"mark.name\"\n type=\"button\"\n class=\"me-tool-btn\"\n :class=\"{ 'is-active': editor.isActive(mark.name) }\"\n :title=\"mark.title\"\n @click=\"mark.run\"\n >\n <component :is=\"mark.icon\" />\n </button>\n\n <span class=\"me-toolbar-divider\" />\n <button type=\"button\" class=\"me-tool-btn\" :class=\"{ 'is-active': editor.isActive('link') }\" :title=\"m.format.link\" @click=\"toggle('link')\">\n <Link />\n </button>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.format.color\" @click=\"toggle('color')\">\n <Baseline class=\"me-swatch--text\" :data-color=\"activeTextColor\" />\n <ChevronDown class=\"me-chevron\" />\n </button>\n\n <template v-if=\"actions.length\">\n <span class=\"me-toolbar-divider\" />\n <button v-for=\"a in actions\" :key=\"a.id\" type=\"button\" class=\"me-tool-btn\" :title=\"actionTitle(a)\" @click=\"runAction(a)\">\n <component :is=\"a.icon\" /> {{ actionTitle(a) }}\n </button>\n </template>\n\n <div v-if=\"panel === 'turn'\" class=\"me-popover me-toolbar-panel me-menu\">\n <button v-for=\"b in targets\" :key=\"b.id\" type=\"button\" class=\"me-menu-item\" @click=\"turnInto(b.id)\">\n <span class=\"me-menu-icon\"><component :is=\"b.icon\" /></span>\n <span class=\"me-menu-title me-menu-text\">{{ blockTitle(m, b) }}</span>\n <Check v-if=\"current?.id === b.id\" class=\"me-menu-check\" />\n </button>\n </div>\n\n <form v-if=\"panel === 'link'\" class=\"me-popover me-toolbar-panel me-link-form\" @submit.prevent=\"applyLink()\">\n <input ref=\"linkInput\" v-model=\"linkUrl\" class=\"me-input\" :placeholder=\"m.format.linkPlaceholder\" @keydown.esc=\"panel = null\">\n <button type=\"submit\" class=\"me-btn me-btn--primary\">\n {{ m.format.apply }}\n </button>\n <button v-if=\"editor.isActive('link')\" type=\"button\" class=\"me-btn\" :title=\"m.format.removeLink\" @click=\"applyLink('')\">\n <Unlink />\n </button>\n </form>\n\n <div v-if=\"panel === 'color'\" class=\"me-popover me-toolbar-panel me-toolbar-panel--end me-menu\">\n <ColorList :messages=\"m\" :recent=\"recent.colors\" :current=\"selectionColors\" @pick=\"setColor\" />\n </div>\n </template>\n </div>\n </BubbleMenu>\n</template>\n","<script setup lang=\"ts\">\nimport type { Editor as CoreEditor } from '@tiptap/core'\nimport type { Editor } from '@tiptap/vue-3'\nimport { BubbleMenu } from '@tiptap/vue-3/menus'\nimport { type EditorState, NodeSelection } from '@tiptap/pm/state'\nimport { CellSelection } from '@tiptap/pm/tables'\nimport { Baseline, Bold, Check, ChevronDown, Code, Italic, Link, Strikethrough, Underline, Unlink } from '@lucide/vue'\nimport { computed, nextTick, ref } from 'vue'\nimport { blockTitle, turnIntoBlocks } from '../block-items'\nimport type { ColorName } from '../colors'\nimport { useScope } from '../composables/useScope'\nimport { readTokenPx } from '../theme/read'\nimport { pushRecentColor, recent } from '../recent'\nimport { blocksIn, currentRange, isBlockSelection, rangeColors, turnBlocksInto } from '../block-ops'\nimport type { FormatAction } from '../define-block'\nimport ColorList from './ColorList.vue'\n\nconst props = defineProps<{ editor: Editor }>()\n\nconst panel = ref<'turn' | 'color' | 'link' | null>(null)\nconst linkUrl = ref('')\nconst linkInput = ref<HTMLInputElement | null>(null)\nconst m = computed(() => props.editor.storage.meiConfig.messages)\nconst scope = useScope(() => props.editor)\nconst offset = readTokenPx(props.editor.view.dom, 'popover.offset')\n\n/** Bubble-menu buttons from blocks (e.g. \"Comment\"); read-only editors show only `readOnly` ones. */\nconst actionsFor = (editor: CoreEditor) => (editor.storage.meiConfig?.formatActions ?? [])\n .filter(a => (editor.isEditable || a.readOnly) && (a.isVisible?.(editor) ?? true))\n\nconst shouldShow = ({ editor, state, from, to }: { editor: CoreEditor, state: EditorState, from: number, to: number }) => {\n if (from === to) return false\n if (!editor.isEditable && !actionsFor(editor).length) return false\n // Whole-block selections use the ⋮⋮ menu instead, like Notion.\n // Whole cells use the table toolbar.\n if (state.selection instanceof NodeSelection || state.selection instanceof CellSelection || isBlockSelection(state)) return false\n if (editor.isActive('codeBlock')) return false\n return state.doc.textBetween(from, to).length > 0\n}\n\n// `isEditable` isn't reactive; reading the (reactive) state re-evaluates it on each transaction.\nconst editable = computed(() => {\n void props.editor.state\n return props.editor.isEditable\n})\n// Re-read on every render of the menu (selection changes re-render it).\nconst actions = computed(() => {\n void props.editor.state.selection\n return actionsFor(props.editor as CoreEditor)\n})\nconst actionTitle = (a: FormatAction) => (typeof a.title === 'function' ? a.title(props.editor as CoreEditor) : a.title)\nfunction runAction(a: FormatAction) {\n panel.value = null\n a.run(props.editor as CoreEditor)\n}\n\nconst targets = computed(() => turnIntoBlocks(props.editor))\nconst current = computed(() => {\n const range = currentRange(props.editor.state)\n const first = range && blocksIn(props.editor.state.doc, range)[0]\n return first ? targets.value.find(b => b.matches?.(first.node)) : undefined\n})\n\nconst marks = computed(() => [\n { name: 'bold', icon: Bold, title: `${m.value.format.bold} (⌘B)`, run: () => props.editor.chain().focus().toggleBold().run() },\n { name: 'italic', icon: Italic, title: `${m.value.format.italic} (⌘I)`, run: () => props.editor.chain().focus().toggleItalic().run() },\n { name: 'underline', icon: Underline, title: `${m.value.format.underline} (⌘U)`, run: () => props.editor.chain().focus().toggleUnderline().run() },\n { name: 'strike', icon: Strikethrough, title: `${m.value.format.strike} (⌘⇧S)`, run: () => props.editor.chain().focus().toggleStrike().run() },\n { name: 'code', icon: Code, title: `${m.value.format.code} (⌘E)`, run: () => props.editor.chain().focus().toggleCode().run() },\n])\n\nfunction toggle(p: typeof panel.value) {\n panel.value = panel.value === p ? null : p\n if (p === 'link' && panel.value === 'link') {\n linkUrl.value = props.editor.getAttributes('link').href ?? ''\n nextTick(() => linkInput.value?.focus())\n }\n}\n\nfunction turnInto(id: string) {\n const range = currentRange(props.editor.state)\n const target = targets.value.find(b => b.id === id)\n if (range && target) turnBlocksInto(props.editor, range, target)\n panel.value = null\n}\n\nfunction applyLink(href = linkUrl.value.trim()) {\n const chain = props.editor.chain().focus().extendMarkRange('link')\n if (!href) chain.unsetLink().run()\n else chain.setLink({ href: /^[a-z]+:/i.test(href) ? href : `https://${href}` }).run()\n panel.value = null\n}\n\nfunction setColor(kind: 'text' | 'bg', color: ColorName) {\n if (color !== 'default') pushRecentColor({ kind, color })\n const chain = props.editor.chain().focus()\n ;(kind === 'text' ? chain.setTextColor(color) : chain.setBgColor(color)).run()\n panel.value = null\n}\n\n// Colors of the selected text, to tick them in the menu.\nconst selectionColors = computed(() => {\n const { from, to } = props.editor.state.selection\n return rangeColors(props.editor.state, { from, to, depth: 0 })\n})\nconst activeTextColor = computed(() => props.editor.getAttributes('textColor').color as string | undefined)\n</script>\n\n<template>\n <BubbleMenu\n :editor=\"editor\"\n :should-show=\"shouldShow\"\n :options=\"{ placement: 'top-start', offset, onHide: () => (panel = null) }\"\n plugin-key=\"formatMenu\"\n >\n <div v-bind=\"scope\" class=\"me-popover me-toolbar\" @mousedown=\"panel !== 'link' && $event.preventDefault()\">\n <template v-if=\"!editable\">\n <button v-for=\"a in actions\" :key=\"a.id\" type=\"button\" class=\"me-tool-btn\" :title=\"actionTitle(a)\" @click=\"runAction(a)\">\n <component :is=\"a.icon\" /> {{ actionTitle(a) }}\n </button>\n </template>\n <template v-else>\n <template v-if=\"current\">\n <button type=\"button\" class=\"me-tool-btn\" @click=\"toggle('turn')\">\n {{ blockTitle(m, current) }} <ChevronDown class=\"me-chevron\" />\n </button>\n <span class=\"me-toolbar-divider\" />\n </template>\n\n <button\n v-for=\"mark in marks\"\n :key=\"mark.name\"\n type=\"button\"\n class=\"me-tool-btn\"\n :class=\"{ 'is-active': editor.isActive(mark.name) }\"\n :title=\"mark.title\"\n @click=\"mark.run\"\n >\n <component :is=\"mark.icon\" />\n </button>\n\n <span class=\"me-toolbar-divider\" />\n <button type=\"button\" class=\"me-tool-btn\" :class=\"{ 'is-active': editor.isActive('link') }\" :title=\"m.format.link\" @click=\"toggle('link')\">\n <Link />\n </button>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.format.color\" @click=\"toggle('color')\">\n <Baseline class=\"me-swatch--text\" :data-color=\"activeTextColor\" />\n <ChevronDown class=\"me-chevron\" />\n </button>\n\n <template v-if=\"actions.length\">\n <span class=\"me-toolbar-divider\" />\n <button v-for=\"a in actions\" :key=\"a.id\" type=\"button\" class=\"me-tool-btn\" :title=\"actionTitle(a)\" @click=\"runAction(a)\">\n <component :is=\"a.icon\" /> {{ actionTitle(a) }}\n </button>\n </template>\n\n <div v-if=\"panel === 'turn'\" class=\"me-popover me-toolbar-panel me-menu\">\n <button v-for=\"b in targets\" :key=\"b.id\" type=\"button\" class=\"me-menu-item\" @click=\"turnInto(b.id)\">\n <span class=\"me-menu-icon\"><component :is=\"b.icon\" /></span>\n <span class=\"me-menu-title me-menu-text\">{{ blockTitle(m, b) }}</span>\n <Check v-if=\"current?.id === b.id\" class=\"me-menu-check\" />\n </button>\n </div>\n\n <form v-if=\"panel === 'link'\" class=\"me-popover me-toolbar-panel me-link-form\" @submit.prevent=\"applyLink()\">\n <input ref=\"linkInput\" v-model=\"linkUrl\" class=\"me-input\" :placeholder=\"m.format.linkPlaceholder\" @keydown.esc=\"panel = null\">\n <button type=\"submit\" class=\"me-btn me-btn--primary\">\n {{ m.format.apply }}\n </button>\n <button v-if=\"editor.isActive('link')\" type=\"button\" class=\"me-btn\" :title=\"m.format.removeLink\" @click=\"applyLink('')\">\n <Unlink />\n </button>\n </form>\n\n <div v-if=\"panel === 'color'\" class=\"me-popover me-toolbar-panel me-toolbar-panel--end me-menu\">\n <ColorList :messages=\"m\" :recent=\"recent.colors\" :current=\"selectionColors\" @pick=\"setColor\" />\n </div>\n </template>\n </div>\n </BubbleMenu>\n</template>\n","<script setup lang=\"ts\">\n/**\n * Notion-style floating outline: short bars on the right edge, one per heading\n * (longer for higher levels, darker for the section in view). Hover to see the full\n * table of contents; click an entry to scroll to it.\n */\nimport type { Editor } from '@tiptap/vue-3'\nimport { TextSelection } from '@tiptap/pm/state'\nimport { computed, onBeforeUnmount, onMounted, ref, shallowRef, watch } from 'vue'\nimport { useScope } from '../composables/useScope'\n\nconst props = defineProps<{ editor: Editor, minHeadings: number, root: HTMLElement | null }>()\nconst scope = useScope(() => props.editor)\n/** Only show while the editor is on screen (several editors on a page don't stack outlines). */\nconst onScreen = ref(true)\nlet observer: IntersectionObserver | null = null\nwatch(() => props.root, (root) => {\n observer?.disconnect()\n if (!root || typeof IntersectionObserver === 'undefined') return\n observer = new IntersectionObserver((list) => {\n onScreen.value = list.at(-1)?.isIntersecting ?? true\n })\n observer.observe(root)\n}, { immediate: true })\n\ninterface Entry { pos: number, level: number, text: string }\nconst entries = shallowRef<Entry[]>([])\nconst active = ref(-1)\nconst open = ref(false)\nconst m = computed(() => props.editor.storage.meiConfig.messages.toc)\n\nfunction collect() {\n const list: Entry[] = []\n props.editor.state.doc.forEach((node, offset) => {\n if (node.type.name === 'heading') list.push({ pos: offset, level: node.attrs.level, text: node.textContent })\n else if (node.type.name === 'details' && node.attrs.level) list.push({ pos: offset, level: node.attrs.level, text: node.firstChild?.textContent ?? '' })\n })\n entries.value = list\n updateActive()\n}\n\n// Recollect at most once per frame while typing.\nlet pending = 0\nfunction schedule() {\n if (pending) return\n pending = requestAnimationFrame(() => {\n pending = 0\n collect()\n })\n}\n\n/** The last heading whose top is above ~a quarter of the viewport. */\nfunction updateActive() {\n const { view } = props.editor\n const line = window.innerHeight * 0.25\n let current = entries.value.length ? 0 : -1\n entries.value.forEach((e, i) => {\n const dom = view.nodeDOM(e.pos)\n if (dom instanceof HTMLElement && dom.getBoundingClientRect().top <= line) current = i\n })\n active.value = current\n}\nlet scrollFrame = 0\nfunction onScroll() {\n cancelAnimationFrame(scrollFrame)\n scrollFrame = requestAnimationFrame(updateActive)\n}\n\nfunction go(e: Entry) {\n const { view } = props.editor\n ;(view.nodeDOM(e.pos) as HTMLElement | null)?.scrollIntoView({ behavior: 'smooth', block: 'start' })\n view.dispatch(view.state.tr.setSelection(TextSelection.near(view.state.doc.resolve(e.pos + 1))))\n view.focus()\n open.value = false\n}\n\nconst minLevel = computed(() => Math.min(...entries.value.map(e => e.level), 4))\nconst visible = computed(() => onScreen.value && entries.value.length >= props.minHeadings)\n\nlet closeTimer: ReturnType<typeof setTimeout> | undefined\nfunction enter() {\n clearTimeout(closeTimer)\n open.value = true\n}\nfunction leave() {\n clearTimeout(closeTimer)\n closeTimer = setTimeout(() => (open.value = false), 150)\n}\n\nonMounted(() => {\n collect()\n props.editor.on('update', schedule)\n window.addEventListener('scroll', onScroll, { passive: true, capture: true })\n window.addEventListener('resize', onScroll, { passive: true })\n})\nonBeforeUnmount(() => {\n observer?.disconnect()\n props.editor.off('update', schedule)\n window.removeEventListener('scroll', onScroll, { capture: true })\n window.removeEventListener('resize', onScroll)\n cancelAnimationFrame(pending)\n cancelAnimationFrame(scrollFrame)\n clearTimeout(closeTimer)\n})\n</script>\n\n<template>\n <!-- Fixed to the viewport's right edge (not the editor's), above full-width blocks. -->\n <Teleport to=\"body\">\n <nav v-if=\"visible\" v-bind=\"scope\" class=\"me-outline\" :aria-label=\"m.title\" @mouseenter=\"enter\" @mouseleave=\"leave\">\n <div class=\"me-outline-bars\" :class=\"{ 'is-hidden': open }\">\n <span\n v-for=\"(e, i) in entries\"\n :key=\"e.pos\"\n class=\"me-outline-bar\"\n :class=\"{ 'is-active': i === active }\"\n :data-depth=\"e.level - minLevel\"\n />\n </div>\n <div v-if=\"open\" class=\"me-popover me-outline-panel\">\n <button\n v-for=\"(e, i) in entries\"\n :key=\"e.pos\"\n type=\"button\"\n class=\"me-outline-item\"\n :class=\"{ 'is-active': i === active }\"\n :data-depth=\"e.level - minLevel\"\n @click=\"go(e)\"\n >\n {{ e.text || m.untitled }}\n </button>\n </div>\n </nav>\n </Teleport>\n</template>\n","<script setup lang=\"ts\">\n/**\n * Notion-style floating outline: short bars on the right edge, one per heading\n * (longer for higher levels, darker for the section in view). Hover to see the full\n * table of contents; click an entry to scroll to it.\n */\nimport type { Editor } from '@tiptap/vue-3'\nimport { TextSelection } from '@tiptap/pm/state'\nimport { computed, onBeforeUnmount, onMounted, ref, shallowRef, watch } from 'vue'\nimport { useScope } from '../composables/useScope'\n\nconst props = defineProps<{ editor: Editor, minHeadings: number, root: HTMLElement | null }>()\nconst scope = useScope(() => props.editor)\n/** Only show while the editor is on screen (several editors on a page don't stack outlines). */\nconst onScreen = ref(true)\nlet observer: IntersectionObserver | null = null\nwatch(() => props.root, (root) => {\n observer?.disconnect()\n if (!root || typeof IntersectionObserver === 'undefined') return\n observer = new IntersectionObserver((list) => {\n onScreen.value = list.at(-1)?.isIntersecting ?? true\n })\n observer.observe(root)\n}, { immediate: true })\n\ninterface Entry { pos: number, level: number, text: string }\nconst entries = shallowRef<Entry[]>([])\nconst active = ref(-1)\nconst open = ref(false)\nconst m = computed(() => props.editor.storage.meiConfig.messages.toc)\n\nfunction collect() {\n const list: Entry[] = []\n props.editor.state.doc.forEach((node, offset) => {\n if (node.type.name === 'heading') list.push({ pos: offset, level: node.attrs.level, text: node.textContent })\n else if (node.type.name === 'details' && node.attrs.level) list.push({ pos: offset, level: node.attrs.level, text: node.firstChild?.textContent ?? '' })\n })\n entries.value = list\n updateActive()\n}\n\n// Recollect at most once per frame while typing.\nlet pending = 0\nfunction schedule() {\n if (pending) return\n pending = requestAnimationFrame(() => {\n pending = 0\n collect()\n })\n}\n\n/** The last heading whose top is above ~a quarter of the viewport. */\nfunction updateActive() {\n const { view } = props.editor\n const line = window.innerHeight * 0.25\n let current = entries.value.length ? 0 : -1\n entries.value.forEach((e, i) => {\n const dom = view.nodeDOM(e.pos)\n if (dom instanceof HTMLElement && dom.getBoundingClientRect().top <= line) current = i\n })\n active.value = current\n}\nlet scrollFrame = 0\nfunction onScroll() {\n cancelAnimationFrame(scrollFrame)\n scrollFrame = requestAnimationFrame(updateActive)\n}\n\nfunction go(e: Entry) {\n const { view } = props.editor\n ;(view.nodeDOM(e.pos) as HTMLElement | null)?.scrollIntoView({ behavior: 'smooth', block: 'start' })\n view.dispatch(view.state.tr.setSelection(TextSelection.near(view.state.doc.resolve(e.pos + 1))))\n view.focus()\n open.value = false\n}\n\nconst minLevel = computed(() => Math.min(...entries.value.map(e => e.level), 4))\nconst visible = computed(() => onScreen.value && entries.value.length >= props.minHeadings)\n\nlet closeTimer: ReturnType<typeof setTimeout> | undefined\nfunction enter() {\n clearTimeout(closeTimer)\n open.value = true\n}\nfunction leave() {\n clearTimeout(closeTimer)\n closeTimer = setTimeout(() => (open.value = false), 150)\n}\n\nonMounted(() => {\n collect()\n props.editor.on('update', schedule)\n window.addEventListener('scroll', onScroll, { passive: true, capture: true })\n window.addEventListener('resize', onScroll, { passive: true })\n})\nonBeforeUnmount(() => {\n observer?.disconnect()\n props.editor.off('update', schedule)\n window.removeEventListener('scroll', onScroll, { capture: true })\n window.removeEventListener('resize', onScroll)\n cancelAnimationFrame(pending)\n cancelAnimationFrame(scrollFrame)\n clearTimeout(closeTimer)\n})\n</script>\n\n<template>\n <!-- Fixed to the viewport's right edge (not the editor's), above full-width blocks. -->\n <Teleport to=\"body\">\n <nav v-if=\"visible\" v-bind=\"scope\" class=\"me-outline\" :aria-label=\"m.title\" @mouseenter=\"enter\" @mouseleave=\"leave\">\n <div class=\"me-outline-bars\" :class=\"{ 'is-hidden': open }\">\n <span\n v-for=\"(e, i) in entries\"\n :key=\"e.pos\"\n class=\"me-outline-bar\"\n :class=\"{ 'is-active': i === active }\"\n :data-depth=\"e.level - minLevel\"\n />\n </div>\n <div v-if=\"open\" class=\"me-popover me-outline-panel\">\n <button\n v-for=\"(e, i) in entries\"\n :key=\"e.pos\"\n type=\"button\"\n class=\"me-outline-item\"\n :class=\"{ 'is-active': i === active }\"\n :data-depth=\"e.level - minLevel\"\n @click=\"go(e)\"\n >\n {{ e.text || m.untitled }}\n </button>\n </div>\n </nav>\n </Teleport>\n</template>\n","/**\n * Table operations used by the table controls (row/column handles, add buttons,\n * cell toolbar). Rows and columns are addressed by index within a table at `tablePos`.\n */\nimport type { Editor } from '@tiptap/core'\nimport type { Node as PMNode } from '@tiptap/pm/model'\nimport { TextSelection } from '@tiptap/pm/state'\nimport { CellSelection, moveTableColumn, moveTableRow, TableMap } from '@tiptap/pm/tables'\n\nexport interface TableRef { pos: number, node: PMNode, map: TableMap }\n\nexport function tableAt(editor: Editor, pos: number): TableRef | null {\n const node = editor.state.doc.nodeAt(pos)\n if (!node || node.type.name !== 'table') return null\n return { pos, node, map: TableMap.get(node) }\n}\n\n/** Document position of the cell at (row, col). */\nexport function cellPos(t: TableRef, row: number, col: number) {\n return t.pos + 1 + t.map.map[row * t.map.width + col]!\n}\n\n/** Puts the cursor in a cell so Tiptap's table commands act on it. */\nfunction focusCell(editor: Editor, t: TableRef, row: number, col: number) {\n const pos = cellPos(t, row, col)\n editor.view.dispatch(editor.state.tr.setSelection(TextSelection.near(editor.state.doc.resolve(pos + 1))))\n}\n\nexport function selectRow(editor: Editor, t: TableRef, row: number) {\n const $cell = editor.state.doc.resolve(cellPos(t, row, 0))\n editor.view.dispatch(editor.state.tr.setSelection(CellSelection.rowSelection($cell)))\n}\n\nexport function selectColumn(editor: Editor, t: TableRef, col: number) {\n const $cell = editor.state.doc.resolve(cellPos(t, 0, col))\n editor.view.dispatch(editor.state.tr.setSelection(CellSelection.colSelection($cell)))\n}\n\nexport function insertRow(editor: Editor, t: TableRef, row: number, where: 'before' | 'after') {\n focusCell(editor, t, row, 0)\n editor.chain().focus()[where === 'before' ? 'addRowBefore' : 'addRowAfter']().run()\n}\n\nexport function insertColumn(editor: Editor, t: TableRef, col: number, where: 'before' | 'after') {\n focusCell(editor, t, 0, col)\n editor.chain().focus()[where === 'before' ? 'addColumnBefore' : 'addColumnAfter']().run()\n}\n\nexport function deleteRow(editor: Editor, t: TableRef, row: number) {\n if (t.map.height <= 1) return editor.chain().focus().setNodeSelection(t.pos).deleteSelection().run()\n focusCell(editor, t, row, 0)\n editor.chain().focus().deleteRow().run()\n}\n\nexport function deleteColumn(editor: Editor, t: TableRef, col: number) {\n if (t.map.width <= 1) return editor.chain().focus().setNodeSelection(t.pos).deleteSelection().run()\n focusCell(editor, t, 0, col)\n editor.chain().focus().deleteColumn().run()\n}\n\nexport function moveRow(editor: Editor, t: TableRef, from: number, to: number) {\n if (to < 0 || to >= t.map.height) return\n moveTableRow({ from, to, select: true, pos: t.pos + 1 })(editor.state, editor.view.dispatch)\n}\n\nexport function moveColumn(editor: Editor, t: TableRef, from: number, to: number) {\n if (to < 0 || to >= t.map.width) return\n moveTableColumn({ from, to, select: true, pos: t.pos + 1 })(editor.state, editor.view.dispatch)\n}\n\nexport function duplicateRow(editor: Editor, t: TableRef, row: number) {\n const $row = editor.state.doc.resolve(cellPos(t, row, 0))\n const rowNode = $row.parent\n const after = $row.after()\n editor.view.dispatch(editor.state.tr.insert(after, rowNode.copy(rowNode.content)))\n}\n\n/** Copies a column to its right. Skips cells that span several columns. */\nexport function duplicateColumn(editor: Editor, t: TableRef, col: number) {\n const tr = editor.state.tr\n for (let row = t.map.height - 1; row >= 0; row--) {\n const pos = cellPos(t, row, col)\n const cell = editor.state.doc.nodeAt(pos)\n if (!cell || (cell.attrs.colspan ?? 1) > 1 || (row > 0 && cellPos(t, row - 1, col) === pos)) continue\n tr.insert(pos + cell.nodeSize, cell.type.create({ ...cell.attrs, colwidth: cell.attrs.colwidth }, cell.content))\n }\n editor.view.dispatch(tr)\n}\n\n/** Empties the cells of the current cell selection. */\nexport function clearSelectedCells(editor: Editor) {\n const sel = editor.state.selection\n if (!(sel instanceof CellSelection)) return\n const tr = editor.state.tr\n const paragraph = editor.schema.nodes.paragraph!\n sel.forEachCell((cell, pos) => {\n const from = tr.mapping.map(pos + 1)\n const to = tr.mapping.map(pos + cell.nodeSize - 1)\n tr.replaceWith(from, to, paragraph.create())\n })\n editor.view.dispatch(tr)\n}\n\nexport function colorSelectedCells(editor: Editor, color: string | null) {\n editor.chain().focus().setCellAttribute('color', color === 'default' ? null : color).run()\n}\n\nexport const hasHeaderRow = (t: TableRef) => {\n let header = true\n t.node.firstChild?.forEach((cell) => {\n if (cell.type.name !== 'tableHeader') header = false\n })\n return header\n}\n\nexport const hasHeaderColumn = (t: TableRef) => {\n let header = true\n t.node.forEach((row) => {\n if (row.firstChild?.type.name !== 'tableHeader') header = false\n })\n return header\n}\n\nexport function toggleHeader(editor: Editor, t: TableRef, kind: 'row' | 'column') {\n focusCell(editor, t, 0, 0)\n editor.chain().focus()[kind === 'row' ? 'toggleHeaderRow' : 'toggleHeaderColumn']().run()\n}\n","<script setup lang=\"ts\">\n/**\n * Notion-style table controls, drawn over the editor:\n * - grip handles on the hovered row (left) and column (top) → row/column menu\n * - \"+\" bars below and to the right of the table to add a row / column\n * - a small toolbar for multi-cell selections (merge, split, color, clear)\n */\nimport type { Editor } from '@tiptap/vue-3'\nimport type { Component } from 'vue'\nimport {\n ArrowDown, ArrowDownToLine, ArrowLeft, ArrowLeftToLine, ArrowRight, ArrowRightToLine, ArrowUp, ArrowUpToLine,\n Check, ChevronRight, Copy, Eraser, GripHorizontal, GripVertical, Palette, PanelLeft, PanelTop, Plus,\n TableCellsMerge, TableCellsSplit, Trash,\n} from '@lucide/vue'\nimport { CellSelection } from '@tiptap/pm/tables'\nimport { computed, onBeforeUnmount, onMounted, ref, shallowRef } from 'vue'\nimport { COLORS } from '../colors'\nimport { useClickOutside } from '../composables/useClickOutside'\nimport { useScope } from '../composables/useScope'\nimport {\n clearSelectedCells, colorSelectedCells, deleteColumn, deleteRow, duplicateColumn, duplicateRow, hasHeaderColumn,\n hasHeaderRow, insertColumn, insertRow, moveColumn, moveRow, selectColumn, selectRow, tableAt, type TableRef, toggleHeader,\n} from '../table-ops'\n\nconst props = defineProps<{ editor: Editor }>()\n\nconst scope = useScope(() => props.editor)\nconst m = computed(() => props.editor.storage.meiConfig.messages.table)\nconst colorNames = computed(() => props.editor.storage.meiConfig.messages.colors)\nconst layer = ref<HTMLElement | null>(null)\n\n// --- Hover tracking -----------------------------------------------------------\ninterface Hover { tablePos: number, row: number, col: number, table: DOMRect, visible: DOMRect, rowRect: DOMRect, colRect: DOMRect }\nconst hover = shallowRef<Hover | null>(null)\nlet hideTimer: ReturnType<typeof setTimeout> | undefined\nlet frame = 0\n\n/** Rect relative to the controls layer (which covers the editor root). */\nfunction local(r: DOMRect) {\n const base = layer.value!.getBoundingClientRect()\n return new DOMRect(r.left - base.left, r.top - base.top, r.width, r.height)\n}\n\nfunction locate(cell: HTMLElement): Hover | null {\n const { view } = props.editor\n const tableEl = cell.closest('table')\n const wrapper = cell.closest('.tableWrapper') ?? tableEl\n if (!tableEl || !wrapper || !layer.value) return null\n const $pos = view.state.doc.resolve(view.posAtDOM(cell, 0))\n let depth = $pos.depth\n while (depth > 0 && !['tableCell', 'tableHeader'].includes($pos.node(depth).type.name)) depth--\n if (depth < 2) return null\n const tablePos = $pos.before(depth - 2)\n const t = tableAt(props.editor, tablePos)\n if (!t) return null\n const rect = t.map.findCell($pos.before(depth) - tablePos - 1)\n const tableRect = tableEl.getBoundingClientRect()\n const wrapRect = wrapper.getBoundingClientRect()\n const visible = new DOMRect(tableRect.left, tableRect.top, Math.min(tableRect.right, wrapRect.right) - tableRect.left, tableRect.height)\n return {\n tablePos,\n row: rect.top,\n col: rect.left,\n table: local(tableRect),\n visible: local(visible),\n rowRect: local((cell.parentElement as HTMLElement).getBoundingClientRect()),\n colRect: local(cell.getBoundingClientRect()),\n }\n}\n\nfunction onMouseMove(e: MouseEvent) {\n if (menu.value || !props.editor.isEditable) return\n const target = e.target as HTMLElement | null\n if (target?.closest('.me-table-controls-ui')) {\n clearTimeout(hideTimer)\n return\n }\n cancelAnimationFrame(frame)\n frame = requestAnimationFrame(() => {\n const cell = target?.closest('td, th') as HTMLElement | null\n if (cell && props.editor.view.dom.contains(cell)) {\n clearTimeout(hideTimer)\n hover.value = locate(cell)\n }\n else if (hover.value) {\n clearTimeout(hideTimer)\n hideTimer = setTimeout(() => (hover.value = null), 250)\n }\n })\n}\n\nconst table = computed<TableRef | null>(() => {\n void tick.value\n return hover.value ? tableAt(props.editor, hover.value.tablePos) : null\n})\n\n// Re-read the table after edits (positions and sizes change).\nconst tick = ref(0)\nconst onUpdate = () => {\n tick.value++\n if (hover.value && !tableAt(props.editor, hover.value.tablePos)) hover.value = null\n}\n\n// --- Menus --------------------------------------------------------------------\ninterface Item { key: string, label: string, icon: Component, run?: () => void, checked?: boolean, danger?: boolean, disabled?: boolean, submenu?: boolean }\nconst menu = shallowRef<{ kind: 'row' | 'col', index: number, tablePos: number, x: number, y: number, above: boolean } | null>(null)\nconst colorOpen = ref(false)\nconst menuEl = ref<HTMLElement | null>(null)\nuseClickOutside(menuEl, computed(() => !!menu.value), () => closeMenu())\n\nfunction openMenu(kind: 'row' | 'col', e: MouseEvent) {\n const h = hover.value\n const t = table.value\n if (!h || !t) return\n if (kind === 'row') selectRow(props.editor, t, h.row)\n else selectColumn(props.editor, t, h.col)\n const screen = (e.currentTarget as HTMLElement).getBoundingClientRect()\n const r = local(screen)\n // Open upwards when the handle is in the lower part of the viewport (menu is ~360px tall).\n const above = screen.bottom + 360 > window.innerHeight\n menu.value = { kind, index: kind === 'row' ? h.row : h.col, tablePos: h.tablePos, x: r.left, y: r.bottom + 4, above }\n colorOpen.value = false\n}\n\nfunction closeMenu() {\n menu.value = null\n colorOpen.value = false\n}\n\nfunction run(fn: () => void) {\n fn()\n closeMenu()\n props.editor.commands.focus()\n}\n\nconst menuItems = computed<Item[]>(() => {\n const mn = menu.value\n void tick.value\n const t = mn && tableAt(props.editor, mn.tablePos)\n if (!mn || !t) return []\n const ed = props.editor\n const i = mn.index\n const t2 = m.value\n if (mn.kind === 'row') {\n return [\n ...(i === 0 ? [{ key: 'header', label: t2.headerRow, icon: PanelTop, checked: hasHeaderRow(t), run: () => toggleHeader(ed, t, 'row') }] : []),\n { key: 'above', label: t2.insertAbove, icon: ArrowUpToLine, run: () => insertRow(ed, t, i, 'before') },\n { key: 'below', label: t2.insertBelow, icon: ArrowDownToLine, run: () => insertRow(ed, t, i, 'after') },\n { key: 'dup', label: t2.duplicate, icon: Copy, run: () => duplicateRow(ed, t, i) },\n { key: 'up', label: t2.moveUp, icon: ArrowUp, disabled: i === 0, run: () => moveRow(ed, t, i, i - 1) },\n { key: 'down', label: t2.moveDown, icon: ArrowDown, disabled: i === t.map.height - 1, run: () => moveRow(ed, t, i, i + 1) },\n { key: 'clear', label: t2.clear, icon: Eraser, run: () => clearSelectedCells(ed) },\n { key: 'color', label: t2.color, icon: Palette, submenu: true },\n { key: 'delete', label: t2.deleteRow, icon: Trash, danger: true, run: () => deleteRow(ed, t, i) },\n ]\n }\n return [\n ...(i === 0 ? [{ key: 'header', label: t2.headerColumn, icon: PanelLeft, checked: hasHeaderColumn(t), run: () => toggleHeader(ed, t, 'column') }] : []),\n { key: 'left', label: t2.insertLeft, icon: ArrowLeftToLine, run: () => insertColumn(ed, t, i, 'before') },\n { key: 'right', label: t2.insertRight, icon: ArrowRightToLine, run: () => insertColumn(ed, t, i, 'after') },\n { key: 'dup', label: t2.duplicate, icon: Copy, run: () => duplicateColumn(ed, t, i) },\n { key: 'mleft', label: t2.moveLeft, icon: ArrowLeft, disabled: i === 0, run: () => moveColumn(ed, t, i, i - 1) },\n { key: 'mright', label: t2.moveRight, icon: ArrowRight, disabled: i === t.map.width - 1, run: () => moveColumn(ed, t, i, i + 1) },\n { key: 'clear', label: t2.clear, icon: Eraser, run: () => clearSelectedCells(ed) },\n { key: 'color', label: t2.color, icon: Palette, submenu: true },\n { key: 'delete', label: t2.deleteColumn, icon: Trash, danger: true, run: () => deleteColumn(ed, t, i) },\n ]\n})\n\nfunction onMenuKey(e: KeyboardEvent) {\n if (e.key === 'Escape') closeMenu()\n}\n\n// --- Add row / column -----------------------------------------------------------\nfunction addRow() {\n const t = table.value\n if (t) insertRow(props.editor, t, t.map.height - 1, 'after')\n}\nfunction addColumn() {\n const t = table.value\n if (t) insertColumn(props.editor, t, t.map.width - 1, 'after')\n}\n\n// --- Multi-cell toolbar -------------------------------------------------------------\nconst selection = shallowRef<{ x: number, y: number, canMerge: boolean, canSplit: boolean } | null>(null)\nconst cellColorOpen = ref(false)\nfunction onSelection() {\n const sel = props.editor.state.selection\n if (!(sel instanceof CellSelection) || menu.value || !layer.value) {\n selection.value = null\n cellColorOpen.value = false\n return\n }\n let top = Infinity\n let left = Infinity\n sel.forEachCell((_cell, pos) => {\n const dom = props.editor.view.nodeDOM(pos)\n if (dom instanceof HTMLElement) {\n const r = local(dom.getBoundingClientRect())\n top = Math.min(top, r.top)\n left = Math.min(left, r.left)\n }\n })\n if (!Number.isFinite(top)) return\n selection.value = { x: left, y: top, canMerge: props.editor.can().mergeCells(), canSplit: props.editor.can().splitCell() }\n}\n\nconst bgColors = COLORS\n\nonMounted(() => {\n document.addEventListener('mousemove', onMouseMove)\n props.editor.on('update', onUpdate)\n props.editor.on('selectionUpdate', onSelection)\n})\nonBeforeUnmount(() => {\n document.removeEventListener('mousemove', onMouseMove)\n props.editor.off('update', onUpdate)\n props.editor.off('selectionUpdate', onSelection)\n clearTimeout(hideTimer)\n cancelAnimationFrame(frame)\n})\n</script>\n\n<template>\n <div ref=\"layer\" class=\"me-table-controls\">\n <template v-if=\"hover && table && !menu\">\n <button\n type=\"button\"\n class=\"me-table-controls-ui me-table-grip me-table-grip--row\"\n :style=\"{ left: `${hover.table.left}px`, top: `${hover.rowRect.top}px`, height: `${hover.rowRect.height}px` }\"\n :title=\"m.rowMenu\"\n @mousedown.prevent\n @click=\"openMenu('row', $event)\"\n >\n <GripVertical />\n </button>\n <button\n type=\"button\"\n class=\"me-table-controls-ui me-table-grip me-table-grip--col\"\n :style=\"{ left: `${hover.colRect.left}px`, top: `${hover.table.top}px`, width: `${hover.colRect.width}px` }\"\n :title=\"m.columnMenu\"\n @mousedown.prevent\n @click=\"openMenu('col', $event)\"\n >\n <GripHorizontal />\n </button>\n <button\n type=\"button\"\n class=\"me-table-controls-ui me-table-add me-table-add--row\"\n :style=\"{ left: `${hover.visible.left}px`, top: `${hover.table.top + hover.table.height}px`, width: `${hover.visible.width}px` }\"\n :title=\"m.addRow\"\n @mousedown.prevent\n @click=\"addRow\"\n >\n <Plus />\n </button>\n <button\n type=\"button\"\n class=\"me-table-controls-ui me-table-add me-table-add--col\"\n :style=\"{ left: `${hover.visible.left + hover.visible.width}px`, top: `${hover.table.top}px`, height: `${hover.table.height}px` }\"\n :title=\"m.addColumn\"\n @mousedown.prevent\n @click=\"addColumn\"\n >\n <Plus />\n </button>\n </template>\n\n <div\n v-if=\"menu\"\n ref=\"menuEl\"\n v-bind=\"scope\"\n class=\"me-table-controls-ui me-popover me-block-menu me-table-menu\"\n :class=\"{ 'is-above': menu.above }\"\n :style=\"{ left: `${menu.x}px`, top: `${menu.y}px` }\"\n tabindex=\"-1\"\n @keydown=\"onMenuKey\"\n @mousedown.prevent\n >\n <div v-for=\"item in menuItems\" :key=\"item.key\" class=\"me-submenu-anchor\" @mouseenter=\"colorOpen = !!item.submenu\">\n <button\n type=\"button\"\n class=\"me-menu-item\"\n :class=\"{ 'is-danger': item.danger, 'is-active': item.submenu && colorOpen }\"\n :disabled=\"item.disabled\"\n @click=\"item.submenu ? (colorOpen = !colorOpen) : run(item.run!)\"\n >\n <span class=\"me-menu-icon\"><component :is=\"item.icon\" /></span>\n <span class=\"me-menu-title me-menu-text\">{{ item.label }}</span>\n <Check v-if=\"item.checked\" class=\"me-menu-check\" />\n <ChevronRight v-if=\"item.submenu\" class=\"me-menu-chevron\" />\n </button>\n <div v-if=\"item.submenu && colorOpen\" class=\"me-popover me-submenu\">\n <button v-for=\"c in bgColors\" :key=\"c\" type=\"button\" class=\"me-menu-item\" @click=\"run(() => colorSelectedCells(editor, c))\">\n <span class=\"me-menu-icon me-swatch--bg\" :data-color=\"c === 'default' ? undefined : c\">A</span>\n <span class=\"me-menu-title me-menu-text\">{{ colorNames[c] }}</span>\n </button>\n </div>\n </div>\n </div>\n\n <div\n v-if=\"selection && !menu\"\n v-bind=\"scope\"\n class=\"me-table-controls-ui me-popover me-toolbar me-table-toolbar\"\n :style=\"{ left: `${selection.x}px`, top: `${selection.y}px` }\"\n @mousedown.prevent\n >\n <button v-if=\"selection.canMerge\" type=\"button\" class=\"me-tool-btn\" :title=\"m.merge\" @click=\"editor.chain().focus().mergeCells().run()\">\n <TableCellsMerge /> {{ m.merge }}\n </button>\n <button v-if=\"selection.canSplit\" type=\"button\" class=\"me-tool-btn\" :title=\"m.split\" @click=\"editor.chain().focus().splitCell().run()\">\n <TableCellsSplit /> {{ m.split }}\n </button>\n <span class=\"me-submenu-anchor\">\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.color\" @click=\"cellColorOpen = !cellColorOpen\">\n <Palette />\n </button>\n <div v-if=\"cellColorOpen\" class=\"me-popover me-toolbar-panel me-menu\">\n <button v-for=\"c in bgColors\" :key=\"c\" type=\"button\" class=\"me-menu-item\" @click=\"colorSelectedCells(editor, c); cellColorOpen = false\">\n <span class=\"me-menu-icon me-swatch--bg\" :data-color=\"c === 'default' ? undefined : c\">A</span>\n <span class=\"me-menu-title me-menu-text\">{{ colorNames[c] }}</span>\n </button>\n </div>\n </span>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.clear\" @click=\"clearSelectedCells(editor)\">\n <Eraser />\n </button>\n </div>\n </div>\n</template>\n","<script setup lang=\"ts\">\n/**\n * Notion-style table controls, drawn over the editor:\n * - grip handles on the hovered row (left) and column (top) → row/column menu\n * - \"+\" bars below and to the right of the table to add a row / column\n * - a small toolbar for multi-cell selections (merge, split, color, clear)\n */\nimport type { Editor } from '@tiptap/vue-3'\nimport type { Component } from 'vue'\nimport {\n ArrowDown, ArrowDownToLine, ArrowLeft, ArrowLeftToLine, ArrowRight, ArrowRightToLine, ArrowUp, ArrowUpToLine,\n Check, ChevronRight, Copy, Eraser, GripHorizontal, GripVertical, Palette, PanelLeft, PanelTop, Plus,\n TableCellsMerge, TableCellsSplit, Trash,\n} from '@lucide/vue'\nimport { CellSelection } from '@tiptap/pm/tables'\nimport { computed, onBeforeUnmount, onMounted, ref, shallowRef } from 'vue'\nimport { COLORS } from '../colors'\nimport { useClickOutside } from '../composables/useClickOutside'\nimport { useScope } from '../composables/useScope'\nimport {\n clearSelectedCells, colorSelectedCells, deleteColumn, deleteRow, duplicateColumn, duplicateRow, hasHeaderColumn,\n hasHeaderRow, insertColumn, insertRow, moveColumn, moveRow, selectColumn, selectRow, tableAt, type TableRef, toggleHeader,\n} from '../table-ops'\n\nconst props = defineProps<{ editor: Editor }>()\n\nconst scope = useScope(() => props.editor)\nconst m = computed(() => props.editor.storage.meiConfig.messages.table)\nconst colorNames = computed(() => props.editor.storage.meiConfig.messages.colors)\nconst layer = ref<HTMLElement | null>(null)\n\n// --- Hover tracking -----------------------------------------------------------\ninterface Hover { tablePos: number, row: number, col: number, table: DOMRect, visible: DOMRect, rowRect: DOMRect, colRect: DOMRect }\nconst hover = shallowRef<Hover | null>(null)\nlet hideTimer: ReturnType<typeof setTimeout> | undefined\nlet frame = 0\n\n/** Rect relative to the controls layer (which covers the editor root). */\nfunction local(r: DOMRect) {\n const base = layer.value!.getBoundingClientRect()\n return new DOMRect(r.left - base.left, r.top - base.top, r.width, r.height)\n}\n\nfunction locate(cell: HTMLElement): Hover | null {\n const { view } = props.editor\n const tableEl = cell.closest('table')\n const wrapper = cell.closest('.tableWrapper') ?? tableEl\n if (!tableEl || !wrapper || !layer.value) return null\n const $pos = view.state.doc.resolve(view.posAtDOM(cell, 0))\n let depth = $pos.depth\n while (depth > 0 && !['tableCell', 'tableHeader'].includes($pos.node(depth).type.name)) depth--\n if (depth < 2) return null\n const tablePos = $pos.before(depth - 2)\n const t = tableAt(props.editor, tablePos)\n if (!t) return null\n const rect = t.map.findCell($pos.before(depth) - tablePos - 1)\n const tableRect = tableEl.getBoundingClientRect()\n const wrapRect = wrapper.getBoundingClientRect()\n const visible = new DOMRect(tableRect.left, tableRect.top, Math.min(tableRect.right, wrapRect.right) - tableRect.left, tableRect.height)\n return {\n tablePos,\n row: rect.top,\n col: rect.left,\n table: local(tableRect),\n visible: local(visible),\n rowRect: local((cell.parentElement as HTMLElement).getBoundingClientRect()),\n colRect: local(cell.getBoundingClientRect()),\n }\n}\n\nfunction onMouseMove(e: MouseEvent) {\n if (menu.value || !props.editor.isEditable) return\n const target = e.target as HTMLElement | null\n if (target?.closest('.me-table-controls-ui')) {\n clearTimeout(hideTimer)\n return\n }\n cancelAnimationFrame(frame)\n frame = requestAnimationFrame(() => {\n const cell = target?.closest('td, th') as HTMLElement | null\n if (cell && props.editor.view.dom.contains(cell)) {\n clearTimeout(hideTimer)\n hover.value = locate(cell)\n }\n else if (hover.value) {\n clearTimeout(hideTimer)\n hideTimer = setTimeout(() => (hover.value = null), 250)\n }\n })\n}\n\nconst table = computed<TableRef | null>(() => {\n void tick.value\n return hover.value ? tableAt(props.editor, hover.value.tablePos) : null\n})\n\n// Re-read the table after edits (positions and sizes change).\nconst tick = ref(0)\nconst onUpdate = () => {\n tick.value++\n if (hover.value && !tableAt(props.editor, hover.value.tablePos)) hover.value = null\n}\n\n// --- Menus --------------------------------------------------------------------\ninterface Item { key: string, label: string, icon: Component, run?: () => void, checked?: boolean, danger?: boolean, disabled?: boolean, submenu?: boolean }\nconst menu = shallowRef<{ kind: 'row' | 'col', index: number, tablePos: number, x: number, y: number, above: boolean } | null>(null)\nconst colorOpen = ref(false)\nconst menuEl = ref<HTMLElement | null>(null)\nuseClickOutside(menuEl, computed(() => !!menu.value), () => closeMenu())\n\nfunction openMenu(kind: 'row' | 'col', e: MouseEvent) {\n const h = hover.value\n const t = table.value\n if (!h || !t) return\n if (kind === 'row') selectRow(props.editor, t, h.row)\n else selectColumn(props.editor, t, h.col)\n const screen = (e.currentTarget as HTMLElement).getBoundingClientRect()\n const r = local(screen)\n // Open upwards when the handle is in the lower part of the viewport (menu is ~360px tall).\n const above = screen.bottom + 360 > window.innerHeight\n menu.value = { kind, index: kind === 'row' ? h.row : h.col, tablePos: h.tablePos, x: r.left, y: r.bottom + 4, above }\n colorOpen.value = false\n}\n\nfunction closeMenu() {\n menu.value = null\n colorOpen.value = false\n}\n\nfunction run(fn: () => void) {\n fn()\n closeMenu()\n props.editor.commands.focus()\n}\n\nconst menuItems = computed<Item[]>(() => {\n const mn = menu.value\n void tick.value\n const t = mn && tableAt(props.editor, mn.tablePos)\n if (!mn || !t) return []\n const ed = props.editor\n const i = mn.index\n const t2 = m.value\n if (mn.kind === 'row') {\n return [\n ...(i === 0 ? [{ key: 'header', label: t2.headerRow, icon: PanelTop, checked: hasHeaderRow(t), run: () => toggleHeader(ed, t, 'row') }] : []),\n { key: 'above', label: t2.insertAbove, icon: ArrowUpToLine, run: () => insertRow(ed, t, i, 'before') },\n { key: 'below', label: t2.insertBelow, icon: ArrowDownToLine, run: () => insertRow(ed, t, i, 'after') },\n { key: 'dup', label: t2.duplicate, icon: Copy, run: () => duplicateRow(ed, t, i) },\n { key: 'up', label: t2.moveUp, icon: ArrowUp, disabled: i === 0, run: () => moveRow(ed, t, i, i - 1) },\n { key: 'down', label: t2.moveDown, icon: ArrowDown, disabled: i === t.map.height - 1, run: () => moveRow(ed, t, i, i + 1) },\n { key: 'clear', label: t2.clear, icon: Eraser, run: () => clearSelectedCells(ed) },\n { key: 'color', label: t2.color, icon: Palette, submenu: true },\n { key: 'delete', label: t2.deleteRow, icon: Trash, danger: true, run: () => deleteRow(ed, t, i) },\n ]\n }\n return [\n ...(i === 0 ? [{ key: 'header', label: t2.headerColumn, icon: PanelLeft, checked: hasHeaderColumn(t), run: () => toggleHeader(ed, t, 'column') }] : []),\n { key: 'left', label: t2.insertLeft, icon: ArrowLeftToLine, run: () => insertColumn(ed, t, i, 'before') },\n { key: 'right', label: t2.insertRight, icon: ArrowRightToLine, run: () => insertColumn(ed, t, i, 'after') },\n { key: 'dup', label: t2.duplicate, icon: Copy, run: () => duplicateColumn(ed, t, i) },\n { key: 'mleft', label: t2.moveLeft, icon: ArrowLeft, disabled: i === 0, run: () => moveColumn(ed, t, i, i - 1) },\n { key: 'mright', label: t2.moveRight, icon: ArrowRight, disabled: i === t.map.width - 1, run: () => moveColumn(ed, t, i, i + 1) },\n { key: 'clear', label: t2.clear, icon: Eraser, run: () => clearSelectedCells(ed) },\n { key: 'color', label: t2.color, icon: Palette, submenu: true },\n { key: 'delete', label: t2.deleteColumn, icon: Trash, danger: true, run: () => deleteColumn(ed, t, i) },\n ]\n})\n\nfunction onMenuKey(e: KeyboardEvent) {\n if (e.key === 'Escape') closeMenu()\n}\n\n// --- Add row / column -----------------------------------------------------------\nfunction addRow() {\n const t = table.value\n if (t) insertRow(props.editor, t, t.map.height - 1, 'after')\n}\nfunction addColumn() {\n const t = table.value\n if (t) insertColumn(props.editor, t, t.map.width - 1, 'after')\n}\n\n// --- Multi-cell toolbar -------------------------------------------------------------\nconst selection = shallowRef<{ x: number, y: number, canMerge: boolean, canSplit: boolean } | null>(null)\nconst cellColorOpen = ref(false)\nfunction onSelection() {\n const sel = props.editor.state.selection\n if (!(sel instanceof CellSelection) || menu.value || !layer.value) {\n selection.value = null\n cellColorOpen.value = false\n return\n }\n let top = Infinity\n let left = Infinity\n sel.forEachCell((_cell, pos) => {\n const dom = props.editor.view.nodeDOM(pos)\n if (dom instanceof HTMLElement) {\n const r = local(dom.getBoundingClientRect())\n top = Math.min(top, r.top)\n left = Math.min(left, r.left)\n }\n })\n if (!Number.isFinite(top)) return\n selection.value = { x: left, y: top, canMerge: props.editor.can().mergeCells(), canSplit: props.editor.can().splitCell() }\n}\n\nconst bgColors = COLORS\n\nonMounted(() => {\n document.addEventListener('mousemove', onMouseMove)\n props.editor.on('update', onUpdate)\n props.editor.on('selectionUpdate', onSelection)\n})\nonBeforeUnmount(() => {\n document.removeEventListener('mousemove', onMouseMove)\n props.editor.off('update', onUpdate)\n props.editor.off('selectionUpdate', onSelection)\n clearTimeout(hideTimer)\n cancelAnimationFrame(frame)\n})\n</script>\n\n<template>\n <div ref=\"layer\" class=\"me-table-controls\">\n <template v-if=\"hover && table && !menu\">\n <button\n type=\"button\"\n class=\"me-table-controls-ui me-table-grip me-table-grip--row\"\n :style=\"{ left: `${hover.table.left}px`, top: `${hover.rowRect.top}px`, height: `${hover.rowRect.height}px` }\"\n :title=\"m.rowMenu\"\n @mousedown.prevent\n @click=\"openMenu('row', $event)\"\n >\n <GripVertical />\n </button>\n <button\n type=\"button\"\n class=\"me-table-controls-ui me-table-grip me-table-grip--col\"\n :style=\"{ left: `${hover.colRect.left}px`, top: `${hover.table.top}px`, width: `${hover.colRect.width}px` }\"\n :title=\"m.columnMenu\"\n @mousedown.prevent\n @click=\"openMenu('col', $event)\"\n >\n <GripHorizontal />\n </button>\n <button\n type=\"button\"\n class=\"me-table-controls-ui me-table-add me-table-add--row\"\n :style=\"{ left: `${hover.visible.left}px`, top: `${hover.table.top + hover.table.height}px`, width: `${hover.visible.width}px` }\"\n :title=\"m.addRow\"\n @mousedown.prevent\n @click=\"addRow\"\n >\n <Plus />\n </button>\n <button\n type=\"button\"\n class=\"me-table-controls-ui me-table-add me-table-add--col\"\n :style=\"{ left: `${hover.visible.left + hover.visible.width}px`, top: `${hover.table.top}px`, height: `${hover.table.height}px` }\"\n :title=\"m.addColumn\"\n @mousedown.prevent\n @click=\"addColumn\"\n >\n <Plus />\n </button>\n </template>\n\n <div\n v-if=\"menu\"\n ref=\"menuEl\"\n v-bind=\"scope\"\n class=\"me-table-controls-ui me-popover me-block-menu me-table-menu\"\n :class=\"{ 'is-above': menu.above }\"\n :style=\"{ left: `${menu.x}px`, top: `${menu.y}px` }\"\n tabindex=\"-1\"\n @keydown=\"onMenuKey\"\n @mousedown.prevent\n >\n <div v-for=\"item in menuItems\" :key=\"item.key\" class=\"me-submenu-anchor\" @mouseenter=\"colorOpen = !!item.submenu\">\n <button\n type=\"button\"\n class=\"me-menu-item\"\n :class=\"{ 'is-danger': item.danger, 'is-active': item.submenu && colorOpen }\"\n :disabled=\"item.disabled\"\n @click=\"item.submenu ? (colorOpen = !colorOpen) : run(item.run!)\"\n >\n <span class=\"me-menu-icon\"><component :is=\"item.icon\" /></span>\n <span class=\"me-menu-title me-menu-text\">{{ item.label }}</span>\n <Check v-if=\"item.checked\" class=\"me-menu-check\" />\n <ChevronRight v-if=\"item.submenu\" class=\"me-menu-chevron\" />\n </button>\n <div v-if=\"item.submenu && colorOpen\" class=\"me-popover me-submenu\">\n <button v-for=\"c in bgColors\" :key=\"c\" type=\"button\" class=\"me-menu-item\" @click=\"run(() => colorSelectedCells(editor, c))\">\n <span class=\"me-menu-icon me-swatch--bg\" :data-color=\"c === 'default' ? undefined : c\">A</span>\n <span class=\"me-menu-title me-menu-text\">{{ colorNames[c] }}</span>\n </button>\n </div>\n </div>\n </div>\n\n <div\n v-if=\"selection && !menu\"\n v-bind=\"scope\"\n class=\"me-table-controls-ui me-popover me-toolbar me-table-toolbar\"\n :style=\"{ left: `${selection.x}px`, top: `${selection.y}px` }\"\n @mousedown.prevent\n >\n <button v-if=\"selection.canMerge\" type=\"button\" class=\"me-tool-btn\" :title=\"m.merge\" @click=\"editor.chain().focus().mergeCells().run()\">\n <TableCellsMerge /> {{ m.merge }}\n </button>\n <button v-if=\"selection.canSplit\" type=\"button\" class=\"me-tool-btn\" :title=\"m.split\" @click=\"editor.chain().focus().splitCell().run()\">\n <TableCellsSplit /> {{ m.split }}\n </button>\n <span class=\"me-submenu-anchor\">\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.color\" @click=\"cellColorOpen = !cellColorOpen\">\n <Palette />\n </button>\n <div v-if=\"cellColorOpen\" class=\"me-popover me-toolbar-panel me-menu\">\n <button v-for=\"c in bgColors\" :key=\"c\" type=\"button\" class=\"me-menu-item\" @click=\"colorSelectedCells(editor, c); cellColorOpen = false\">\n <span class=\"me-menu-icon me-swatch--bg\" :data-color=\"c === 'default' ? undefined : c\">A</span>\n <span class=\"me-menu-title me-menu-text\">{{ colorNames[c] }}</span>\n </button>\n </div>\n </span>\n <button type=\"button\" class=\"me-tool-btn\" :title=\"m.clear\" @click=\"clearSelectedCells(editor)\">\n <Eraser />\n </button>\n </div>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport type { AnyExtension } from '@tiptap/core'\nimport { Editor, EditorContent, type EditorOptions, type JSONContent } from '@tiptap/vue-3'\nimport { DragHandle } from '@tiptap/extension-drag-handle-vue-3'\nimport type { NestedOptions } from '@tiptap/extension-drag-handle'\nimport type { Node as PMNode } from '@tiptap/pm/model'\nimport type { ComputePositionConfig, Middleware } from '@floating-ui/dom'\nimport { GripVertical, Plus } from '@lucide/vue'\nimport { computed, inject, onBeforeUnmount, onMounted, ref, shallowRef, toRaw, useId, watch, watchEffect } from 'vue'\nimport type { ImageUploader } from '../config'\nimport { createExtensions } from '../extensions'\nimport type { MeiCollaboration } from '../collaboration'\nimport { type BlockRange, currentRange, isBlockSelection, rangeOfBlock, selectBlocks } from '../block-ops'\nimport { handleAnchorRect } from '../handle-anchor'\nimport { kbd } from '../keys'\nimport { type LocaleName, type PartialMessages, resolveMessages } from '../locale'\nimport { GLOBAL_BLOCKS_KEY, GLOBAL_TOKENS_KEY } from '../plugin-key'\nimport { defaultBlocks, text } from '../blocks'\nimport type { BlockDefinition } from '../define-block'\nimport { ContentError, type ContentIssue, sanitizeContent, unwrapUnknown } from '../content'\nimport { assignIds } from '../extensions/block-id'\nimport { injectStyle, installBaseTokens, overridesCss, type ThemeMode, type ThemeTokens } from '../theme'\nimport BlockMenu from './BlockMenu.vue'\nimport FormatMenu from './FormatMenu.vue'\nimport MeiOutline from './MeiOutline.vue'\nimport TableControls from './TableControls.vue'\n\nconst props = withDefaults(defineProps<{\n /** Document as Tiptap JSON. Use with `v-model`. */\n modelValue?: JSONContent | null\n editable?: boolean\n autofocus?: boolean | 'start' | 'end'\n /** Built-in UI language. */\n locale?: LocaleName\n /** Override any UI string, e.g. `{ placeholder: 'Write…' }`. */\n messages?: PartialMessages\n /**\n * Blocks to load (read once, at mount). Defaults to the app-wide list from the\n * Vue plugin / Nuxt module, else `defaultBlocks`.\n */\n blocks?: BlockDefinition[]\n /** Uploads an image and returns its URL. Without it images are stored as base64. */\n uploadImage?: ImageUploader\n /** Max image size in MB. */\n maxImageSize?: number\n /** Extra Tiptap extensions appended to the built-in ones. */\n extensions?: AnyExtension[]\n /** Light / dark mode. `auto` follows `<html class=\"dark\">`. */\n theme?: ThemeMode\n /** Design token overrides for this editor, e.g. `{ color: { accent: '#7c3aed' } }`. */\n tokens?: ThemeTokens\n /** URL for \"Copy link to block\". Default: current page URL + `#<block id>`. */\n blockLink?: (id: string) => string\n /**\n * Floating outline on the right edge (Notion-style). Shown once the page has\n * `minHeadings` headings (default 2). `false` turns it off.\n */\n outline?: boolean | { minHeadings?: number }\n /**\n * Edit a shared Yjs document (read once, at mount). The `Y.Doc` is the source of truth:\n * `modelValue` is ignored and `update:modelValue` is not emitted — listen to `change`\n * (cheap, no payload to serialize) and read the document yourself when needed.\n * Undo / redo become Yjs undo (only your own changes). With `presence` (an awareness + `resolveUser`), remote\n * carets and selections are drawn and the local caret is published (not while read-only).\n */\n collaboration?: MeiCollaboration\n}>(), {\n outline: true,\n theme: 'auto',\n modelValue: null,\n editable: true,\n autofocus: false,\n locale: 'vi',\n maxImageSize: 5,\n})\n\nconst emit = defineEmits<{\n /** Document after each change (not emitted in collaboration mode). */\n 'update:modelValue': [content: JSONContent]\n /**\n * Fired on every document change, local or remote, without serializing it. Debounce\n * your own work (saving, title extraction…) and call `editor.getJSON()` when you need it.\n */\n 'change': [info: { editor: Editor }]\n 'ready': [editor: Editor]\n /**\n * Problems found while loading content. `fatal` means the input isn't a document:\n * the editor turns read-only and stops emitting updates so saved data isn't overwritten.\n */\n 'content-error': [info: { fatal: boolean, issues: ContentIssue[], error?: Error }]\n}>()\n\n/** Set when content couldn't be read at all; blocks editing and updates until fixed. */\nconst contentFailed = ref(false)\n\n// Paragraphs (`text`) are always available; other blocks come from props or app config.\nconst globalBlocks = inject(GLOBAL_BLOCKS_KEY, undefined)\nconst blocks = [text, ...(props.blocks ?? globalBlocks ?? defaultBlocks)]\n .filter((b, i, all) => all.findIndex(o => o.name === b.name) === i)\n\nconst rootEl = ref<HTMLElement | null>(null)\nconst outlineMin = computed(() => (typeof props.outline === 'object' ? props.outline.minHeadings ?? 2 : 2))\nconst hasTables = computed(() => !!editor.value?.schema.nodes.table)\n\nconst messages = computed(() => resolveMessages(props.locale, ...blocks.map(b => b.messages?.[props.locale]), props.messages))\n\n// --- Theme ----------------------------------------------------------------\n// Default tokens are injected once; per-editor overrides go in a <style> scoped by id,\n// and the same scope attrs are copied onto popovers rendered in <body>.\ninstallBaseTokens()\nconst instanceId = `me-${useId()}`\nconst globalTokens = inject(GLOBAL_TOKENS_KEY, undefined)\nconst scope = computed(() => ({\n 'class': ['me-scope', props.theme === 'light' ? 'me-light' : props.theme === 'dark' ? 'me-dark' : ''].filter(Boolean),\n 'data-me-id': instanceId,\n}))\nwatchEffect(() => {\n const css = [\n overridesCss(globalTokens?.value, `.me-scope[data-me-id=\"${instanceId}\"]`),\n overridesCss(props.tokens, `.me-scope[data-me-id=\"${instanceId}\"]`),\n ].filter(Boolean).join('\\n')\n injectStyle(`mei-editor-${instanceId}`, css)\n})\nonBeforeUnmount(() => injectStyle(`mei-editor-${instanceId}`, ''))\n\n/**\n * Validates content (repairing or quarantining broken blocks), wraps unknown block\n * types and assigns missing ids. Never yields a blank doc for bad input: on a fatal\n * error the editor goes read-only and keeps the previous content.\n */\nfunction prepare(doc: JSONContent | null | undefined, ed: { schema: Editor['schema'], extensionManager: Editor['extensionManager'] }): JSONContent | null | undefined {\n const types = ed.extensionManager.extensions.find(e => e.name === 'blockId')?.options.types ?? []\n const issues: ContentIssue[] = []\n try {\n const content = assignIds(sanitizeContent(doc, ed.schema, issues), types)\n contentFailed.value = false\n if (issues.some(i => i.kind !== 'unknown')) {\n console.warn('[MeiEditor] Some blocks were repaired or kept as invalid:', issues)\n emit('content-error', { fatal: false, issues })\n }\n return content\n }\n catch (error) {\n contentFailed.value = true\n console.error('[MeiEditor] Content could not be loaded:', error)\n emit('content-error', { fatal: true, issues, error: error instanceof Error ? error : new ContentError(String(error), doc) })\n return undefined\n }\n}\n\n/** Loads content unless it is unreadable (then the current doc stays, read-only). */\nfunction load(ed: Editor, doc: JSONContent | null | undefined) {\n const content = prepare(doc, ed)\n if (content !== undefined) ed.commands.setContent(content ?? '', { emitUpdate: false })\n ed.setEditable(props.editable && !contentFailed.value)\n}\n\n// The last value we emitted, so an echoed v-model update doesn't reset the doc.\nlet lastEmitted: JSONContent | null = null\n\n// Read once, like `blocks`. With it the Y.Doc owns the content: never setContent / v-model.\nconst collaboration = props.collaboration ? toRaw(props.collaboration) : undefined\n\nconst editor = shallowRef<Editor>()\nlet unmounted = false\n\nfunction createEditor(extra: AnyExtension[]) {\n const options: Partial<EditorOptions> = {\n extensions: [\n ...createExtensions({\n blocks,\n messages: messages.value,\n locale: props.locale,\n uploadImage: props.uploadImage ?? null,\n maxImageSize: props.maxImageSize,\n scope: scope.value,\n // Collaboration brings Yjs undo (Mod-z / Mod-Shift-z); two histories would fight.\n undoRedo: !collaboration,\n }),\n ...extra,\n ...(props.extensions ?? []),\n ],\n content: null,\n editable: props.editable,\n autofocus: props.autofocus,\n editorProps: {\n attributes: { class: 'me-content', spellcheck: 'false' },\n },\n onCreate: ({ editor }) => {\n // Load content after the schema exists, so unknown block types can be wrapped.\n if (!collaboration) load(editor as Editor, toRaw(props.modelValue))\n emit('ready', editor as Editor)\n },\n onUpdate: ({ editor }) => {\n if (contentFailed.value) return\n emit('change', { editor: editor as Editor })\n // getJSON() is O(document): skip it when nobody needs the JSON (collaboration).\n if (collaboration) return\n lastEmitted = unwrapUnknown(editor.getJSON())\n emit('update:modelValue', lastEmitted)\n },\n }\n editor.value = new Editor(options)\n}\n\nonMounted(() => {\n if (!collaboration) {\n createEditor([])\n return\n }\n // Yjs + the sync plugin load only for collaborative editors.\n import('../collaboration').then(({ collaborationExtensions }) => {\n if (!unmounted) createEditor(collaborationExtensions(collaboration))\n }).catch(error => console.error('[MeiEditor] Collaboration could not be loaded:', error))\n})\n\n// Only reload the document for real external changes. `v-model` on a `ref()` hands\n// back a reactive proxy of what we emitted, so compare the raw object, then content.\nwatch(() => props.modelValue, (value) => {\n const ed = editor.value\n const raw = value ? toRaw(value) : null\n if (!ed || collaboration || raw === lastEmitted) return\n if (raw && JSON.stringify(raw) === JSON.stringify(unwrapUnknown(ed.getJSON()))) return\n load(ed, raw)\n})\nwatch(() => props.editable, value => editor.value?.setEditable(value && !contentFailed.value))\nwatch([messages, () => props.locale, () => props.uploadImage, () => props.maxImageSize, scope], () => {\n const config = editor.value?.storage.meiConfig\n if (!config) return\n config.messages = messages.value\n config.locale = props.locale\n config.uploadImage = props.uploadImage ?? null\n config.maxImageSize = props.maxImageSize\n config.scope = scope.value\n})\n\ndefineExpose({ editor })\n\n// --- Drag handle + block menu -------------------------------------------\n// Show the handle for top-level blocks and for blocks directly inside a column\n// (not for list items, table cells, callout children...). On ties the deeper\n// node wins, so inside a column you grab the block, not the whole columns row.\nconst nestedOptions: NestedOptions = {\n defaultRules: false,\n edgeDetection: 'none',\n rules: [{\n id: 'blockLevelOnly',\n evaluate: ({ node, parent }) => {\n if (!parent || node.type.name === 'column') return 1000\n return ['doc', 'column'].includes(parent.type.name) ? 0 : 1000\n },\n }],\n}\n\ninterface HoveredBlock { node: PMNode, pos: number }\nconst hovered = shallowRef<HoveredBlock | null>(null)\nconst menu = shallowRef<{ range: BlockRange, anchor: DOMRect } | null>(null)\n\n// Block under the pointer, for placing the handle (tracked even while a menu is open).\nlet handlePos: number | null = null\n\nfunction onNodeChange({ node, pos }: { node: PMNode | null, pos: number }) {\n handlePos = node ? pos : null\n if (menu.value) return\n hovered.value = node ? { node, pos } : null\n}\n\n/**\n * Centers the handle on the block's anchor line (first text line, header bar, divider…)\n * instead of aligning tops, so it lines up the same way for every block type.\n */\nconst alignHandleToLine: Middleware = {\n name: 'meAlignToLine',\n fn({ y, rects }) {\n const ed = editor.value\n const dom = ed && handlePos !== null ? ed.view.nodeDOM(handlePos) : null\n if (!(dom instanceof HTMLElement)) return {}\n const anchor = handleAnchorRect(dom)\n // Work in the reference's own coordinates: shift by the anchor's offset from the block's top.\n const offset = anchor.top + anchor.height / 2 - dom.getBoundingClientRect().top\n return { y: Number.isFinite(offset) ? rects.reference.y + offset - rects.floating.height / 2 : y }\n },\n}\nconst handlePosition: Partial<ComputePositionConfig> = { placement: 'left-start', strategy: 'absolute', middleware: [alignHandleToLine] }\n\n// Lets the BlockDrop extension take over the drop (see block-drop.ts).\nfunction onDragStart() {\n const config = editor.value?.storage.blockDrop\n if (config) config.active = true\n}\n\nfunction setHandleLocked(locked: boolean) {\n const ed = editor.value\n if (ed && !ed.isDestroyed) ed.view.dispatch(ed.state.tr.setMeta('lockDragHandle', locked))\n}\n\nfunction showMenu(range: BlockRange, anchor: DOMRect) {\n const ed = editor.value\n if (!ed) return\n hideTooltip()\n selectBlocks(ed, range)\n menu.value = { range, anchor }\n setHandleLocked(true)\n}\n\n/** ⋮⋮ click: act on the whole block selection if the block is part of it, else select just this block. */\nfunction openMenu(e: MouseEvent) {\n const ed = editor.value\n if (!ed || !hovered.value) return\n const own = rangeOfBlock({ ...hovered.value, depth: ed.state.doc.resolve(hovered.value.pos).depth })\n const sel = isBlockSelection(ed.state) ? currentRange(ed.state) : null\n const range = sel && own.from >= sel.from && own.to <= sel.to ? sel : own\n showMenu(range, (e.currentTarget as HTMLElement).getBoundingClientRect())\n}\n\n/** ⌘/: open the menu next to the first selected block. */\nfunction openMenuAt(range: BlockRange) {\n const dom = editor.value?.view.nodeDOM(range.from)\n if (!(dom instanceof HTMLElement)) return\n const r = dom.getBoundingClientRect()\n showMenu(range, new DOMRect(r.left, r.top, 0, Math.min(r.height, 24)))\n}\n\n/** Closing keeps the blocks selected (like Notion) so shortcuts keep working. */\nfunction closeMenu() {\n menu.value = null\n setHandleLocked(false)\n editor.value?.view.focus()\n}\n\n// --- Copy link to block ---------------------------------------------------\nconst toast = ref('')\nlet toastTimer: ReturnType<typeof setTimeout> | undefined\nfunction showToast(text: string) {\n toast.value = text\n clearTimeout(toastTimer)\n toastTimer = setTimeout(() => (toast.value = ''), 1800)\n}\nasync function copyLink(id: string) {\n const url = props.blockLink?.(id) ?? `${location.href.split('#')[0]}#${id}`\n try {\n await navigator.clipboard.writeText(url)\n }\n catch {}\n showToast(messages.value.blockMenu.linkCopied)\n}\n\n/** Scroll to and select the block named in the URL hash (target of a copied link). */\nfunction revealHashBlock() {\n const ed = editor.value\n const id = decodeURIComponent(location.hash.slice(1))\n if (!ed || !id) return\n let found: BlockRange | null = null\n ed.state.doc.descendants((node, pos) => {\n if (found) return false\n if (node.attrs.id === id) found = { from: pos, to: pos + node.nodeSize, depth: ed.state.doc.resolve(pos).depth }\n })\n if (!found) return\n selectBlocks(ed, found)\n ;(ed.view.nodeDOM((found as BlockRange).from) as HTMLElement | null)?.scrollIntoView({ block: 'center' })\n}\n\n// --- Handle tooltips --------------------------------------------------------\nconst tooltip = shallowRef<{ lines: [string, string][], hint?: string, rect: DOMRect } | null>(null)\nlet tooltipTimer: ReturnType<typeof setTimeout> | undefined\nfunction showTooltip(e: MouseEvent, kind: 'add' | 'grip') {\n const rect = (e.currentTarget as HTMLElement).getBoundingClientRect()\n const h = messages.value.handle\n const lines: [string, string][] = kind === 'add'\n ? [[h.clickVerb, h.add], [h.altClickVerb, h.addAbove]]\n : [[h.dragVerb, h.drag], [h.clickVerb, h.menu]]\n clearTimeout(tooltipTimer)\n tooltipTimer = setTimeout(() => (tooltip.value = { lines, hint: kind === 'grip' ? kbd('Mod-/') : undefined, rect }), 500)\n}\nfunction hideTooltip() {\n clearTimeout(tooltipTimer)\n tooltip.value = null\n}\n\n/** \"+\" button: add an empty line below the hovered block and open the slash menu. */\nfunction addBlock(e: MouseEvent) {\n const ed = editor.value\n if (!ed || !hovered.value) return\n const { node, pos } = hovered.value\n if (node.type.name === 'paragraph' && node.content.size === 0) {\n ed.chain().focus().setTextSelection(pos + 1).insertContent('/').run()\n return\n }\n // Alt-click inserts above, like Notion.\n const at = e.altKey ? pos : pos + node.nodeSize\n ed.chain()\n .insertContentAt(at, { type: 'paragraph', content: [{ type: 'text', text: '/' }] })\n .setTextSelection(at + 2)\n .focus()\n .run()\n}\n\nfunction focusEnd() {\n const ed = editor.value\n if (!ed || !ed.isEditable) return\n const last = ed.state.doc.lastChild\n if (last?.type.name === 'paragraph' && last.content.size === 0) ed.commands.focus('end')\n else ed.chain().insertContentAt(ed.state.doc.content.size, { type: 'paragraph' }).focus('end').run()\n}\n\nwatch(editor, (ed) => {\n if (!ed) return\n ed.storage.blockSelection.openMenu = openMenuAt\n revealHashBlock()\n}, { immediate: true })\nonMounted(() => window.addEventListener('hashchange', revealHashBlock))\nonBeforeUnmount(() => {\n unmounted = true\n window.removeEventListener('hashchange', revealHashBlock)\n clearTimeout(toastTimer)\n clearTimeout(tooltipTimer)\n editor.value?.destroy()\n})\n</script>\n\n<template>\n <div v-if=\"editor\" ref=\"rootEl\" v-bind=\"scope\" class=\"me-root\">\n <DragHandle\n :editor=\"editor\"\n :nested=\"nestedOptions\"\n :on-node-change=\"onNodeChange\"\n :on-element-drag-start=\"onDragStart\"\n :compute-position-config=\"handlePosition\"\n class=\"me-drag-handle\"\n >\n <div class=\"me-handle\">\n <button type=\"button\" class=\"me-handle-btn\" @click=\"addBlock\" @mouseenter=\"showTooltip($event, 'add')\" @mouseleave=\"hideTooltip\" @mousedown=\"hideTooltip\">\n <Plus />\n </button>\n <button\n type=\"button\"\n class=\"me-handle-btn me-handle-btn--grab\"\n @click=\"openMenu\"\n @mouseenter=\"showTooltip($event, 'grip')\"\n @mouseleave=\"hideTooltip\"\n @mousedown=\"hideTooltip\"\n >\n <GripVertical />\n </button>\n </div>\n </DragHandle>\n\n <!-- Static wrapper: the drag handle plugin moves its own DOM, so conditional siblings need a fixed anchor. -->\n <div class=\"me-content-error-slot\">\n <div v-if=\"contentFailed\" class=\"me-content-error\" role=\"alert\">\n {{ messages.contentError }}\n </div>\n </div>\n <FormatMenu :editor=\"editor\" />\n <EditorContent :editor=\"editor\" />\n <TableControls v-if=\"hasTables && editable\" :editor=\"editor\" />\n <MeiOutline v-if=\"outline\" :editor=\"editor\" :min-headings=\"outlineMin\" :root=\"rootEl\" />\n <div v-if=\"editable\" class=\"me-editor-tail\" @click=\"focusEnd\" />\n\n <BlockMenu\n v-if=\"menu\"\n :editor=\"editor\"\n :range=\"menu.range\"\n :anchor=\"menu.anchor\"\n @close=\"closeMenu\"\n @copy-link=\"copyLink\"\n />\n\n <Teleport to=\"body\">\n <div\n v-if=\"tooltip\"\n v-bind=\"scope\"\n class=\"me-tooltip\"\n :style=\"{ left: `${tooltip.rect.left + tooltip.rect.width / 2}px`, top: `${tooltip.rect.top}px` }\"\n >\n <div v-for=\"[verb, text] in tooltip.lines\" :key=\"verb\">\n <strong class=\"me-tooltip-verb\">{{ verb }}</strong> {{ text }}\n </div>\n <div v-if=\"tooltip.hint\" class=\"me-tooltip-hint\">\n {{ tooltip.hint }}\n </div>\n </div>\n <div v-if=\"toast\" v-bind=\"scope\" class=\"me-toast\">\n {{ toast }}\n </div>\n </Teleport>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport type { AnyExtension } from '@tiptap/core'\nimport { Editor, EditorContent, type EditorOptions, type JSONContent } from '@tiptap/vue-3'\nimport { DragHandle } from '@tiptap/extension-drag-handle-vue-3'\nimport type { NestedOptions } from '@tiptap/extension-drag-handle'\nimport type { Node as PMNode } from '@tiptap/pm/model'\nimport type { ComputePositionConfig, Middleware } from '@floating-ui/dom'\nimport { GripVertical, Plus } from '@lucide/vue'\nimport { computed, inject, onBeforeUnmount, onMounted, ref, shallowRef, toRaw, useId, watch, watchEffect } from 'vue'\nimport type { ImageUploader } from '../config'\nimport { createExtensions } from '../extensions'\nimport type { MeiCollaboration } from '../collaboration'\nimport { type BlockRange, currentRange, isBlockSelection, rangeOfBlock, selectBlocks } from '../block-ops'\nimport { handleAnchorRect } from '../handle-anchor'\nimport { kbd } from '../keys'\nimport { type LocaleName, type PartialMessages, resolveMessages } from '../locale'\nimport { GLOBAL_BLOCKS_KEY, GLOBAL_TOKENS_KEY } from '../plugin-key'\nimport { defaultBlocks, text } from '../blocks'\nimport type { BlockDefinition } from '../define-block'\nimport { ContentError, type ContentIssue, sanitizeContent, unwrapUnknown } from '../content'\nimport { assignIds } from '../extensions/block-id'\nimport { injectStyle, installBaseTokens, overridesCss, type ThemeMode, type ThemeTokens } from '../theme'\nimport BlockMenu from './BlockMenu.vue'\nimport FormatMenu from './FormatMenu.vue'\nimport MeiOutline from './MeiOutline.vue'\nimport TableControls from './TableControls.vue'\n\nconst props = withDefaults(defineProps<{\n /** Document as Tiptap JSON. Use with `v-model`. */\n modelValue?: JSONContent | null\n editable?: boolean\n autofocus?: boolean | 'start' | 'end'\n /** Built-in UI language. */\n locale?: LocaleName\n /** Override any UI string, e.g. `{ placeholder: 'Write…' }`. */\n messages?: PartialMessages\n /**\n * Blocks to load (read once, at mount). Defaults to the app-wide list from the\n * Vue plugin / Nuxt module, else `defaultBlocks`.\n */\n blocks?: BlockDefinition[]\n /** Uploads an image and returns its URL. Without it images are stored as base64. */\n uploadImage?: ImageUploader\n /** Max image size in MB. */\n maxImageSize?: number\n /** Extra Tiptap extensions appended to the built-in ones. */\n extensions?: AnyExtension[]\n /** Light / dark mode. `auto` follows `<html class=\"dark\">`. */\n theme?: ThemeMode\n /** Design token overrides for this editor, e.g. `{ color: { accent: '#7c3aed' } }`. */\n tokens?: ThemeTokens\n /** URL for \"Copy link to block\". Default: current page URL + `#<block id>`. */\n blockLink?: (id: string) => string\n /**\n * Floating outline on the right edge (Notion-style). Shown once the page has\n * `minHeadings` headings (default 2). `false` turns it off.\n */\n outline?: boolean | { minHeadings?: number }\n /**\n * Edit a shared Yjs document (read once, at mount). The `Y.Doc` is the source of truth:\n * `modelValue` is ignored and `update:modelValue` is not emitted — listen to `change`\n * (cheap, no payload to serialize) and read the document yourself when needed.\n * Undo / redo become Yjs undo (only your own changes). With `presence` (an awareness + `resolveUser`), remote\n * carets and selections are drawn and the local caret is published (not while read-only).\n */\n collaboration?: MeiCollaboration\n}>(), {\n outline: true,\n theme: 'auto',\n modelValue: null,\n editable: true,\n autofocus: false,\n locale: 'vi',\n maxImageSize: 5,\n})\n\nconst emit = defineEmits<{\n /** Document after each change (not emitted in collaboration mode). */\n 'update:modelValue': [content: JSONContent]\n /**\n * Fired on every document change, local or remote, without serializing it. Debounce\n * your own work (saving, title extraction…) and call `editor.getJSON()` when you need it.\n */\n 'change': [info: { editor: Editor }]\n 'ready': [editor: Editor]\n /**\n * Problems found while loading content. `fatal` means the input isn't a document:\n * the editor turns read-only and stops emitting updates so saved data isn't overwritten.\n */\n 'content-error': [info: { fatal: boolean, issues: ContentIssue[], error?: Error }]\n}>()\n\n/** Set when content couldn't be read at all; blocks editing and updates until fixed. */\nconst contentFailed = ref(false)\n\n// Paragraphs (`text`) are always available; other blocks come from props or app config.\nconst globalBlocks = inject(GLOBAL_BLOCKS_KEY, undefined)\nconst blocks = [text, ...(props.blocks ?? globalBlocks ?? defaultBlocks)]\n .filter((b, i, all) => all.findIndex(o => o.name === b.name) === i)\n\nconst rootEl = ref<HTMLElement | null>(null)\nconst outlineMin = computed(() => (typeof props.outline === 'object' ? props.outline.minHeadings ?? 2 : 2))\nconst hasTables = computed(() => !!editor.value?.schema.nodes.table)\n\nconst messages = computed(() => resolveMessages(props.locale, ...blocks.map(b => b.messages?.[props.locale]), props.messages))\n\n// --- Theme ----------------------------------------------------------------\n// Default tokens are injected once; per-editor overrides go in a <style> scoped by id,\n// and the same scope attrs are copied onto popovers rendered in <body>.\ninstallBaseTokens()\nconst instanceId = `me-${useId()}`\nconst globalTokens = inject(GLOBAL_TOKENS_KEY, undefined)\nconst scope = computed(() => ({\n 'class': ['me-scope', props.theme === 'light' ? 'me-light' : props.theme === 'dark' ? 'me-dark' : ''].filter(Boolean),\n 'data-me-id': instanceId,\n}))\nwatchEffect(() => {\n const css = [\n overridesCss(globalTokens?.value, `.me-scope[data-me-id=\"${instanceId}\"]`),\n overridesCss(props.tokens, `.me-scope[data-me-id=\"${instanceId}\"]`),\n ].filter(Boolean).join('\\n')\n injectStyle(`mei-editor-${instanceId}`, css)\n})\nonBeforeUnmount(() => injectStyle(`mei-editor-${instanceId}`, ''))\n\n/**\n * Validates content (repairing or quarantining broken blocks), wraps unknown block\n * types and assigns missing ids. Never yields a blank doc for bad input: on a fatal\n * error the editor goes read-only and keeps the previous content.\n */\nfunction prepare(doc: JSONContent | null | undefined, ed: { schema: Editor['schema'], extensionManager: Editor['extensionManager'] }): JSONContent | null | undefined {\n const types = ed.extensionManager.extensions.find(e => e.name === 'blockId')?.options.types ?? []\n const issues: ContentIssue[] = []\n try {\n const content = assignIds(sanitizeContent(doc, ed.schema, issues), types)\n contentFailed.value = false\n if (issues.some(i => i.kind !== 'unknown')) {\n console.warn('[MeiEditor] Some blocks were repaired or kept as invalid:', issues)\n emit('content-error', { fatal: false, issues })\n }\n return content\n }\n catch (error) {\n contentFailed.value = true\n console.error('[MeiEditor] Content could not be loaded:', error)\n emit('content-error', { fatal: true, issues, error: error instanceof Error ? error : new ContentError(String(error), doc) })\n return undefined\n }\n}\n\n/** Loads content unless it is unreadable (then the current doc stays, read-only). */\nfunction load(ed: Editor, doc: JSONContent | null | undefined) {\n const content = prepare(doc, ed)\n if (content !== undefined) ed.commands.setContent(content ?? '', { emitUpdate: false })\n ed.setEditable(props.editable && !contentFailed.value)\n}\n\n// The last value we emitted, so an echoed v-model update doesn't reset the doc.\nlet lastEmitted: JSONContent | null = null\n\n// Read once, like `blocks`. With it the Y.Doc owns the content: never setContent / v-model.\nconst collaboration = props.collaboration ? toRaw(props.collaboration) : undefined\n\nconst editor = shallowRef<Editor>()\nlet unmounted = false\n\nfunction createEditor(extra: AnyExtension[]) {\n const options: Partial<EditorOptions> = {\n extensions: [\n ...createExtensions({\n blocks,\n messages: messages.value,\n locale: props.locale,\n uploadImage: props.uploadImage ?? null,\n maxImageSize: props.maxImageSize,\n scope: scope.value,\n // Collaboration brings Yjs undo (Mod-z / Mod-Shift-z); two histories would fight.\n undoRedo: !collaboration,\n }),\n ...extra,\n ...(props.extensions ?? []),\n ],\n content: null,\n editable: props.editable,\n autofocus: props.autofocus,\n editorProps: {\n attributes: { class: 'me-content', spellcheck: 'false' },\n },\n onCreate: ({ editor }) => {\n // Load content after the schema exists, so unknown block types can be wrapped.\n if (!collaboration) load(editor as Editor, toRaw(props.modelValue))\n emit('ready', editor as Editor)\n },\n onUpdate: ({ editor }) => {\n if (contentFailed.value) return\n emit('change', { editor: editor as Editor })\n // getJSON() is O(document): skip it when nobody needs the JSON (collaboration).\n if (collaboration) return\n lastEmitted = unwrapUnknown(editor.getJSON())\n emit('update:modelValue', lastEmitted)\n },\n }\n editor.value = new Editor(options)\n}\n\nonMounted(() => {\n if (!collaboration) {\n createEditor([])\n return\n }\n // Yjs + the sync plugin load only for collaborative editors.\n import('../collaboration').then(({ collaborationExtensions }) => {\n if (!unmounted) createEditor(collaborationExtensions(collaboration))\n }).catch(error => console.error('[MeiEditor] Collaboration could not be loaded:', error))\n})\n\n// Only reload the document for real external changes. `v-model` on a `ref()` hands\n// back a reactive proxy of what we emitted, so compare the raw object, then content.\nwatch(() => props.modelValue, (value) => {\n const ed = editor.value\n const raw = value ? toRaw(value) : null\n if (!ed || collaboration || raw === lastEmitted) return\n if (raw && JSON.stringify(raw) === JSON.stringify(unwrapUnknown(ed.getJSON()))) return\n load(ed, raw)\n})\nwatch(() => props.editable, value => editor.value?.setEditable(value && !contentFailed.value))\nwatch([messages, () => props.locale, () => props.uploadImage, () => props.maxImageSize, scope], () => {\n const config = editor.value?.storage.meiConfig\n if (!config) return\n config.messages = messages.value\n config.locale = props.locale\n config.uploadImage = props.uploadImage ?? null\n config.maxImageSize = props.maxImageSize\n config.scope = scope.value\n})\n\ndefineExpose({ editor })\n\n// --- Drag handle + block menu -------------------------------------------\n// Show the handle for top-level blocks and for blocks directly inside a column\n// (not for list items, table cells, callout children...). On ties the deeper\n// node wins, so inside a column you grab the block, not the whole columns row.\nconst nestedOptions: NestedOptions = {\n defaultRules: false,\n edgeDetection: 'none',\n rules: [{\n id: 'blockLevelOnly',\n evaluate: ({ node, parent }) => {\n if (!parent || node.type.name === 'column') return 1000\n return ['doc', 'column'].includes(parent.type.name) ? 0 : 1000\n },\n }],\n}\n\ninterface HoveredBlock { node: PMNode, pos: number }\nconst hovered = shallowRef<HoveredBlock | null>(null)\nconst menu = shallowRef<{ range: BlockRange, anchor: DOMRect } | null>(null)\n\n// Block under the pointer, for placing the handle (tracked even while a menu is open).\nlet handlePos: number | null = null\n\nfunction onNodeChange({ node, pos }: { node: PMNode | null, pos: number }) {\n handlePos = node ? pos : null\n if (menu.value) return\n hovered.value = node ? { node, pos } : null\n}\n\n/**\n * Centers the handle on the block's anchor line (first text line, header bar, divider…)\n * instead of aligning tops, so it lines up the same way for every block type.\n */\nconst alignHandleToLine: Middleware = {\n name: 'meAlignToLine',\n fn({ y, rects }) {\n const ed = editor.value\n const dom = ed && handlePos !== null ? ed.view.nodeDOM(handlePos) : null\n if (!(dom instanceof HTMLElement)) return {}\n const anchor = handleAnchorRect(dom)\n // Work in the reference's own coordinates: shift by the anchor's offset from the block's top.\n const offset = anchor.top + anchor.height / 2 - dom.getBoundingClientRect().top\n return { y: Number.isFinite(offset) ? rects.reference.y + offset - rects.floating.height / 2 : y }\n },\n}\nconst handlePosition: Partial<ComputePositionConfig> = { placement: 'left-start', strategy: 'absolute', middleware: [alignHandleToLine] }\n\n// Lets the BlockDrop extension take over the drop (see block-drop.ts).\nfunction onDragStart() {\n const config = editor.value?.storage.blockDrop\n if (config) config.active = true\n}\n\nfunction setHandleLocked(locked: boolean) {\n const ed = editor.value\n if (ed && !ed.isDestroyed) ed.view.dispatch(ed.state.tr.setMeta('lockDragHandle', locked))\n}\n\nfunction showMenu(range: BlockRange, anchor: DOMRect) {\n const ed = editor.value\n if (!ed) return\n hideTooltip()\n selectBlocks(ed, range)\n menu.value = { range, anchor }\n setHandleLocked(true)\n}\n\n/** ⋮⋮ click: act on the whole block selection if the block is part of it, else select just this block. */\nfunction openMenu(e: MouseEvent) {\n const ed = editor.value\n if (!ed || !hovered.value) return\n const own = rangeOfBlock({ ...hovered.value, depth: ed.state.doc.resolve(hovered.value.pos).depth })\n const sel = isBlockSelection(ed.state) ? currentRange(ed.state) : null\n const range = sel && own.from >= sel.from && own.to <= sel.to ? sel : own\n showMenu(range, (e.currentTarget as HTMLElement).getBoundingClientRect())\n}\n\n/** ⌘/: open the menu next to the first selected block. */\nfunction openMenuAt(range: BlockRange) {\n const dom = editor.value?.view.nodeDOM(range.from)\n if (!(dom instanceof HTMLElement)) return\n const r = dom.getBoundingClientRect()\n showMenu(range, new DOMRect(r.left, r.top, 0, Math.min(r.height, 24)))\n}\n\n/** Closing keeps the blocks selected (like Notion) so shortcuts keep working. */\nfunction closeMenu() {\n menu.value = null\n setHandleLocked(false)\n editor.value?.view.focus()\n}\n\n// --- Copy link to block ---------------------------------------------------\nconst toast = ref('')\nlet toastTimer: ReturnType<typeof setTimeout> | undefined\nfunction showToast(text: string) {\n toast.value = text\n clearTimeout(toastTimer)\n toastTimer = setTimeout(() => (toast.value = ''), 1800)\n}\nasync function copyLink(id: string) {\n const url = props.blockLink?.(id) ?? `${location.href.split('#')[0]}#${id}`\n try {\n await navigator.clipboard.writeText(url)\n }\n catch {}\n showToast(messages.value.blockMenu.linkCopied)\n}\n\n/** Scroll to and select the block named in the URL hash (target of a copied link). */\nfunction revealHashBlock() {\n const ed = editor.value\n const id = decodeURIComponent(location.hash.slice(1))\n if (!ed || !id) return\n let found: BlockRange | null = null\n ed.state.doc.descendants((node, pos) => {\n if (found) return false\n if (node.attrs.id === id) found = { from: pos, to: pos + node.nodeSize, depth: ed.state.doc.resolve(pos).depth }\n })\n if (!found) return\n selectBlocks(ed, found)\n ;(ed.view.nodeDOM((found as BlockRange).from) as HTMLElement | null)?.scrollIntoView({ block: 'center' })\n}\n\n// --- Handle tooltips --------------------------------------------------------\nconst tooltip = shallowRef<{ lines: [string, string][], hint?: string, rect: DOMRect } | null>(null)\nlet tooltipTimer: ReturnType<typeof setTimeout> | undefined\nfunction showTooltip(e: MouseEvent, kind: 'add' | 'grip') {\n const rect = (e.currentTarget as HTMLElement).getBoundingClientRect()\n const h = messages.value.handle\n const lines: [string, string][] = kind === 'add'\n ? [[h.clickVerb, h.add], [h.altClickVerb, h.addAbove]]\n : [[h.dragVerb, h.drag], [h.clickVerb, h.menu]]\n clearTimeout(tooltipTimer)\n tooltipTimer = setTimeout(() => (tooltip.value = { lines, hint: kind === 'grip' ? kbd('Mod-/') : undefined, rect }), 500)\n}\nfunction hideTooltip() {\n clearTimeout(tooltipTimer)\n tooltip.value = null\n}\n\n/** \"+\" button: add an empty line below the hovered block and open the slash menu. */\nfunction addBlock(e: MouseEvent) {\n const ed = editor.value\n if (!ed || !hovered.value) return\n const { node, pos } = hovered.value\n if (node.type.name === 'paragraph' && node.content.size === 0) {\n ed.chain().focus().setTextSelection(pos + 1).insertContent('/').run()\n return\n }\n // Alt-click inserts above, like Notion.\n const at = e.altKey ? pos : pos + node.nodeSize\n ed.chain()\n .insertContentAt(at, { type: 'paragraph', content: [{ type: 'text', text: '/' }] })\n .setTextSelection(at + 2)\n .focus()\n .run()\n}\n\nfunction focusEnd() {\n const ed = editor.value\n if (!ed || !ed.isEditable) return\n const last = ed.state.doc.lastChild\n if (last?.type.name === 'paragraph' && last.content.size === 0) ed.commands.focus('end')\n else ed.chain().insertContentAt(ed.state.doc.content.size, { type: 'paragraph' }).focus('end').run()\n}\n\nwatch(editor, (ed) => {\n if (!ed) return\n ed.storage.blockSelection.openMenu = openMenuAt\n revealHashBlock()\n}, { immediate: true })\nonMounted(() => window.addEventListener('hashchange', revealHashBlock))\nonBeforeUnmount(() => {\n unmounted = true\n window.removeEventListener('hashchange', revealHashBlock)\n clearTimeout(toastTimer)\n clearTimeout(tooltipTimer)\n editor.value?.destroy()\n})\n</script>\n\n<template>\n <div v-if=\"editor\" ref=\"rootEl\" v-bind=\"scope\" class=\"me-root\">\n <DragHandle\n :editor=\"editor\"\n :nested=\"nestedOptions\"\n :on-node-change=\"onNodeChange\"\n :on-element-drag-start=\"onDragStart\"\n :compute-position-config=\"handlePosition\"\n class=\"me-drag-handle\"\n >\n <div class=\"me-handle\">\n <button type=\"button\" class=\"me-handle-btn\" @click=\"addBlock\" @mouseenter=\"showTooltip($event, 'add')\" @mouseleave=\"hideTooltip\" @mousedown=\"hideTooltip\">\n <Plus />\n </button>\n <button\n type=\"button\"\n class=\"me-handle-btn me-handle-btn--grab\"\n @click=\"openMenu\"\n @mouseenter=\"showTooltip($event, 'grip')\"\n @mouseleave=\"hideTooltip\"\n @mousedown=\"hideTooltip\"\n >\n <GripVertical />\n </button>\n </div>\n </DragHandle>\n\n <!-- Static wrapper: the drag handle plugin moves its own DOM, so conditional siblings need a fixed anchor. -->\n <div class=\"me-content-error-slot\">\n <div v-if=\"contentFailed\" class=\"me-content-error\" role=\"alert\">\n {{ messages.contentError }}\n </div>\n </div>\n <FormatMenu :editor=\"editor\" />\n <EditorContent :editor=\"editor\" />\n <TableControls v-if=\"hasTables && editable\" :editor=\"editor\" />\n <MeiOutline v-if=\"outline\" :editor=\"editor\" :min-headings=\"outlineMin\" :root=\"rootEl\" />\n <div v-if=\"editable\" class=\"me-editor-tail\" @click=\"focusEnd\" />\n\n <BlockMenu\n v-if=\"menu\"\n :editor=\"editor\"\n :range=\"menu.range\"\n :anchor=\"menu.anchor\"\n @close=\"closeMenu\"\n @copy-link=\"copyLink\"\n />\n\n <Teleport to=\"body\">\n <div\n v-if=\"tooltip\"\n v-bind=\"scope\"\n class=\"me-tooltip\"\n :style=\"{ left: `${tooltip.rect.left + tooltip.rect.width / 2}px`, top: `${tooltip.rect.top}px` }\"\n >\n <div v-for=\"[verb, text] in tooltip.lines\" :key=\"verb\">\n <strong class=\"me-tooltip-verb\">{{ verb }}</strong> {{ text }}\n </div>\n <div v-if=\"tooltip.hint\" class=\"me-tooltip-hint\">\n {{ tooltip.hint }}\n </div>\n </div>\n <div v-if=\"toast\" v-bind=\"scope\" class=\"me-toast\">\n {{ toast }}\n </div>\n </Teleport>\n </div>\n</template>\n","import { type App, type Plugin, ref } from 'vue'\nimport MeiEditor from './components/MeiEditor.vue'\nimport type { BlockDefinition } from './define-block'\nimport { GLOBAL_BLOCKS_KEY, GLOBAL_TOKENS_KEY } from './plugin-key'\nimport type { ThemeTokens } from './theme/tokens'\n\nexport interface MeiEditorPluginOptions {\n /** Global component name. */\n componentName?: string\n /** Token overrides applied to every editor in the app. */\n tokens?: ThemeTokens\n /** Blocks loaded by every editor that has no `blocks` prop. */\n blocks?: BlockDefinition[]\n /** Register <MeiEditor> globally (set false when the Nuxt module already does). */\n component?: boolean\n}\n\n/**\n * Vue plugin that registers <MeiEditor> globally and sets app-wide tokens.\n *\n * @example\n * app.use(MeiEditorPlugin, { tokens: { color: { accent: '#7c3aed' } } })\n */\nexport const MeiEditorPlugin: Plugin<[MeiEditorPluginOptions?]> = {\n install(app: App, options: MeiEditorPluginOptions = {}) {\n if (options.component !== false) app.component(options.componentName ?? 'MeiEditor', MeiEditor)\n app.provide(GLOBAL_TOKENS_KEY, ref(options.tokens))\n if (options.blocks) app.provide(GLOBAL_BLOCKS_KEY, options.blocks)\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,IAAa6mB,KAAYC,GAAU,OAAoD;CACrF,MAAM;CAGN,aAAa;EACX,OAAOC,GAAgB;GACrB,UAAU,KAAK,QAAQ,YAAYvC;GACnC,QAAQ,KAAK,QAAQ,UAAU;GAC/B,OAAO,KAAK,QAAQ,SAAS,CAAC;GAC9B,eAAe,KAAK,QAAQ,iBAAiB,CAAC;GAC9C,aAAa,KAAK,QAAQ,eAAe;GACzC,cAAc,KAAK,QAAQ,gBAAgB;GAC3C,OAAO,KAAK,QAAQ,SAAS;IAAEwC,OAAS,CAAC,UAAU;IAAG,cAAc;GAAG;EACzE,CAAC;CACH;AACF,CAAC;;ACkBD,SAAgBC,EAAsD,GAAwC;CAC5G,IAAMC,KAAS,OAAoC;EACjD,MAAMC,EAAK;EACX;EACA,YAAYA,EAAK,aAAaC,CAAO,KAAK,CAAC;EAC3C,OAAOD,EAAK,QAAQC,CAAO,KAAK,CAAC;EACjC,OAAOD,EAAK,SAAS,CAAC;EACtB,UAAUA,EAAK;EACf,eAAeA,EAAK,gBAAgBC,CAAO;EAC3C,QAAQD,EAAK,SAASC,CAAO;EAC7B,YAAW,MAAaF,EAAM;GA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