zt-react-milkdown 0.1.37 → 0.1.39
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.cjs +6 -6
- package/dist/index.mjs +1380 -1135
- package/dist/src/core/createEditor.d.ts.map +1 -1
- package/dist/src/core/ime-composition-isolation.d.ts +7 -0
- package/dist/src/core/ime-composition-isolation.d.ts.map +1 -0
- package/dist/src/core/markdown-sync.d.ts +30 -0
- package/dist/src/core/markdown-sync.d.ts.map +1 -0
- package/dist/src/plugins/custom/cjk-friendly.d.ts.map +1 -1
- package/dist/src/plugins/custom/code-block/code-block-prism-refresh.d.ts.map +1 -1
- package/dist/src/plugins/custom/heading/index.d.ts +2 -0
- package/dist/src/plugins/custom/heading/index.d.ts.map +1 -1
- package/dist/src/plugins/custom/heading/sync-heading-id.d.ts +5 -0
- package/dist/src/plugins/custom/heading/sync-heading-id.d.ts.map +1 -0
- package/dist/src/plugins/custom/inline-code-boundary-navigation.d.ts.map +1 -1
- package/dist/src/plugins/custom/list/index.d.ts +2 -0
- package/dist/src/plugins/custom/list/index.d.ts.map +1 -1
- package/dist/src/plugins/custom/list/sync-list-order.d.ts +5 -0
- package/dist/src/plugins/custom/list/sync-list-order.d.ts.map +1 -0
- package/dist/src/plugins/custom/search/editor-search.d.ts.map +1 -1
- package/dist/style.css +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require("react");c=s(c,1);let l=require("@milkdown/react"),u=require("clsx");u=s(u,1);let d=require("es-toolkit/function"),f=require("lucide-react"),p=require("class-variance-authority"),m=require("radix-ui"),h=require("tailwind-merge"),g=require("react/jsx-runtime"),_=require("i18next");_=s(_,1);let v=require("@milkdown/prose/state"),y=require("@milkdown/core"),b=require("@milkdown/plugin-clipboard"),x=require("@milkdown/plugin-history"),S=require("@milkdown/plugin-indent"),C=require("@milkdown/preset-commonmark"),w=require("@milkdown/preset-gfm"),T=require("@milkdown/plugin-prism"),E=require("refractor"),D=require("refractor/dart");D=s(D,1);let O=require("refractor/docker");O=s(O,1);let k=require("refractor/graphql");k=s(k,1);let A=require("refractor/groovy");A=s(A,1);let j=require("refractor/jsx");j=s(j,1);let M=require("refractor/mermaid");M=s(M,1);let N=require("refractor/nginx");N=s(N,1);let ee=require("refractor/powershell");ee=s(ee,1);let P=require("refractor/protobuf");P=s(P,1);let te=require("refractor/scala");te=s(te,1);let ne=require("refractor/toml");ne=s(ne,1);let re=require("refractor/tsx");re=s(re,1);let F=require("refractor/zig");F=s(F,1);let I=require("@milkdown/prose/view"),L=require("@milkdown/utils"),ie=require("@milkdown/prose/dropcursor"),R=require("@milkdown/prose/gapcursor"),ae=require("react-dom/client"),z=require("katex");z=s(z,1);let oe=require("@milkdown/prose/inputrules"),se=require("remark-math");se=s(se,1);let ce=require("@milkdown/prose/transform"),le=require("react-dom"),ue=require("remark-frontmatter");ue=s(ue,1);let de=require("@milkdown/plugin-tooltip"),B=require("@milkdown/prose/commands"),fe=require("@milkdown/prose/schema-list"),pe=require("@milkdown/plugin-slash"),me=require("@milkdown/prose/tables"),V=require("prosemirror-search"),he=require("remark-cjk-friendly");he=s(he,1);let ge=require("remark-cjk-friendly-gfm-strikethrough");ge=s(ge,1);function _e(...e){return(0,h.twMerge)((0,u.clsx)(e))}var ve=(0,p.cva)(`group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4`,{variants:{variant:{default:`bg-primary text-primary-foreground [a]:hover:bg-primary/80`,outline:`border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50`,secondary:`bg-secondary text-secondary-foreground hover:bg-secondary/80 aria-expanded:bg-secondary aria-expanded:text-secondary-foreground`,ghost:`hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50`,destructive:`bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40`,link:`text-primary underline-offset-4 hover:underline`},size:{default:`h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2`,xs:`h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3`,sm:`h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5`,lg:`h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2`,icon:`size-8`,"icon-xs":`size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3`,"icon-sm":`size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg`,"icon-lg":`size-9`}},defaultVariants:{variant:`default`,size:`default`}}),H=c.forwardRef(function({className:e,variant:t=`default`,size:n=`default`,asChild:r=!1,...i},a){return(0,g.jsx)(r?m.Slot.Root:`button`,{ref:a,"data-slot":`button`,"data-variant":t,"data-size":n,className:_e(ve({variant:t,size:n,className:e})),...i})}),ye=e=>{let t=e.snapshot.total===0||e.snapshot.isInvalidExpression;return(0,g.jsxs)(`section`,{className:`zt-md-search-panel`,role:`search`,"aria-label":e.messages.searchPanelAriaLabel,children:[(0,g.jsxs)(`div`,{className:`zt-md-search-row zt-md-search-main-row`,children:[e.readOnly?null:(0,g.jsx)(H,{className:`zt-md-search-icon-button zt-md-search-replace-toggle`,type:`button`,variant:`ghost`,size:`icon-sm`,"aria-label":e.messages.searchReplaceLabel,"aria-expanded":e.isReplaceExpanded,title:e.messages.searchReplaceLabel,onClick:e.onReplaceExpandedToggle,children:(0,g.jsx)(f.ChevronRight,{})}),(0,g.jsx)(`input`,{ref:e.searchInputRef,className:`zt-md-search-input`,type:`text`,value:e.options.search,placeholder:e.messages.searchInputPlaceholder,"aria-label":e.messages.searchInputPlaceholder,"aria-invalid":e.snapshot.isInvalidExpression,onChange:t=>{e.onSearchChange(t.target.value)}}),(0,g.jsxs)(`div`,{className:`zt-md-search-options`,role:`group`,"aria-label":e.messages.searchPanelAriaLabel,children:[(0,g.jsx)(H,{className:`zt-md-search-option`,type:`button`,variant:`ghost`,size:`sm`,"aria-pressed":e.options.caseSensitive,"aria-label":e.messages.searchCaseSensitiveLabel,title:e.messages.searchCaseSensitiveLabel,onClick:()=>{e.onOptionToggle(`caseSensitive`)},children:`Aa`}),(0,g.jsx)(H,{className:`zt-md-search-option`,type:`button`,variant:`ghost`,size:`sm`,"aria-pressed":e.options.wholeWord,"aria-label":e.messages.searchWholeWordLabel,title:e.messages.searchWholeWordLabel,onClick:()=>{e.onOptionToggle(`wholeWord`)},children:`W`}),(0,g.jsx)(H,{className:`zt-md-search-option`,type:`button`,variant:`ghost`,size:`sm`,"aria-pressed":e.options.regexp,"aria-label":e.messages.searchRegexpLabel,title:e.messages.searchRegexpLabel,onClick:()=>{e.onOptionToggle(`regexp`)},children:`.*`})]}),(0,g.jsxs)(`output`,{className:`zt-md-search-count`,"aria-live":`polite`,children:[e.snapshot.current,` / `,e.snapshot.total]}),(0,g.jsxs)(`div`,{className:`zt-md-search-navigation`,children:[(0,g.jsxs)(`div`,{className:`zt-md-search-navigation-buttons`,children:[(0,g.jsx)(H,{className:`zt-md-search-icon-button`,type:`button`,variant:`ghost`,size:`icon-sm`,"aria-label":e.messages.searchPreviousAriaLabel,title:e.messages.searchPreviousAriaLabel,disabled:t,onClick:e.onFindPrevious,children:(0,g.jsx)(f.ChevronUp,{})}),(0,g.jsx)(H,{className:`zt-md-search-icon-button`,type:`button`,variant:`ghost`,size:`icon-sm`,"aria-label":e.messages.searchNextAriaLabel,title:e.messages.searchNextAriaLabel,disabled:t,onClick:e.onFindNext,children:(0,g.jsx)(f.ChevronDown,{})})]}),(0,g.jsx)(H,{className:`zt-md-search-icon-button zt-md-search-close-button`,type:`button`,variant:`ghost`,size:`icon-sm`,"aria-label":e.messages.searchCloseAriaLabel,title:e.messages.searchCloseAriaLabel,onClick:e.onClose,children:(0,g.jsx)(f.X,{})})]})]}),e.snapshot.isInvalidExpression?(0,g.jsx)(`span`,{className:`zt-md-search-error`,role:`alert`,children:e.messages.searchInvalidRegexp}):null,!e.readOnly&&e.isReplaceExpanded?(0,g.jsxs)(`div`,{className:`zt-md-search-row zt-md-search-replace-row`,children:[(0,g.jsx)(`input`,{className:`zt-md-search-input`,type:`text`,value:e.options.replace,placeholder:e.messages.searchReplaceInputPlaceholder,"aria-label":e.messages.searchReplaceInputPlaceholder,onChange:t=>{e.onReplaceChange(t.target.value)}}),(0,g.jsx)(H,{className:`zt-md-search-action-button zt-md-search-action-primary`,type:`button`,variant:`default`,size:`sm`,disabled:t,onClick:e.onReplaceCurrent,children:e.messages.searchReplaceLabel}),(0,g.jsx)(H,{className:`zt-md-search-action-button`,type:`button`,variant:`outline`,size:`sm`,disabled:t,onClick:e.onReplaceAll,children:e.messages.searchReplaceAllLabel})]}):null]})},be=e=>typeof e==`string`?e:``,xe=(e,t,n)=>{let r=typeof e==`string`,[i,a]=(0,c.useState)(be(t));return{markdown:(0,c.useMemo)(()=>r?be(e):i,[i,r,e]),setMarkdown:(0,c.useCallback)(e=>{r||a(e),n?.(e)},[r,n]),isControlled:r}},Se={placeholder:`Type / to open the command menu...`,initError:`Editor initialization failed. Please refresh the page and try again.`,editorAriaLabel:`Markdown editor`,searchPanelAriaLabel:`Find and replace in document`,searchInputPlaceholder:`Find in document`,searchReplaceInputPlaceholder:`Replace with`,searchPreviousAriaLabel:`Previous match`,searchNextAriaLabel:`Next match`,searchCloseAriaLabel:`Close search`,searchCaseSensitiveLabel:`Match case`,searchWholeWordLabel:`Match whole word`,searchRegexpLabel:`Use regular expression`,searchReplaceLabel:`Replace`,searchReplaceAllLabel:`Replace all`,searchInvalidRegexp:`Invalid regular expression`,mathBlockSourceAriaLabel:`Math block source`,mathBlockCopyAriaLabel:`Copy math source`,mathBlockDeleteAriaLabel:`Delete math block`,imageDeleteAriaLabel:`Delete image`,tableDeleteAriaLabel:`Delete table`,tableMoreAriaLabel:`More table actions`,tableAlignLeftAriaLabel:`Align current column left`,tableAlignCenterAriaLabel:`Align current column center`,tableAlignRightAriaLabel:`Align current column right`,tableInsertRowAboveLabel:`Insert row above`,tableInsertRowBelowLabel:`Insert row below`,tableInsertColumnLeftLabel:`Insert column left`,tableInsertColumnRightLabel:`Insert column right`,tableDeleteRowLabel:`Delete row`,tableDeleteColumnLabel:`Delete column`,mathRenderError:`Formula rendering failed. Please check the formula syntax.`,imageUploadDialogTitle:`Insert image`,imageUploadDropLabel:`Drop an image here, or choose a file`,imageUploadPickFileLabel:`Choose file`,imageUploadFileTab:`Upload file`,imageUploadUrlTab:`Image URL`,imageUploadUrlPlaceholder:`Paste image URL`,imageUploadInsertUrlLabel:`Insert URL`,imageUploadConfirmLabel:`Insert image`,imageUploadAltLabel:`Alternative text (optional)`,imageUploadAltPlaceholder:`Describe the image`,imageUploadUploadingLabel:`Uploading...`,imageUploadInsertingLabel:`Inserting...`,imageUploadCancelLabel:`Cancel`,imageUploadLoadFailed:`Image failed to load`,imageUploadReselectHint:`Click or drag to reselect`,imageUploadSupportsAndMax:`Supports PNG, JPG, GIF, WebP, SVG, and more, max {size}`,imageUploadFileTooLarge:`The image file is too large.`,imageUploadFileSizeExceeded:`Image size must not exceed {size}`,imageUploadInvalidType:`Please choose an image file.`,imageUploadFailed:`Image upload failed. Please try again.`,imageUploadFileReadFailed:`File read failed. Please try again.`,imageUploadInvalidUrl:`Please enter a valid image URL.`,imageUploadUrlRequired:`Please enter an image URL.`,imageUploadSelectOrEnterImage:`Please select an image or enter an image URL.`,imageUploadUploadingWait:`Image is uploading, please wait.`,selectionTooltipStrongTitle:`Bold`,selectionTooltipEmTitle:`Italic`,selectionTooltipStrikeTitle:`Strikethrough`,selectionTooltipInlineCodeTitle:`Inline code`,selectionTooltipLinkTitle:`Link`,selectionTooltipTransformLabel:`Turn into`,selectionTooltipTransformParagraphLabel:`Paragraph`,selectionTooltipTransformHeading1Label:`Heading 1`,selectionTooltipTransformHeading2Label:`Heading 2`,selectionTooltipTransformHeading3Label:`Heading 3`,selectionTooltipTransformHeading4Label:`Heading 4`,selectionTooltipTransformHeading5Label:`Heading 5`,selectionTooltipTransformHeading6Label:`Heading 6`,selectionTooltipTransformBulletListLabel:`Bullet list`,selectionTooltipTransformOrderedListLabel:`Ordered list`,selectionTooltipTransformTaskListLabel:`Task list`,selectionTooltipTransformBlockquoteLabel:`Blockquote`,selectionTooltipTransformCodeBlockLabel:`Code block`,selectionLinkInputPlaceholder:`Type or paste a link`,selectionLinkSaveAriaLabel:`Save link`,selectionLinkRemoveAriaLabel:`Remove link`,codeBlockLanguageSearchPlaceholder:`Search languages`,codeBlockLanguagePlainText:`text`,codeBlockCopyAriaLabel:`Copy code block`,codeBlockPreviewAriaLabel:`Preview code block`,codeBlockSourceAriaLabel:`View code block source`,codeBlockDeleteAriaLabel:`Delete code block`,frontmatterYamlLabel:`YAML Frontmatter`,frontmatterTomlLabel:`TOML Frontmatter`,frontmatterCollapseAriaLabel:`Collapse frontmatter`,frontmatterExpandAriaLabel:`Expand frontmatter`,frontmatterCopyAriaLabel:`Copy frontmatter`,frontmatterDeleteAriaLabel:`Delete frontmatter`},Ce={placeholder:`请输入 / 打开命令菜单...`,initError:`编辑器初始化失败,请刷新页面后重试。`,editorAriaLabel:`Markdown 编辑器`,searchPanelAriaLabel:`文档搜索与替换`,searchInputPlaceholder:`搜索文档`,searchReplaceInputPlaceholder:`替换为`,searchPreviousAriaLabel:`上一个匹配项`,searchNextAriaLabel:`下一个匹配项`,searchCloseAriaLabel:`关闭搜索`,searchCaseSensitiveLabel:`区分大小写`,searchWholeWordLabel:`全词匹配`,searchRegexpLabel:`使用正则表达式`,searchReplaceLabel:`替换`,searchReplaceAllLabel:`全部替换`,searchInvalidRegexp:`正则表达式无效`,mathBlockSourceAriaLabel:`公式块源码`,mathBlockCopyAriaLabel:`复制公式源码`,mathBlockDeleteAriaLabel:`删除公式块`,imageDeleteAriaLabel:`删除图片`,tableDeleteAriaLabel:`删除表格`,tableMoreAriaLabel:`更多表格操作`,tableAlignLeftAriaLabel:`当前列左对齐`,tableAlignCenterAriaLabel:`当前列居中对齐`,tableAlignRightAriaLabel:`当前列右对齐`,tableInsertRowAboveLabel:`上方插入行`,tableInsertRowBelowLabel:`下方插入行`,tableInsertColumnLeftLabel:`左侧插入列`,tableInsertColumnRightLabel:`右侧插入列`,tableDeleteRowLabel:`删除该行`,tableDeleteColumnLabel:`删除该列`,mathRenderError:`公式渲染失败,请检查公式语法。`,imageUploadDialogTitle:`插入图片`,imageUploadDropLabel:`拖拽图片到这里,或选择文件`,imageUploadPickFileLabel:`选择文件`,imageUploadFileTab:`上传文件`,imageUploadUrlTab:`图片链接`,imageUploadUrlPlaceholder:`粘贴图片链接`,imageUploadInsertUrlLabel:`插入链接`,imageUploadConfirmLabel:`插入图片`,imageUploadAltLabel:`替代文本(可选)`,imageUploadAltPlaceholder:`描述图片内容`,imageUploadUploadingLabel:`上传中...`,imageUploadInsertingLabel:`正在插入...`,imageUploadCancelLabel:`取消`,imageUploadLoadFailed:`图片加载失败`,imageUploadReselectHint:`点击或拖拽重新选择`,imageUploadSupportsAndMax:`支持 PNG、JPG、GIF、WebP、SVG 等,最大 {size}`,imageUploadFileTooLarge:`图片文件过大。`,imageUploadFileSizeExceeded:`图片大小不能超过 {size}`,imageUploadInvalidType:`请选择图片文件。`,imageUploadFailed:`图片上传失败,请重试。`,imageUploadFileReadFailed:`文件读取失败,请重试。`,imageUploadInvalidUrl:`请输入有效的图片链接。`,imageUploadUrlRequired:`请输入图片链接。`,imageUploadSelectOrEnterImage:`请选择图片或输入图片链接。`,imageUploadUploadingWait:`图片正在上传,请稍候。`,selectionTooltipStrongTitle:`加粗`,selectionTooltipEmTitle:`斜体`,selectionTooltipStrikeTitle:`删除线`,selectionTooltipInlineCodeTitle:`行内代码`,selectionTooltipLinkTitle:`链接`,selectionTooltipTransformLabel:`转换为`,selectionTooltipTransformParagraphLabel:`段落`,selectionTooltipTransformHeading1Label:`标题 1`,selectionTooltipTransformHeading2Label:`标题 2`,selectionTooltipTransformHeading3Label:`标题 3`,selectionTooltipTransformHeading4Label:`标题 4`,selectionTooltipTransformHeading5Label:`标题 5`,selectionTooltipTransformHeading6Label:`标题 6`,selectionTooltipTransformBulletListLabel:`无序列表`,selectionTooltipTransformOrderedListLabel:`有序列表`,selectionTooltipTransformTaskListLabel:`任务列表`,selectionTooltipTransformBlockquoteLabel:`引用块`,selectionTooltipTransformCodeBlockLabel:`代码块`,selectionLinkInputPlaceholder:`输入或粘贴链接`,selectionLinkSaveAriaLabel:`保存链接`,selectionLinkRemoveAriaLabel:`移除链接`,codeBlockLanguageSearchPlaceholder:`搜索语言`,codeBlockLanguagePlainText:`text`,codeBlockCopyAriaLabel:`复制代码块`,codeBlockPreviewAriaLabel:`预览代码块`,codeBlockSourceAriaLabel:`查看代码块源码`,codeBlockDeleteAriaLabel:`删除代码块`,frontmatterYamlLabel:`YAML 元数据`,frontmatterTomlLabel:`TOML 元数据`,frontmatterCollapseAriaLabel:`折叠元数据`,frontmatterExpandAriaLabel:`展开元数据`,frontmatterCopyAriaLabel:`复制元数据`,frontmatterDeleteAriaLabel:`删除元数据`},we=`zh-CN`,Te={"zh-CN":{translation:Ce},"en-US":{translation:Se}},Ee=_.default.createInstance(),De=!1,Oe=()=>{De||=(Ee.init({resources:Te,fallbackLng:we,lng:we,interpolation:{escapeValue:!1}}),!0)},U=(e=we,t,n)=>{Oe();let r={...Ee.getResourceBundle(e,`translation`),...t};return n!==void 0&&(r.placeholder=n),r},ke=new WeakMap,W=(e,t)=>{let n=ke.get(e)??new Set;return ke.set(e,n),n.add(t),()=>{n.delete(t)}},Ae=(e,t)=>{Object.keys(t).every(n=>e[n]===t[n])||(Object.assign(e,t),ke.get(e)?.forEach(e=>e()))},je=[j.default,re.default,O.default,ne.default,k.default,ee.default,N.default,M.default,P.default,D.default,te.default,A.default,F.default];function Me(e){e.languages.text={}}Me.displayName=`text`;function Ne(e){je.forEach(t=>{e.registered(t.displayName)||e.register(t)}),e.register(Me)}Ne(E.refractor);var Pe=`code_block`,Fe=new v.PluginKey(`MILKDOWN_PRISM`),Ie=(e,t=[])=>{let n=[];for(let r of e)if(r.type===`element`){let e=Array.isArray(r.properties?.className)?[...t,...r.properties.className.map(String)]:t;n.push(...Ie(r.children,e))}else r.type===`text`&&r.value&&n.push({text:r.value,classNames:t});return n},Le=e=>{let t=[];return e.descendants((e,n)=>e.type.name===Pe?(t.push({pos:n,node:e}),!1):!0),t},Re=(e,t,n)=>{let r=typeof e.node.attrs.language==`string`?e.node.attrs.language:``;if(!r||!n.has(r))return[];let i=e.pos+1,a=[],o=Ie(t.highlight(e.node.textContent,r).children);for(let e of o){let t=i+e.text.length;e.classNames.length>0&&t>i&&a.push(I.Decoration.inline(i,t,{class:e.classNames.join(` `)})),i=t}return a},ze=(e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n].node!==t[n].node)return!1;return!0},Be=(e,t)=>{let n=Math.max(0,Math.min(e.content.size,t)),r=e.resolve(n);for(let e=r.depth;e>=0;--e)if(r.node(e).type.name===Pe)return!0;return!1},Ve=(e,t,n)=>{for(let r=0;r<e.steps.length;r+=1){let i=e.steps[r],a=e.mapping.maps[r],o=[];if(a.forEach((e,t,n,r)=>{o.push([e,t,n,r])}),o.length===0){if(`mark`in i)continue;return!0}let s=r>0?e.mapping.slice(0,r).invert():null,c=r+1<e.mapping.maps.length?e.mapping.slice(r+1):null;for(let[e,r,i,a]of o){let o=s?s.map(e,-1):e,l=s?s.map(r,1):r;for(let e of t){if(e.pos>l)break;if(o<=e.pos+e.node.nodeSize&&l>=e.pos)return!0}let u=Math.max(0,Math.min(n.content.size,c?c.map(i,-1):i)),d=Math.max(u,Math.min(n.content.size,c?c.map(a,1):a));if(u===d){if(Be(n,u))return!0;continue}let f=!1;if(n.nodesBetween(u,d,e=>e.type.name===Pe?(f=!0,!1):!f),f)return!0}}return!1},He=(0,L.$prose)(e=>{let{configureRefractor:t}=e.get(T.prismConfig.key),n=t?.(E.refractor)??E.refractor,r=new Set(n.listLanguages());return new v.Plugin({key:Fe,state:{init:(e,{doc:t})=>{let i=Le(t),a=[];for(let e of i)a.push(...Re(e,n,r));return{decorations:I.DecorationSet.create(t,a),blocks:i}},apply:(e,t,i,a)=>{if(!e.docChanged)return{decorations:t.decorations.map(e.mapping,e.doc),blocks:t.blocks};if(!Ve(e,t.blocks,a.doc)){let n=t.blocks.length===0?t.blocks:t.blocks.map(t=>({pos:e.mapping.map(t.pos,1),node:t.node}));return{decorations:t.decorations.map(e.mapping,e.doc),blocks:n}}let o=Le(a.doc);if(ze(t.blocks,o))return{decorations:t.decorations.map(e.mapping,e.doc),blocks:o};let s=t.decorations.map(e.mapping,e.doc),c=new Set;for(let n of t.blocks){let t=e.mapping.map(n.pos,1);a.doc.nodeAt(t)===n.node&&c.add(t)}let l=[];for(let e of o){if(c.has(e.pos))continue;let t=s.find(e.pos,e.pos+e.node.nodeSize);t.length>0&&(s=s.remove(t)),l.push(...Re(e,n,r))}return l.length>0&&(s=s.add(a.doc,l)),{decorations:s,blocks:o}}},props:{decorations(e){return this.getState(e)?.decorations??I.DecorationSet.empty}}})}),Ue=(e,t)=>typeof e==`function`?n=>{t.action(e(n))}:()=>void 0,G=(e,t,n)=>{if(Array.isArray(n)){n.forEach((n,r)=>{e.push({name:`${t}-${r}`,plugin:n})});return}e.push({name:t,plugin:n})},We=(e,t={})=>{let n=[],r=t.includeRuntime??!0;return e.listener&&G(n,`listener`,e.listener),G(n,`commonmark`,e.commonmark),G(n,`frontmatter`,e.frontmatter),G(n,`task-list-transform-keymap`,e.taskListTransformKeymap),G(n,`inline-code-boundary-navigation`,e.inlineCodeBoundaryNavigation),G(n,`gfm`,e.gfm),G(n,`cjk-friendly`,e.cjkFriendly),G(n,`history`,e.history),G(n,`editor-search`,e.editorSearch),G(n,`code-block-prism`,e.codeBlockPrism),G(n,`code-block-language-picker`,e.codeBlockLanguagePicker),r&&(G(n,`clipboard`,e.clipboard),G(n,`indent`,e.indent)),G(n,`image-delete-selection`,e.imageDeleteSelection),G(n,`image-paste`,e.imagePaste),G(n,`table-arrow-entry`,e.tableArrowEntry),G(n,`block-boundary-navigation`,e.blockBoundaryNavigation),G(n,`heading-backspace-empty-paragraph`,e.headingBackspaceEmptyParagraph),G(n,`heading-focus-indicator`,e.headingFocusIndicator),G(n,`math-backspace-entry`,e.mathBackspaceEntry),G(n,`blockquote-backspace-lift`,e.blockquoteBackspaceLift),G(n,`table-focus-actions`,e.tableFocusActions),G(n,`selection-tooltip`,e.selectionTooltip),G(n,`gap-cursor`,e.gapCursor),G(n,`drop-cursor`,e.dropCursor),G(n,`math`,e.math),G(n,`math-inline-edit`,e.mathInlineEdit),G(n,`math-inline-arrow-navigation`,e.mathInlineArrowNavigation),G(n,`task-list-toggle`,e.taskListToggle),G(n,`tab-space-indent`,e.tabSpaceIndent),G(n,`code-block-mod-a-select`,e.codeBlockModASelect),e.slash&&G(n,`slash`,e.slash),n},Ge=2,Ke=`var(--zt-primary)`,qe=(0,L.$prose)(()=>(0,ie.dropCursor)({color:Ke,width:Ge})),Je=(0,L.$prose)(()=>(0,R.gapCursor)()),Ye=-1,Xe=1,Ze=new Set([`math_block`,`code_block`,`frontmatter`,`table`,`image`,`hr`]),Qe=e=>typeof e.props.editable==`function`?e.props.editable(e.state):e.editable,$e=(e,t,n)=>{let r=e.state.doc.resolve(t);return R.GapCursor.valid(r)?new R.GapCursor(r):v.TextSelection.near(r,n)},et=(e,t)=>t===Ye?e.nodeBefore!==null:e.nodeAfter!==null,tt=(e,t)=>{let n=e.state.schema.nodes.paragraph;if(!n)return!1;let r=e.state.doc.resolve(t),i=r.index();if(!r.parent.canReplaceWith(i,i,n))return!1;let a=n.createAndFill();if(!a)return!1;let o=e.state.tr.insert(t,a),s=t+1;return o.setSelection(v.TextSelection.near(o.doc.resolve(s),1)).scrollIntoView(),e.dispatch(o),e.focus(),!0},nt=(e,t,n,r)=>{if(!Ze.has(n.type.name)||n.type.name===`frontmatter`&&r===Ye)return!1;let i=r===Ye?t:t+n.nodeSize;if(i<0||i>e.state.doc.content.size)return!1;if(!et(e.state.doc.resolve(i),r)&&tt(e,i))return!0;let a=e.state.tr.setSelection($e(e,i,r)).scrollIntoView();return e.dispatch(a),e.focus(),!0},rt=e=>{for(let t=e.depth;t>0;--t){let n=e.node(t);if(Ze.has(n.type.name))return{node:n,position:e.before(t),depth:t}}return null},it=(e,t,n)=>{for(let r=t;r<e.depth;r+=1){let t=e.node(r);if(e.index(r)!==(n===Ye?0:t.childCount-1))return!1}return!0},at=(e,t)=>{let{selection:n}=e.state;if(n instanceof v.NodeSelection)return nt(e,n.from,n.node,t);if(!n.empty)return!1;let r=rt(n.$from);return!r||!it(n.$from,r.depth,t)||!e.endOfTextblock(t===Ye?`up`:`down`)?!1:nt(e,r.position,r.node,t)},ot=e=>{let{doc:t,selection:n}=e.state;return!(n instanceof v.TextSelection)||!n.empty||!(n.$from.after(1)===t.content.size&&it(n.$from,1,Xe))||!e.endOfTextblock(`down`)?!1:tt(e,t.content.size)},st={ArrowUp:e=>at(e,Ye),ArrowDown:e=>at(e,Xe)||ot(e)},ct=(e,t)=>t.defaultPrevented||t.altKey||t.ctrlKey||t.metaKey||t.shiftKey||!Qe(e),lt=(e,t,n,r)=>{let i=r===`ArrowUp`?Ye:r===`ArrowDown`?Xe:null;return i===null||!Qe(e)?!1:nt(e,t,n,i)},ut=(0,L.$prose)(()=>new v.Plugin({key:new v.PluginKey(`zt-md-block-boundary-navigation`),props:{handleKeyDown:(e,t)=>{let n=st[t.key];if(!n||ct(e,t))return!1;let r=n(e);return r&&t.preventDefault(),r}}})),dt={AlignCenter:[[`path`,{d:`M21 5H3`}],[`path`,{d:`M17 12H7`}],[`path`,{d:`M19 19H5`}]],AlignLeft:[[`path`,{d:`M21 5H3`}],[`path`,{d:`M15 12H3`}],[`path`,{d:`M17 19H3`}]],AlignRight:[[`path`,{d:`M21 5H3`}],[`path`,{d:`M21 12H9`}],[`path`,{d:`M21 19H7`}]],Bold:[[`path`,{d:`M6 12h9a4 4 0 0 1 0 8H7a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h7a4 4 0 0 1 0 8`}]],Check:[[`path`,{d:`M20 6 9 17l-5-5`}]],ChevronDown:[[`path`,{d:`m6 9 6 6 6-6`}]],Circle:[[`circle`,{cx:`12`,cy:`12`,r:`10`}]],Code:[[`path`,{d:`m16 18 6-6-6-6`}],[`path`,{d:`m8 6-6 6 6 6`}]],Code2:[[`path`,{d:`m18 16 4-4-4-4`}],[`path`,{d:`m6 8-4 4 4 4`}],[`path`,{d:`m14.5 4-5 16`}]],Copy:[[`rect`,{width:`14`,height:`14`,x:`8`,y:`8`,rx:`2`,ry:`2`}],[`path`,{d:`M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2`}]],Eye:[[`path`,{d:`M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0`}],[`circle`,{cx:`12`,cy:`12`,r:`3`}]],Heading1:[[`path`,{d:`M4 12h8`}],[`path`,{d:`M4 18V6`}],[`path`,{d:`M12 18V6`}],[`path`,{d:`m17 12 3-2v8`}]],Heading2:[[`path`,{d:`M4 12h8`}],[`path`,{d:`M4 18V6`}],[`path`,{d:`M12 18V6`}],[`path`,{d:`M21 18h-4c0-4 4-3 4-6 0-1.5-2-2.5-4-1`}]],Heading3:[[`path`,{d:`M4 12h8`}],[`path`,{d:`M4 18V6`}],[`path`,{d:`M12 18V6`}],[`path`,{d:`M17.5 10.5c1.7-1 3.5 0 3.5 1.5a2 2 0 0 1-2 2`}],[`path`,{d:`M17 17.5c2 1.5 4 .3 4-1.5a2 2 0 0 0-2-2`}]],Heading4:[[`path`,{d:`M12 18V6`}],[`path`,{d:`M17 10v3a1 1 0 0 0 1 1h3`}],[`path`,{d:`M21 10v8`}],[`path`,{d:`M4 12h8`}],[`path`,{d:`M4 18V6`}]],Heading5:[[`path`,{d:`M4 12h8`}],[`path`,{d:`M4 18V6`}],[`path`,{d:`M12 18V6`}],[`path`,{d:`M17 13v-3h4`}],[`path`,{d:`M17 17.7c.4.2.8.3 1.3.3 1.5 0 2.7-1.1 2.7-2.5S19.8 13 18.3 13H17`}]],Heading6:[[`path`,{d:`M4 12h8`}],[`path`,{d:`M4 18V6`}],[`path`,{d:`M12 18V6`}],[`circle`,{cx:`19`,cy:`16`,r:`2`}],[`path`,{d:`M20 10c-2 2-3 3.5-3 6`}]],Image:[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,ry:`2`}],[`circle`,{cx:`9`,cy:`9`,r:`2`}],[`path`,{d:`m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21`}]],ImageOff:[[`line`,{x1:`2`,x2:`22`,y1:`2`,y2:`22`}],[`path`,{d:`M10.41 10.41a2 2 0 1 1-2.83-2.83`}],[`line`,{x1:`13.5`,x2:`6`,y1:`13.5`,y2:`21`}],[`line`,{x1:`18`,x2:`21`,y1:`12`,y2:`15`}],[`path`,{d:`M3.59 3.59A1.99 1.99 0 0 0 3 5v14a2 2 0 0 0 2 2h14c.55 0 1.052-.22 1.41-.59`}],[`path`,{d:`M21 15V5a2 2 0 0 0-2-2H9`}]],Italic:[[`line`,{x1:`19`,x2:`10`,y1:`4`,y2:`4`}],[`line`,{x1:`14`,x2:`5`,y1:`20`,y2:`20`}],[`line`,{x1:`15`,x2:`9`,y1:`4`,y2:`20`}]],List:[[`path`,{d:`M3 5h.01`}],[`path`,{d:`M3 12h.01`}],[`path`,{d:`M3 19h.01`}],[`path`,{d:`M8 5h13`}],[`path`,{d:`M8 12h13`}],[`path`,{d:`M8 19h13`}]],ListOrdered:[[`path`,{d:`M11 5h10`}],[`path`,{d:`M11 12h10`}],[`path`,{d:`M11 19h10`}],[`path`,{d:`M4 4h1v5`}],[`path`,{d:`M4 9h2`}],[`path`,{d:`M6.5 20H3.4c0-1 2.6-1.925 2.6-3.5a1.5 1.5 0 0 0-2.6-1.02`}]],ListTodo:[[`path`,{d:`M13 5h8`}],[`path`,{d:`M13 12h8`}],[`path`,{d:`M13 19h8`}],[`path`,{d:`m3 17 2 2 4-4`}],[`rect`,{x:`3`,y:`4`,width:`6`,height:`6`,rx:`1`}]],Sigma:[[`path`,{d:`M18 7V5a1 1 0 0 0-1-1H6.5a.5.5 0 0 0-.4.8l4.5 6a2 2 0 0 1 0 2.4l-4.5 6a.5.5 0 0 0 .4.8H17a1 1 0 0 0 1-1v-2`}]],SquareCode:[[`path`,{d:`m10 9-3 3 3 3`}],[`path`,{d:`m14 15 3-3-3-3`}],[`rect`,{x:`3`,y:`3`,width:`18`,height:`18`,rx:`2`}]],SquareFunction:[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,ry:`2`}],[`path`,{d:`M9 17c2 0 2.8-1 2.8-2.8V10c0-2 1-3.3 3.2-3`}],[`path`,{d:`M9 11.2h5.7`}]],Strikethrough:[[`path`,{d:`M16 4H9a3 3 0 0 0-2.83 4`}],[`path`,{d:`M14 12a4 4 0 0 1 0 8H6`}],[`line`,{x1:`4`,x2:`20`,y1:`12`,y2:`12`}]],Table:[[`path`,{d:`M12 3v18`}],[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`}],[`path`,{d:`M3 9h18`}],[`path`,{d:`M3 15h18`}]],TextQuote:[[`path`,{d:`M17 5H3`}],[`path`,{d:`M21 12H8`}],[`path`,{d:`M21 19H8`}],[`path`,{d:`M3 12v7`}]],Trash2:[[`path`,{d:`M10 11v6`}],[`path`,{d:`M14 11v6`}],[`path`,{d:`M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6`}],[`path`,{d:`M3 6h18`}],[`path`,{d:`M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2`}]],Type:[[`path`,{d:`M12 4v16`}],[`path`,{d:`M4 7V5a1 1 0 0 1 1-1h14a1 1 0 0 1 1 1v2`}],[`path`,{d:`M9 20h6`}]]},ft=new Map,pt=e=>Object.entries(e).map(([e,t])=>`${e}="${t}"`).join(` `),mt=(e,t)=>e&&Object.prototype.hasOwnProperty.call(dt,e)?e:t,K=(e,t={})=>{let n=t.size??16,r=t.strokeWidth??2,i=t.ariaHidden??!0,a=`${e}:${n}:${r}:${i}`,o=ft.get(a);if(o!==void 0)return o;let s=dt[e].map(([e,t])=>`<${e} ${pt(t)}></${e}>`).join(``),c=`<svg xmlns="http://www.w3.org/2000/svg" width="${n}" height="${n}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="${r}" stroke-linecap="round" stroke-linejoin="round"${i?` aria-hidden="true"`:``}>${s}</svg>`;return ft.set(a,c),c},ht=new Set([`http:`,`https:`,`mailto:`,`tel:`]),gt=new Set([`data:`]),_t=/[\u0000-\u0020\u007f]+/g,vt=/^([a-z][a-z\d+\-.]*:)/i,yt=/[<>"'`]/,bt=new Set([`src`,`alt`,`title`,`style`]),xt=(e,t)=>{if(typeof e!=`string`)return``;let n=e.trim();if(!n||yt.test(n)||/[\u0000-\u001f\u007f]/.test(n))return``;let r=n.replace(_t,``);if(r.startsWith(`//`))return``;let i=r.match(vt)?.[1]?.toLowerCase()??``;if(!i)return n;if(!t.has(i))return``;try{return new URL(n).toString()}catch{return``}},St=e=>xt(e,ht),Ct=(e,t=[])=>xt(e,new Set([...ht,...gt,...t.map(e=>e.trim().toLowerCase())])),wt=(e,t,n=[])=>{if(typeof e!=`string`)return null;let r=e.trim();if(!r)return null;let i=new DOMParser().parseFromString(r,`text/html`),a=null;for(let e of Array.from(i.body.childNodes))if(!(e.nodeType===Node.TEXT_NODE&&!(e.textContent??``).trim())){if(e instanceof HTMLImageElement&&a===null){a=e;continue}return null}if(!a||a.tagName.toLowerCase()!==`img`)return null;for(let e of Array.from(a.attributes))if(!bt.has(e.name.toLowerCase()))return null;let o=Ct(a.getAttribute(`src`)??``,n);return o?{src:o,alt:a.getAttribute(`alt`)??``,title:a.getAttribute(`title`)??``,style:t(a.getAttribute(`style`)??``)}:null},Tt=/^\s*width\s*:\s*(\d{1,3})%\s*;?\s*$/i,Et=(e,t)=>{let n=Array.isArray(e.children)?e.children:[],r=n[0];return n.length===1&&(r?.type===`image`||r?.type===`html`&&wt(r.value,At,t)!==null)?r:null},Dt=e=>Math.min(100,Math.max(10,e)),Ot=e=>`width: ${Dt(Math.round(e))}%;`,kt=e=>{if(typeof e!=`string`)return null;let t=e.match(Tt);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?Dt(n):null},At=e=>{let t=kt(e);return t===null?``:Ot(t)},jt=e=>typeof e==`string`?e.replace(/&/g,`&`).replace(/"/g,`"`).replace(/</g,`<`).replace(/>/g,`>`):``,Mt=(e,t)=>{let n=Ct(e.src,t);if(!n)return``;let r=typeof e.alt==`string`?e.alt:``,i=typeof e.title==`string`?e.title:``,a=i?` title="${jt(i)}"`:``,o=At(e.style);return`<img src="${jt(n)}" alt="${jt(r)}"${a} style="${jt(o)}">`},Nt=(e,t)=>n=>{let r=e(n);return{...r,inline:!1,group:`block`,attrs:{...r.attrs,style:{default:``,validate:`string`}},parseDOM:[{tag:`img[src]`,getAttrs:e=>{let n=e,r=Ct(n.getAttribute(`src`)??``,t);return r?{src:r,alt:n.getAttribute(`alt`)??``,title:n.getAttribute(`title`)??n.getAttribute(`alt`)??``,style:At(n.getAttribute(`style`)??``)}:!1}}],parseMarkdown:{match:e=>e.type===`image`||e.type===`html`&&wt(e.value,At,t)!==null,runner:(e,n,r)=>{if(n.type===`html`){let i=wt(n.value,At,t);i&&e.addNode(r,i);return}let i=Ct(String(n.url??``),t);i&&e.addNode(r,{src:i,alt:String(n.alt??``),title:String(n.title??``),style:``})}},toMarkdown:{match:e=>e.type.name===`image`,runner:(e,n)=>{let r=Ct(n.attrs.src,t);if(!r)return;let i=At(n.attrs.style);if(i){let a=Mt({...n.attrs,src:r,style:i},t);a&&e.addNode(`html`,void 0,a);return}let a={type:`image`,title:n.attrs.title,url:r,alt:n.attrs.alt};e.addNode(`paragraph`,[a])}}}},Pt=(e,t)=>n=>{let r=e(n);return{...r,parseMarkdown:{...r.parseMarkdown,runner:(e,n,i)=>{let a=Et(n,t);if(a){e.next(a);return}r.parseMarkdown.runner(e,n,i)}}}},Ft=(e,t=[])=>{let n=e.get(C.imageSchema.key),r=e.get(C.paragraphSchema.key);e.set(C.imageSchema.key,Nt(n,t)),e.set(C.paragraphSchema.key,Pt(r,t))},It=`image`,Lt=`left`,Rt=`right`,zt=160,Bt=K(`Trash2`,{size:14,strokeWidth:2}),Vt=K(`ImageOff`,{size:14,strokeWidth:2}),Ht=e=>typeof e==`function`?e():null,Ut=e=>typeof e.props.editable==`function`?e.props.editable(e.state):e.editable,Wt=class{constructor(e,t,n,r){this.resizeState=null,this.isSelected=!1,this.currentImageSrc=``,this.imageLoadingStartedAt=0,this.imageLoadingFinishTimer=null,this.handleDeleteClick=e=>{e.preventDefault(),e.stopPropagation(),Ut(this.view)&&this.deleteCurrentImage()},this.handleImageLoad=()=>{delete this.dom.dataset.loadError,this.finishImageLoadingWithMinimumDuration()},this.handleImageError=()=>{this.dom.dataset.loadError=`true`,this.finishImageLoadingWithMinimumDuration()},this.handleResizePointerDown=e=>{if(e.preventDefault(),e.stopPropagation(),!Ut(this.view))return;let t=e.currentTarget;if(!(t instanceof HTMLElement))return;let n=t.dataset.side===Lt?Lt:Rt,r=this.dom.parentElement;if(!r)return;let i=this.imageElement.getBoundingClientRect(),a=r.getBoundingClientRect();if(i.width<=0||a.width<=0)return;let o=Dt(i.width/a.width*100);this.resizeState={side:n,startClientX:e.clientX,startWidth:i.width,containerWidth:a.width,widthPercent:o},this.dom.dataset.resizing=`true`,this.applyPreviewWidth(o),window.addEventListener(`pointermove`,this.handleResizePointerMove),window.addEventListener(`pointerup`,this.handleResizePointerUp),window.addEventListener(`pointercancel`,this.handleResizePointerUp)},this.handleResizePointerMove=e=>{if(!this.resizeState)return;e.preventDefault();let t=e.clientX-this.resizeState.startClientX,n=this.resizeState.side===Lt?-t:t,r=Dt((this.resizeState.startWidth+n)/this.resizeState.containerWidth*100);this.resizeState.widthPercent=r,this.applyPreviewWidth(r)},this.handleResizePointerUp=e=>{if(e.preventDefault(),!this.resizeState)return;let t=Math.round(this.resizeState.widthPercent);this.resizeState=null,delete this.dom.dataset.resizing,this.removeResizeWindowListeners(),this.commitImageWidth(t)},this.node=e,this.view=t,this.getPos=n,this.deleteAriaLabel=r.imageDeleteAriaLabel,this.dom=document.createElement(`span`),this.dom.dataset.type=It,this.dom.className=`zt-md-image`,this.updateEditableState(),this.syncSelectedState(),this.imageElement=document.createElement(`img`),this.imageElement.loading=`lazy`,this.imageElement.decoding=`async`,this.imageElement.addEventListener(`load`,this.handleImageLoad),this.imageElement.addEventListener(`error`,this.handleImageError),this.imageLoadErrorElement=document.createElement(`span`),this.imageLoadErrorElement.className=`zt-md-image-load-error`,this.imageLoadErrorElement.contentEditable=`false`,this.imageLoadErrorElement.innerHTML=Vt,this.imageLoadErrorElement.append(r.imageUploadLoadFailed),this.leftResizeHandle=this.createResizeHandle(Lt),this.rightResizeHandle=this.createResizeHandle(Rt),this.actionsContainer=document.createElement(`span`),this.actionsContainer.className=`zt-md-image-actions`,this.deleteButton=document.createElement(`button`),this.deleteButton.type=`button`,this.deleteButton.className=`zt-md-image-action-button zt-md-image-action-button-danger`,this.deleteButton.setAttribute(`aria-label`,this.deleteAriaLabel),this.deleteButton.innerHTML=Bt,this.actionsContainer.appendChild(this.deleteButton),this.dom.append(this.imageElement,this.imageLoadErrorElement,this.leftResizeHandle,this.rightResizeHandle,this.actionsContainer),this.syncFromNode(e),this.deleteButton.addEventListener(`click`,this.handleDeleteClick),this.leftResizeHandle.addEventListener(`pointerdown`,this.handleResizePointerDown),this.rightResizeHandle.addEventListener(`pointerdown`,this.handleResizePointerDown),this.stopObservingMessages=W(r,()=>{this.deleteButton.setAttribute(`aria-label`,r.imageDeleteAriaLabel);let e=this.imageLoadErrorElement.lastChild;e&&(e.textContent=r.imageUploadLoadFailed)})}createResizeHandle(e){let t=document.createElement(`span`);return t.className=`zt-md-image-resize-handle zt-md-image-resize-handle-${e}`,t.dataset.side=e,t.setAttribute(`aria-hidden`,`true`),t}deleteCurrentImage(){let e=Ht(this.getPos);if(e===null)return;let t=this.view.state.tr.delete(e,e+this.node.nodeSize).scrollIntoView();this.view.dispatch(t),requestAnimationFrame(()=>{this.view.focus()})}updateEditableState(){this.dom.dataset.editable=Ut(this.view)?`true`:`false`}syncSelectedState(){this.dom.dataset.selected=this.isSelected?`true`:`false`}markImageLoading(){this.clearImageLoadingFinishTimer(),this.imageLoadingStartedAt=performance.now(),delete this.dom.dataset.loadError,this.dom.dataset.loading=`true`}finishImageLoading(){this.clearImageLoadingFinishTimer(),delete this.dom.dataset.loading}finishImageLoadingWithMinimumDuration(){let e=performance.now()-this.imageLoadingStartedAt,t=Math.max(0,zt-e);if(t<=0){this.finishImageLoading();return}this.clearImageLoadingFinishTimer(),this.imageLoadingFinishTimer=window.setTimeout(()=>{this.finishImageLoading()},t)}clearImageLoadingFinishTimer(){this.imageLoadingFinishTimer!==null&&(window.clearTimeout(this.imageLoadingFinishTimer),this.imageLoadingFinishTimer=null)}removeResizeWindowListeners(){window.removeEventListener(`pointermove`,this.handleResizePointerMove),window.removeEventListener(`pointerup`,this.handleResizePointerUp),window.removeEventListener(`pointercancel`,this.handleResizePointerUp)}applyPreviewWidth(e){this.dom.style.width=`${Math.round(e)}%`,this.dom.dataset.hasWidth=`true`}commitImageWidth(e){let t=Ht(this.getPos);if(t===null)return;let n={...this.node.attrs,style:Ot(e)},r=this.view.state.tr.setNodeMarkup(t,void 0,n);this.view.dispatch(r),requestAnimationFrame(()=>{this.view.focus()})}syncFromNode(e){this.updateEditableState();let t=typeof e.attrs.src==`string`?e.attrs.src:``,n=typeof e.attrs.alt==`string`?e.attrs.alt:``,r=typeof e.attrs.title==`string`?e.attrs.title:``,i=kt(At(e.attrs.style));t!==this.currentImageSrc&&(delete this.dom.dataset.loadError,t&&this.markImageLoading()),this.imageElement.setAttribute(`src`,t),this.currentImageSrc=t,this.imageElement.setAttribute(`alt`,n),r?this.imageElement.title=r:this.imageElement.removeAttribute(`title`),i===null?(this.dom.style.removeProperty(`width`),delete this.dom.dataset.hasWidth):(this.dom.style.width=`${i}%`,this.dom.dataset.hasWidth=`true`),t?this.imageElement.complete&&this.imageElement.naturalWidth>0&&this.finishImageLoadingWithMinimumDuration():this.finishImageLoading()}update(e){return e.type.name===It?(this.node=e,this.syncFromNode(e),!0):!1}selectNode(){this.isSelected=!0,this.syncSelectedState()}deselectNode(){this.isSelected=!1,this.syncSelectedState()}stopEvent(e){let t=e.target;return t instanceof Node?this.deleteButton.contains(t)||this.leftResizeHandle.contains(t)||this.rightResizeHandle.contains(t)||this.resizeState!==null:!1}ignoreMutation(){return!0}destroy(){this.stopObservingMessages(),this.removeResizeWindowListeners(),this.clearImageLoadingFinishTimer(),this.imageElement.removeEventListener(`load`,this.handleImageLoad),this.imageElement.removeEventListener(`error`,this.handleImageError),this.deleteButton.removeEventListener(`click`,this.handleDeleteClick),this.leftResizeHandle.removeEventListener(`pointerdown`,this.handleResizePointerDown),this.rightResizeHandle.removeEventListener(`pointerdown`,this.handleResizePointerDown)}},Gt=(e=U())=>(t,n,r)=>new Wt(t,n,typeof r==`function`?()=>{let e=r();return typeof e==`number`?e:0}:!1,e),Kt=`image`,qt={Backspace:`before`,Delete:`after`},Jt=e=>typeof e.props.editable==`function`?e.props.editable(e.state):e.editable,Yt=e=>e instanceof Element?!!e.closest(`.zt-md-image-actions, .zt-md-image-resize-handle`):!1,Xt=e=>e?.type.name===Kt,Zt=(e,t)=>!qt[t.key]||t.defaultPrevented||t.altKey||t.ctrlKey||t.metaKey||t.shiftKey||!Jt(e)||Yt(t.target)||Yt(document.activeElement),Qt=e=>{if(e.parent.type.name!==`paragraph`||e.parentOffset!==0||e.parent.textContent.length>0||e.depth<1)return null;let t=e.index(e.depth-1);if(t<=0)return null;let n=e.node(e.depth-1).child(t-1);return Xt(n)?{previousBlockStart:e.before(e.depth)-n.nodeSize}:null},$t=(e,t)=>{try{return v.TextSelection.create(e,t)}catch{return v.TextSelection.near(e.resolve(t),-1)}},en=(e,t,n)=>{n.preventDefault();let r=t.from,i=e.state.tr.delete(t.from,t.to),a=i.doc.content.size,o=Math.min(r,a);return i.setSelection($t(i.doc,o)).scrollIntoView(),e.dispatch(i),e.focus(),!0},tn=(e,t)=>{if(t.key!==`Backspace`)return!1;let{selection:n}=e.state;if(!n.empty)return!1;let r=n.$from,i=Qt(r);if(!i)return!1;let a=r.before(r.depth),o=a+r.parent.nodeSize;t.preventDefault();let s=e.state.tr;return s.delete(a,o),s.setSelection(v.NodeSelection.create(s.doc,i.previousBlockStart)).scrollIntoView(),e.dispatch(s),e.focus(),!0},nn=(e,t)=>{if(tn(e,t))return!0;let n=qt[t.key];if(!n)return!1;let{selection:r}=e.state;if(!r.empty)return!1;let i=r.$from,a=n===`before`?i.nodeBefore:i.nodeAfter;if(!Xt(a))return!1;t.preventDefault();let o=n===`before`?r.from-a.nodeSize:r.from;return e.dispatch(e.state.tr.setSelection(v.NodeSelection.create(e.state.doc,o)).scrollIntoView()),e.focus(),!0},rn=(e,t)=>{if(Zt(e,t))return!1;let{selection:n}=e.state;return n instanceof v.NodeSelection&&Xt(n.node)?en(e,n,t):nn(e,t)},an=(0,L.$prose)(()=>new v.Plugin({key:new v.PluginKey(`zt-md-image-delete-selection`),props:{handleKeyDown:(e,t)=>rn(e,t)}})),on=e=>e.state.schema.nodes.paragraph?.createAndFill()??null,sn=(e,t)=>e.state.schema.nodes.image?.create(t)??null,cn=e=>{let t=e.$to.parent;if(e.$to.parentOffset<t.content.size)return!0;if(e.$to.depth<1)return!1;let n=e.$to.node(e.$to.depth-1);return e.$to.index(e.$to.depth-1)<n.childCount-1},ln=(e,t)=>{let n=[t,t-1,t+1];for(let t of n)if(!(t<0||t>e.content.size)&&e.nodeAt(t)?.type.name===`image`)return t;return null},un=(e,t)=>{let n=e.selection.from-t,r=ln(e.doc,n);return r===null?null:v.NodeSelection.create(e.doc,r)},dn=(e,t,n=e.state.selection)=>{let r=sn(e,t);if(!r)return!1;let i=cn(n),a=e.state.tr.setSelection(n).replaceSelectionWith(r),o=a.selection.to;if(!i){let t=on(e);t&&a.insert(o,t)}let s=un(a,r.nodeSize);return s?(a.setSelection(s).scrollIntoView(),e.dispatch(a),!0):!1},fn=`zt-md-image-upload-file-input`,pn=`zt-md-image-upload-alt-input`,mn=e=>new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let e=r.result;if(typeof e==`string`){t(e);return}n(Error(`Invalid file result`))},r.onerror=()=>{n(r.error??Error(`File read failed`))},r.readAsDataURL(e)}),hn=e=>e<1024*1024?`${Math.ceil(e/1024)}KB`:`${(e/1024/1024).toFixed(1)}MB`,gn=e=>{try{let t=new URL(e);return!!(t.protocol&&t.host)}catch{return!1}},_n=e=>new Promise((t,n)=>{let r=new Image;r.onload=()=>{t()},r.onerror=()=>{n(Error(`Image load failed`))},r.src=e}),vn=e=>e.replace(/\.[^/.]+$/,``),yn=new v.PluginKey(`zt-md-image-paste`),bn=0,xn=e=>(typeof e.props.editable==`function`?e.props.editable(e.state):e.editable)&&!e.state.selection.$from.parent.type.spec.code,Sn=e=>Array.from(e.items).find(e=>e.kind===`file`&&e.type.startsWith(`image/`))?.getAsFile()||(Array.from(e.files).find(e=>e.type.startsWith(`image/`))??null),Cn=()=>(bn+=1,`image-paste-${bn}`),wn=(e,t)=>{let n=new Map;t.forEach((t,r)=>{n.set(r,t.map(e.mapping))});let r=e.getMeta(yn);return r?.type===`add`&&n.set(r.requestId,r.bookmark),r?.type===`remove`&&n.delete(r.requestId),n},Tn=(e,t)=>{e.isDestroyed||!yn.getState(e.state)?.has(t)||e.dispatch(e.state.tr.setMeta(yn,{type:`remove`,requestId:t}))},En=async(e,t,n)=>{let r=t?.upload?await t.upload(e):await mn(e);if(!r)throw Error(n.imageUploadFailed);return r},Dn=async(e,t,n,r,i)=>{try{let a=await En(t,r,i);if(e.isDestroyed)return;let o=yn.getState(e.state)?.get(n);if(!o)return;let s=o.resolve(e.state.doc);Tn(e,n),dn(e,{src:a,alt:vn(t.name),title:``},s)}catch(e){console.error(e)}finally{Tn(e,n)}},On=(e,t)=>(0,L.$prose)(()=>new v.Plugin({key:yn,state:{init:()=>new Map,apply:wn},props:{handlePaste:(n,r)=>{if(!xn(n))return!1;let i=r.clipboardData?Sn(r.clipboardData):null;if(!i)return!1;r.preventDefault();let a=e?.maxFileSize??5242880;if(i.size>a)return console.error(Error(t.imageUploadFileSizeExceeded.replace(`{size}`,hn(a)))),!0;let o=Cn(),s=n.state.selection.getBookmark();return n.dispatch(n.state.tr.setMeta(yn,{type:`add`,requestId:o,bookmark:s})),Dn(n,i,o,e,t),!0}}}));function kn({...e}){return(0,g.jsx)(m.Dialog.Root,{"data-slot":`dialog`,...e})}c.forwardRef(function({...e},t){return(0,g.jsx)(m.Dialog.Trigger,{ref:t,"data-slot":`dialog-trigger`,...e})});function An({container:e,...t}){return(0,g.jsx)(m.Dialog.Portal,{"data-slot":`dialog-portal`,container:e??void 0,...t})}c.forwardRef(function({...e},t){return(0,g.jsx)(m.Dialog.Close,{ref:t,"data-slot":`dialog-close`,...e})});var jn=c.forwardRef(function({className:e,...t},n){return(0,g.jsx)(m.Dialog.Overlay,{ref:n,"data-slot":`dialog-overlay`,className:_e(`fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0`,e),...t})}),Mn=c.forwardRef(function({container:e,className:t,children:n,showCloseButton:r=!0,closeLabel:i=`Close`,...a},o){return(0,g.jsxs)(An,{container:e,children:[(0,g.jsx)(jn,{}),(0,g.jsxs)(m.Dialog.Content,{ref:o,"data-slot":`dialog-content`,className:_e(`fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95`,t),...a,children:[n,r&&(0,g.jsx)(m.Dialog.Close,{"data-slot":`dialog-close`,asChild:!0,children:(0,g.jsxs)(H,{variant:`ghost`,className:`absolute top-2 right-2`,size:`icon-sm`,children:[(0,g.jsx)(f.XIcon,{}),(0,g.jsx)(`span`,{className:`sr-only`,children:i})]})})]})]})});function Nn({className:e,...t}){return(0,g.jsx)(`div`,{"data-slot":`dialog-header`,className:_e(`flex flex-col gap-2`,e),...t})}function Pn({className:e,showCloseButton:t=!1,children:n,...r}){return(0,g.jsxs)(`div`,{"data-slot":`dialog-footer`,className:_e(`-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end`,e),...r,children:[n,t&&(0,g.jsx)(m.Dialog.Close,{asChild:!0,children:(0,g.jsx)(H,{variant:`outline`,children:`Close`})})]})}var Fn=c.forwardRef(function({className:e,...t},n){return(0,g.jsx)(m.Dialog.Title,{ref:n,"data-slot":`dialog-title`,className:_e(`text-base leading-none font-medium`,e),...t})}),In=c.forwardRef(function({className:e,...t},n){return(0,g.jsx)(m.Dialog.Description,{ref:n,"data-slot":`dialog-description`,className:_e(`text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground`,e),...t})}),Ln=({messages:e,portalContainer:t,imageUpload:n,onConfirm:r,onCancel:i})=>{let[a,o]=(0,c.useState)(`file`),[s,l]=(0,c.useState)(``),[u,d]=(0,c.useState)(``),[p,m]=(0,c.useState)(!1),[h,_]=(0,c.useState)(null),[v,y]=(0,c.useState)(!1),[b,x]=(0,c.useState)(!1),[S,C]=(0,c.useState)(!1),w=(0,c.useRef)(null),T=(0,c.useRef)(null),E=(0,c.useRef)(!0),D=n?.maxFileSize??5242880,O=v||b,k=a===`file`&&!!s&&!O,A=(h?`key`in h?e[h.key].replace(`{size}`,hn(D)):h.text:``)||(k?e.imageUploadReselectHint:``),j=!!h,M=!!A,N=!!s&&!h&&!v&&!p,ee=!s||!!h||O||p,P=(0,c.useCallback)(async e=>{if(!e.type.startsWith(`image/`)){l(``),d(``),_({key:`imageUploadInvalidType`});return}if(e.size>D){l(``),d(``),_({key:`imageUploadFileSizeExceeded`});return}_(null),d(vn(e.name)),m(!1),y(!0);try{let t=n?.upload?await n.upload(e):await mn(e);if(!E.current)return;if(!t){l(``),_({key:`imageUploadFailed`});return}l(t)}catch(e){if(!E.current)return;let t=n?.upload&&e instanceof Error?e.message:``,r=n?.upload?`imageUploadFailed`:`imageUploadFileReadFailed`;l(``),_(t?{text:t}:{key:r})}finally{E.current&&y(!1)}},[n,D]),te=(0,c.useCallback)(()=>{let e=w.current?.files?.[0];e&&(P(e),w.current.value=``)},[P]),ne=(0,c.useCallback)(e=>{if(m(!1),l(e),!e){_(null);return}_(gn(e)?null:{key:`imageUploadInvalidUrl`})},[]),re=(0,c.useCallback)(e=>{e.preventDefault(),e.stopPropagation(),!O&&(e.dataTransfer.dropEffect=`copy`,C(!0))},[O]),F=(0,c.useCallback)(e=>{e.preventDefault(),e.stopPropagation(),e.currentTarget.contains(e.relatedTarget)||C(!1)},[]),I=(0,c.useCallback)(e=>{if(e.preventDefault(),e.stopPropagation(),C(!1),O)return;let t=e.dataTransfer.files?.[0];t&&P(t)},[O,P]),L=(0,c.useCallback)(e=>{O||(o(e),l(``),d(``),m(!1),_(null))},[O]),ie=(0,c.useCallback)(async()=>{if(O){_({key:`imageUploadUploadingWait`});return}if(!s){_({key:`imageUploadSelectOrEnterImage`});return}if(a===`url`&&!gn(s)){_({key:`imageUploadInvalidUrl`});return}_(null),x(!0);try{if(await _n(s),!E.current)return;r({src:s,alt:u.trim()})}catch{E.current&&(m(!0),_({key:`imageUploadLoadFailed`}))}finally{E.current&&x(!1)}},[u,s,O,r,a]),R=(0,c.useCallback)(e=>{e.key===`Enter`&&!e.shiftKey&&a===`url`&&(e.preventDefault(),ie())},[ie,a]);return(0,c.useEffect)(()=>(E.current=!0,()=>{E.current=!1}),[]),(0,c.useEffect)(()=>{a===`url`&&T.current?.focus()},[a]),(0,g.jsx)(kn,{open:!0,onOpenChange:e=>!e&&i(),children:(0,g.jsxs)(Mn,{container:t,className:`zt-md-image-upload-content-shell max-w-2xl sm:!max-w-2xl max-h-[90vh] overflow-hidden flex flex-col`,closeLabel:e.imageUploadCancelLabel,onCloseAutoFocus:e=>e.preventDefault(),onMouseDown:e=>e.stopPropagation(),onKeyDown:R,children:[(0,g.jsxs)(Nn,{children:[(0,g.jsx)(Fn,{children:e.imageUploadDialogTitle}),(0,g.jsx)(In,{className:`sr-only`,children:`${e.imageUploadFileTab},${e.imageUploadUrlTab}`})]}),(0,g.jsxs)(`div`,{className:`zt-md-image-upload-segmented`,role:`group`,"aria-label":e.imageUploadDialogTitle,children:[(0,g.jsx)(H,{type:`button`,variant:`ghost`,className:`zt-md-image-upload-segment`,"data-active":a===`file`?`true`:`false`,"aria-pressed":a===`file`,disabled:O,onClick:()=>L(`file`),children:e.imageUploadFileTab}),(0,g.jsx)(H,{type:`button`,variant:`ghost`,className:`zt-md-image-upload-segment`,"data-active":a===`url`?`true`:`false`,"aria-pressed":a===`url`,disabled:O,onClick:()=>L(`url`),children:e.imageUploadUrlTab})]}),(0,g.jsx)(`div`,{className:`zt-md-image-upload-content`,children:(0,g.jsxs)(`div`,{className:`zt-md-image-upload-control`,children:[a===`file`?(0,g.jsxs)(`div`,{className:`zt-md-image-upload-file`,children:[(0,g.jsx)(`input`,{ref:w,id:fn,type:`file`,accept:`image/*`,className:`zt-md-image-upload-file-input`,disabled:O,onChange:te}),(0,g.jsx)(`label`,{htmlFor:fn,className:`zt-md-image-upload-file-label`,"data-drag-over":S?`true`:`false`,"data-has-preview":s?`true`:`false`,"data-disabled":O?`true`:`false`,"aria-disabled":O,onClick:e=>{O&&e.preventDefault()},onDragOver:re,onDragLeave:F,onDrop:I,children:v?(0,g.jsxs)(g.Fragment,{children:[(0,g.jsx)(`div`,{className:`zt-md-image-upload-file-icon`,children:(0,g.jsx)(f.Loader2,{size:40,className:`zt-md-image-upload-spin`})}),(0,g.jsx)(`div`,{className:`zt-md-image-upload-file-text`,children:e.imageUploadUploadingLabel})]}):s?(0,g.jsx)(`div`,{className:`zt-md-image-upload-file-preview`,children:p?(0,g.jsxs)(`div`,{className:`zt-md-image-upload-preview-error`,children:[(0,g.jsx)(f.ImageOff,{size:40}),(0,g.jsx)(`span`,{children:e.imageUploadLoadFailed})]}):(0,g.jsx)(`img`,{src:s,alt:``,onLoad:()=>m(!1),onError:()=>m(!0)})}):(0,g.jsxs)(g.Fragment,{children:[(0,g.jsx)(`div`,{className:`zt-md-image-upload-file-icon`,children:(0,g.jsx)(f.ImagePlus,{size:40})}),(0,g.jsx)(`div`,{className:`zt-md-image-upload-file-text`,children:e.imageUploadDropLabel}),(0,g.jsx)(`div`,{className:`zt-md-image-upload-file-hint`,children:e.imageUploadSupportsAndMax.replace(`{size}`,hn(D))})]})})]}):(0,g.jsxs)(`div`,{className:`zt-md-image-upload-url`,children:[(0,g.jsx)(`label`,{className:`zt-md-image-upload-label`,htmlFor:`zt-md-image-upload-url-input`,children:e.imageUploadUrlTab}),(0,g.jsx)(`input`,{ref:T,id:`zt-md-image-upload-url-input`,type:`url`,className:`zt-md-image-upload-url-input`,placeholder:e.imageUploadUrlPlaceholder,value:s,disabled:O,onChange:e=>ne(e.target.value)}),s&&!h?(0,g.jsx)(`div`,{className:`zt-md-image-upload-url-preview`,children:p?(0,g.jsxs)(`div`,{className:`zt-md-image-upload-preview-error`,children:[(0,g.jsx)(f.ImageOff,{size:32}),(0,g.jsx)(`span`,{children:e.imageUploadLoadFailed})]}):(0,g.jsx)(`img`,{src:s,alt:``,onLoad:()=>m(!1),onError:()=>m(!0)})}):null]}),N?(0,g.jsxs)(`div`,{className:`zt-md-image-upload-alt`,children:[(0,g.jsx)(`label`,{className:`zt-md-image-upload-label`,htmlFor:pn,children:e.imageUploadAltLabel}),(0,g.jsx)(`input`,{id:pn,type:`text`,className:`zt-md-image-upload-alt-input`,placeholder:e.imageUploadAltPlaceholder,value:u,disabled:O,onChange:e=>d(e.target.value)})]}):null,(0,g.jsxs)(`div`,{className:`zt-md-image-upload-file-hint zt-md-image-upload-reselect-hint`,"data-error":j?`true`:`false`,"data-placeholder":M?`false`:`true`,role:j?`alert`:void 0,"aria-live":j?`polite`:`off`,"aria-hidden":!M,children:[j?(0,g.jsx)(f.AlertCircle,{size:14,className:`zt-md-image-upload-hint-icon`}):null,(0,g.jsx)(`span`,{className:`zt-md-image-upload-hint-text`,children:A||e.imageUploadReselectHint})]})]})}),(0,g.jsxs)(Pn,{children:[(0,g.jsx)(H,{type:`button`,variant:`outline`,onClick:i,children:e.imageUploadCancelLabel}),(0,g.jsx)(H,{type:`button`,disabled:ee,onClick:()=>{ie()},children:v?e.imageUploadUploadingLabel:b?e.imageUploadInsertingLabel:e.imageUploadConfirmLabel})]})]})})},Rn=[`--zt-font`,`--zt-font-mono`,`--zt-bg`,`--zt-surface`,`--zt-elevated`,`--zt-popover`,`--zt-hover`,`--zt-active`,`--zt-control-active`,`--zt-fg`,`--zt-muted`,`--zt-border`,`--zt-border-strong`,`--zt-primary`,`--zt-primary-foreground`,`--zt-secondary`,`--zt-accent`,`--zt-destructive`,`--zt-destructive-foreground`,`--zt-overlay`,`--zt-shadow-sm`,`--zt-shadow-md`,`--zt-shadow-lg`,`--zt-radius`,`--zt-radius-lg`],zn=(e,t)=>{if(!t)return;let n=window.getComputedStyle(t);Rn.forEach(t=>{let r=n.getPropertyValue(t);r&&e.style.setProperty(t,r.trim())})},Bn=(e,t)=>{let n=e.closest(`.zt-md`),r=n?.classList.contains(`zt-md-dark`)?`zt-md-dark`:`zt-md-light`,i=document.createElement(`div`);return i.className=`zt-md zt-md-dialog-host ${t} ${r}`,zn(i,n),document.body.appendChild(i),i},Vn=e=>{let t=Bn(e.portalContainer,`zt-md-image-upload-host`),n=(0,ae.createRoot)(t),r=e=>{o(),queueMicrotask(()=>{n.unmount(),t.remove(),e?.()})},i=()=>{r(()=>{e.view?.focus?.()})},a=()=>{n.render((0,c.createElement)(Ln,{messages:{...e.messages},portalContainer:t,imageUpload:e.imageUpload,onConfirm:t=>{let n=dn(e.view,{src:t.src,alt:t.alt,title:``});r(()=>{n&&e.view?.focus?.()})},onCancel:i}))},o=W(e.messages,a);a()},Hn=`math_block`,Un=`Backspace`,Wn=e=>e.key!==Un||e.defaultPrevented||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey,Gn=e=>{if(e.parent.type.name!==`paragraph`||e.parentOffset!==0||e.depth<1)return null;let t=e.index(e.depth-1);if(t<=0)return null;let n=e.node(e.depth-1).child(t-1);return n.type.name===Hn?{previousBlock:n,previousBlockStart:e.before(e.depth)-n.nodeSize}:null},Kn=(e,t)=>{let{selection:n}=e.state;if(!n.empty)return!1;let r=n.$from,i=Gn(r);if(!i)return!1;let a=r.parent.textContent.length===0,o=r.before(r.depth),s=o+r.parent.nodeSize;t.preventDefault();let c=e.state.tr;return a&&c.delete(o,s),c.setSelection(v.NodeSelection.create(c.doc,i.previousBlockStart)).scrollIntoView(),e.dispatch(c),!0},qn=(0,L.$prose)(()=>new v.Plugin({key:new v.PluginKey(`zt-md-math-backspace-entry`),props:{handleKeyDown:(e,t)=>Wn(t)?!1:Kn(e,t)}})),Jn=`math_block`,Yn=5,Xn=1200,Zn=K(`Copy`,{size:14,strokeWidth:2}),Qn=K(`Check`,{size:14,strokeWidth:2}),$n=K(`Trash2`,{size:14,strokeWidth:2}),er=e=>typeof e==`function`?e():null,tr=e=>typeof e.props.editable==`function`?e.props.editable(e.state):e.editable,nr=class{syncEditableState(){this.dom.dataset.editable=tr(this.view)?`true`:`false`}constructor(e,t,n,r){this.pointerStartX=null,this.pointerStartY=null,this.hasDragged=!1,this.isDeletingByBackspace=!1,this.copyFeedbackTimer=null,this.handleClick=()=>{if(this.hasDragged){this.hasDragged=!1;return}this.enterEditMode()},this.handlePointerDown=e=>{this.pointerStartX=e.clientX,this.pointerStartY=e.clientY,this.hasDragged=!1},this.handlePointerMove=e=>{if(this.pointerStartX===null||this.pointerStartY===null)return;let t=Math.abs(e.clientX-this.pointerStartX),n=Math.abs(e.clientY-this.pointerStartY);(t>=Yn||n>=Yn)&&(this.hasDragged=!0)},this.handlePointerUp=()=>{this.pointerStartX=null,this.pointerStartY=null},this.handleCopyClick=e=>{if(e.preventDefault(),e.stopPropagation(),!tr(this.view))return;let t=typeof this.node.attrs.value==`string`?this.node.attrs.value:``;(typeof navigator<`u`&&navigator.clipboard?.writeText?navigator.clipboard.writeText(t):Promise.resolve()).then(()=>{this.copyButton.innerHTML=Qn,this.copyButton.dataset.copied=`true`,this.copyFeedbackTimer!==null&&clearTimeout(this.copyFeedbackTimer),this.copyFeedbackTimer=setTimeout(()=>{this.copyButton.innerHTML=Zn,delete this.copyButton.dataset.copied,this.copyFeedbackTimer=null},Xn)}).catch(()=>{})},this.handleDeleteClick=e=>{e.preventDefault(),e.stopPropagation(),tr(this.view)&&this.deleteCurrentMathBlock()},this.handleInput=()=>{let e=this.sourceTextarea.value,t=er(this.getPos);if(t===null)return;this.renderMath(e);let n=this.view.state.tr.setNodeMarkup(t,void 0,{...this.node.attrs,value:e});n.docChanged&&this.view.dispatch(n)},this.handleKeyDown=e=>{let t=this.sourceTextarea.selectionStart,n=this.sourceTextarea.selectionEnd;if(e.key===`Backspace`){if(!(t===0&&n===0)||er(this.getPos)===null)return;e.preventDefault(),this.deleteCurrentMathBlock();return}if(e.key!==`ArrowUp`&&e.key!==`ArrowDown`||e.defaultPrevented||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey||t!==n)return;let r=this.sourceTextarea.value,i=r.slice(0,t),a=r.slice(n),o=!i.includes(`
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require("react");c=s(c,1);let l=require("@milkdown/react"),u=require("clsx");u=s(u,1);let d=require("es-toolkit/function"),f=require("lucide-react"),p=require("class-variance-authority"),m=require("radix-ui"),h=require("tailwind-merge"),g=require("react/jsx-runtime"),_=require("i18next");_=s(_,1);let v=require("@milkdown/prose/state"),y=require("@milkdown/core"),b=require("@milkdown/plugin-clipboard"),x=require("@milkdown/plugin-history"),S=require("@milkdown/plugin-indent"),C=require("@milkdown/preset-commonmark"),w=require("@milkdown/preset-gfm"),T=require("@milkdown/plugin-prism"),E=require("refractor"),D=require("refractor/dart");D=s(D,1);let O=require("refractor/docker");O=s(O,1);let k=require("refractor/graphql");k=s(k,1);let A=require("refractor/groovy");A=s(A,1);let j=require("refractor/jsx");j=s(j,1);let M=require("refractor/mermaid");M=s(M,1);let N=require("refractor/nginx");N=s(N,1);let ee=require("refractor/powershell");ee=s(ee,1);let P=require("refractor/protobuf");P=s(P,1);let te=require("refractor/scala");te=s(te,1);let ne=require("refractor/toml");ne=s(ne,1);let re=require("refractor/tsx");re=s(re,1);let ie=require("refractor/zig");ie=s(ie,1);let F=require("@milkdown/prose/view"),I=require("@milkdown/utils"),ae=require("@milkdown/prose/dropcursor"),L=require("@milkdown/prose/gapcursor"),oe=require("react-dom/client"),R=require("katex");R=s(R,1);let se=require("@milkdown/prose/inputrules"),ce=require("remark-math");ce=s(ce,1);let le=require("@milkdown/prose/transform"),ue=require("react-dom"),de=require("remark-frontmatter");de=s(de,1);let fe=require("@milkdown/plugin-tooltip"),z=require("@milkdown/prose/commands"),pe=require("@milkdown/prose/schema-list"),me=require("@milkdown/plugin-slash"),he=require("@milkdown/prose/tables"),B=require("prosemirror-search"),ge=require("remark-cjk-friendly/parseOnly");ge=s(ge,1);let _e=require("remark-cjk-friendly-gfm-strikethrough/parseOnly");_e=s(_e,1);function V(...e){return(0,h.twMerge)((0,u.clsx)(e))}var ve=(0,p.cva)(`group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4`,{variants:{variant:{default:`bg-primary text-primary-foreground [a]:hover:bg-primary/80`,outline:`border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50`,secondary:`bg-secondary text-secondary-foreground hover:bg-secondary/80 aria-expanded:bg-secondary aria-expanded:text-secondary-foreground`,ghost:`hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50`,destructive:`bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40`,link:`text-primary underline-offset-4 hover:underline`},size:{default:`h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2`,xs:`h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3`,sm:`h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5`,lg:`h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2`,icon:`size-8`,"icon-xs":`size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3`,"icon-sm":`size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg`,"icon-lg":`size-9`}},defaultVariants:{variant:`default`,size:`default`}}),H=c.forwardRef(function({className:e,variant:t=`default`,size:n=`default`,asChild:r=!1,...i},a){return(0,g.jsx)(r?m.Slot.Root:`button`,{ref:a,"data-slot":`button`,"data-variant":t,"data-size":n,className:V(ve({variant:t,size:n,className:e})),...i})}),ye=e=>{let t=e.snapshot.total===0||e.snapshot.isInvalidExpression;return(0,g.jsxs)(`section`,{className:`zt-md-search-panel`,role:`search`,"aria-label":e.messages.searchPanelAriaLabel,children:[(0,g.jsxs)(`div`,{className:`zt-md-search-row zt-md-search-main-row`,children:[e.readOnly?null:(0,g.jsx)(H,{className:`zt-md-search-icon-button zt-md-search-replace-toggle`,type:`button`,variant:`ghost`,size:`icon-sm`,"aria-label":e.messages.searchReplaceLabel,"aria-expanded":e.isReplaceExpanded,title:e.messages.searchReplaceLabel,onClick:e.onReplaceExpandedToggle,children:(0,g.jsx)(f.ChevronRight,{})}),(0,g.jsx)(`input`,{ref:e.searchInputRef,className:`zt-md-search-input`,type:`text`,value:e.options.search,placeholder:e.messages.searchInputPlaceholder,"aria-label":e.messages.searchInputPlaceholder,"aria-invalid":e.snapshot.isInvalidExpression,onChange:t=>{e.onSearchChange(t.target.value)}}),(0,g.jsxs)(`div`,{className:`zt-md-search-options`,role:`group`,"aria-label":e.messages.searchPanelAriaLabel,children:[(0,g.jsx)(H,{className:`zt-md-search-option`,type:`button`,variant:`ghost`,size:`sm`,"aria-pressed":e.options.caseSensitive,"aria-label":e.messages.searchCaseSensitiveLabel,title:e.messages.searchCaseSensitiveLabel,onClick:()=>{e.onOptionToggle(`caseSensitive`)},children:`Aa`}),(0,g.jsx)(H,{className:`zt-md-search-option`,type:`button`,variant:`ghost`,size:`sm`,"aria-pressed":e.options.wholeWord,"aria-label":e.messages.searchWholeWordLabel,title:e.messages.searchWholeWordLabel,onClick:()=>{e.onOptionToggle(`wholeWord`)},children:`W`}),(0,g.jsx)(H,{className:`zt-md-search-option`,type:`button`,variant:`ghost`,size:`sm`,"aria-pressed":e.options.regexp,"aria-label":e.messages.searchRegexpLabel,title:e.messages.searchRegexpLabel,onClick:()=>{e.onOptionToggle(`regexp`)},children:`.*`})]}),(0,g.jsxs)(`output`,{className:`zt-md-search-count`,"aria-live":`polite`,children:[e.snapshot.current,` / `,e.snapshot.total]}),(0,g.jsxs)(`div`,{className:`zt-md-search-navigation`,children:[(0,g.jsxs)(`div`,{className:`zt-md-search-navigation-buttons`,children:[(0,g.jsx)(H,{className:`zt-md-search-icon-button`,type:`button`,variant:`ghost`,size:`icon-sm`,"aria-label":e.messages.searchPreviousAriaLabel,title:e.messages.searchPreviousAriaLabel,disabled:t,onClick:e.onFindPrevious,children:(0,g.jsx)(f.ChevronUp,{})}),(0,g.jsx)(H,{className:`zt-md-search-icon-button`,type:`button`,variant:`ghost`,size:`icon-sm`,"aria-label":e.messages.searchNextAriaLabel,title:e.messages.searchNextAriaLabel,disabled:t,onClick:e.onFindNext,children:(0,g.jsx)(f.ChevronDown,{})})]}),(0,g.jsx)(H,{className:`zt-md-search-icon-button zt-md-search-close-button`,type:`button`,variant:`ghost`,size:`icon-sm`,"aria-label":e.messages.searchCloseAriaLabel,title:e.messages.searchCloseAriaLabel,onClick:e.onClose,children:(0,g.jsx)(f.X,{})})]})]}),e.snapshot.isInvalidExpression?(0,g.jsx)(`span`,{className:`zt-md-search-error`,role:`alert`,children:e.messages.searchInvalidRegexp}):null,!e.readOnly&&e.isReplaceExpanded?(0,g.jsxs)(`div`,{className:`zt-md-search-row zt-md-search-replace-row`,children:[(0,g.jsx)(`input`,{className:`zt-md-search-input`,type:`text`,value:e.options.replace,placeholder:e.messages.searchReplaceInputPlaceholder,"aria-label":e.messages.searchReplaceInputPlaceholder,onChange:t=>{e.onReplaceChange(t.target.value)}}),(0,g.jsx)(H,{className:`zt-md-search-action-button zt-md-search-action-primary`,type:`button`,variant:`default`,size:`sm`,disabled:t,onClick:e.onReplaceCurrent,children:e.messages.searchReplaceLabel}),(0,g.jsx)(H,{className:`zt-md-search-action-button`,type:`button`,variant:`outline`,size:`sm`,disabled:t,onClick:e.onReplaceAll,children:e.messages.searchReplaceAllLabel})]}):null]})},be=e=>typeof e==`string`?e:``,xe=(e,t,n)=>{let r=typeof e==`string`,[i,a]=(0,c.useState)(be(t));return{markdown:(0,c.useMemo)(()=>r?be(e):i,[i,r,e]),setMarkdown:(0,c.useCallback)(e=>{r||a(e),n?.(e)},[r,n]),isControlled:r}},Se={placeholder:`Type / to open the command menu...`,initError:`Editor initialization failed. Please refresh the page and try again.`,editorAriaLabel:`Markdown editor`,searchPanelAriaLabel:`Find and replace in document`,searchInputPlaceholder:`Find in document`,searchReplaceInputPlaceholder:`Replace with`,searchPreviousAriaLabel:`Previous match`,searchNextAriaLabel:`Next match`,searchCloseAriaLabel:`Close search`,searchCaseSensitiveLabel:`Match case`,searchWholeWordLabel:`Match whole word`,searchRegexpLabel:`Use regular expression`,searchReplaceLabel:`Replace`,searchReplaceAllLabel:`Replace all`,searchInvalidRegexp:`Invalid regular expression`,mathBlockSourceAriaLabel:`Math block source`,mathBlockCopyAriaLabel:`Copy math source`,mathBlockDeleteAriaLabel:`Delete math block`,imageDeleteAriaLabel:`Delete image`,tableDeleteAriaLabel:`Delete table`,tableMoreAriaLabel:`More table actions`,tableAlignLeftAriaLabel:`Align current column left`,tableAlignCenterAriaLabel:`Align current column center`,tableAlignRightAriaLabel:`Align current column right`,tableInsertRowAboveLabel:`Insert row above`,tableInsertRowBelowLabel:`Insert row below`,tableInsertColumnLeftLabel:`Insert column left`,tableInsertColumnRightLabel:`Insert column right`,tableDeleteRowLabel:`Delete row`,tableDeleteColumnLabel:`Delete column`,mathRenderError:`Formula rendering failed. Please check the formula syntax.`,imageUploadDialogTitle:`Insert image`,imageUploadDropLabel:`Drop an image here, or choose a file`,imageUploadPickFileLabel:`Choose file`,imageUploadFileTab:`Upload file`,imageUploadUrlTab:`Image URL`,imageUploadUrlPlaceholder:`Paste image URL`,imageUploadInsertUrlLabel:`Insert URL`,imageUploadConfirmLabel:`Insert image`,imageUploadAltLabel:`Alternative text (optional)`,imageUploadAltPlaceholder:`Describe the image`,imageUploadUploadingLabel:`Uploading...`,imageUploadInsertingLabel:`Inserting...`,imageUploadCancelLabel:`Cancel`,imageUploadLoadFailed:`Image failed to load`,imageUploadReselectHint:`Click or drag to reselect`,imageUploadSupportsAndMax:`Supports PNG, JPG, GIF, WebP, SVG, and more, max {size}`,imageUploadFileTooLarge:`The image file is too large.`,imageUploadFileSizeExceeded:`Image size must not exceed {size}`,imageUploadInvalidType:`Please choose an image file.`,imageUploadFailed:`Image upload failed. Please try again.`,imageUploadFileReadFailed:`File read failed. Please try again.`,imageUploadInvalidUrl:`Please enter a valid image URL.`,imageUploadUrlRequired:`Please enter an image URL.`,imageUploadSelectOrEnterImage:`Please select an image or enter an image URL.`,imageUploadUploadingWait:`Image is uploading, please wait.`,selectionTooltipStrongTitle:`Bold`,selectionTooltipEmTitle:`Italic`,selectionTooltipStrikeTitle:`Strikethrough`,selectionTooltipInlineCodeTitle:`Inline code`,selectionTooltipLinkTitle:`Link`,selectionTooltipTransformLabel:`Turn into`,selectionTooltipTransformParagraphLabel:`Paragraph`,selectionTooltipTransformHeading1Label:`Heading 1`,selectionTooltipTransformHeading2Label:`Heading 2`,selectionTooltipTransformHeading3Label:`Heading 3`,selectionTooltipTransformHeading4Label:`Heading 4`,selectionTooltipTransformHeading5Label:`Heading 5`,selectionTooltipTransformHeading6Label:`Heading 6`,selectionTooltipTransformBulletListLabel:`Bullet list`,selectionTooltipTransformOrderedListLabel:`Ordered list`,selectionTooltipTransformTaskListLabel:`Task list`,selectionTooltipTransformBlockquoteLabel:`Blockquote`,selectionTooltipTransformCodeBlockLabel:`Code block`,selectionLinkInputPlaceholder:`Type or paste a link`,selectionLinkSaveAriaLabel:`Save link`,selectionLinkRemoveAriaLabel:`Remove link`,codeBlockLanguageSearchPlaceholder:`Search languages`,codeBlockLanguagePlainText:`text`,codeBlockCopyAriaLabel:`Copy code block`,codeBlockPreviewAriaLabel:`Preview code block`,codeBlockSourceAriaLabel:`View code block source`,codeBlockDeleteAriaLabel:`Delete code block`,frontmatterYamlLabel:`YAML Frontmatter`,frontmatterTomlLabel:`TOML Frontmatter`,frontmatterCollapseAriaLabel:`Collapse frontmatter`,frontmatterExpandAriaLabel:`Expand frontmatter`,frontmatterCopyAriaLabel:`Copy frontmatter`,frontmatterDeleteAriaLabel:`Delete frontmatter`},Ce={placeholder:`请输入 / 打开命令菜单...`,initError:`编辑器初始化失败,请刷新页面后重试。`,editorAriaLabel:`Markdown 编辑器`,searchPanelAriaLabel:`文档搜索与替换`,searchInputPlaceholder:`搜索文档`,searchReplaceInputPlaceholder:`替换为`,searchPreviousAriaLabel:`上一个匹配项`,searchNextAriaLabel:`下一个匹配项`,searchCloseAriaLabel:`关闭搜索`,searchCaseSensitiveLabel:`区分大小写`,searchWholeWordLabel:`全词匹配`,searchRegexpLabel:`使用正则表达式`,searchReplaceLabel:`替换`,searchReplaceAllLabel:`全部替换`,searchInvalidRegexp:`正则表达式无效`,mathBlockSourceAriaLabel:`公式块源码`,mathBlockCopyAriaLabel:`复制公式源码`,mathBlockDeleteAriaLabel:`删除公式块`,imageDeleteAriaLabel:`删除图片`,tableDeleteAriaLabel:`删除表格`,tableMoreAriaLabel:`更多表格操作`,tableAlignLeftAriaLabel:`当前列左对齐`,tableAlignCenterAriaLabel:`当前列居中对齐`,tableAlignRightAriaLabel:`当前列右对齐`,tableInsertRowAboveLabel:`上方插入行`,tableInsertRowBelowLabel:`下方插入行`,tableInsertColumnLeftLabel:`左侧插入列`,tableInsertColumnRightLabel:`右侧插入列`,tableDeleteRowLabel:`删除该行`,tableDeleteColumnLabel:`删除该列`,mathRenderError:`公式渲染失败,请检查公式语法。`,imageUploadDialogTitle:`插入图片`,imageUploadDropLabel:`拖拽图片到这里,或选择文件`,imageUploadPickFileLabel:`选择文件`,imageUploadFileTab:`上传文件`,imageUploadUrlTab:`图片链接`,imageUploadUrlPlaceholder:`粘贴图片链接`,imageUploadInsertUrlLabel:`插入链接`,imageUploadConfirmLabel:`插入图片`,imageUploadAltLabel:`替代文本(可选)`,imageUploadAltPlaceholder:`描述图片内容`,imageUploadUploadingLabel:`上传中...`,imageUploadInsertingLabel:`正在插入...`,imageUploadCancelLabel:`取消`,imageUploadLoadFailed:`图片加载失败`,imageUploadReselectHint:`点击或拖拽重新选择`,imageUploadSupportsAndMax:`支持 PNG、JPG、GIF、WebP、SVG 等,最大 {size}`,imageUploadFileTooLarge:`图片文件过大。`,imageUploadFileSizeExceeded:`图片大小不能超过 {size}`,imageUploadInvalidType:`请选择图片文件。`,imageUploadFailed:`图片上传失败,请重试。`,imageUploadFileReadFailed:`文件读取失败,请重试。`,imageUploadInvalidUrl:`请输入有效的图片链接。`,imageUploadUrlRequired:`请输入图片链接。`,imageUploadSelectOrEnterImage:`请选择图片或输入图片链接。`,imageUploadUploadingWait:`图片正在上传,请稍候。`,selectionTooltipStrongTitle:`加粗`,selectionTooltipEmTitle:`斜体`,selectionTooltipStrikeTitle:`删除线`,selectionTooltipInlineCodeTitle:`行内代码`,selectionTooltipLinkTitle:`链接`,selectionTooltipTransformLabel:`转换为`,selectionTooltipTransformParagraphLabel:`段落`,selectionTooltipTransformHeading1Label:`标题 1`,selectionTooltipTransformHeading2Label:`标题 2`,selectionTooltipTransformHeading3Label:`标题 3`,selectionTooltipTransformHeading4Label:`标题 4`,selectionTooltipTransformHeading5Label:`标题 5`,selectionTooltipTransformHeading6Label:`标题 6`,selectionTooltipTransformBulletListLabel:`无序列表`,selectionTooltipTransformOrderedListLabel:`有序列表`,selectionTooltipTransformTaskListLabel:`任务列表`,selectionTooltipTransformBlockquoteLabel:`引用块`,selectionTooltipTransformCodeBlockLabel:`代码块`,selectionLinkInputPlaceholder:`输入或粘贴链接`,selectionLinkSaveAriaLabel:`保存链接`,selectionLinkRemoveAriaLabel:`移除链接`,codeBlockLanguageSearchPlaceholder:`搜索语言`,codeBlockLanguagePlainText:`text`,codeBlockCopyAriaLabel:`复制代码块`,codeBlockPreviewAriaLabel:`预览代码块`,codeBlockSourceAriaLabel:`查看代码块源码`,codeBlockDeleteAriaLabel:`删除代码块`,frontmatterYamlLabel:`YAML 元数据`,frontmatterTomlLabel:`TOML 元数据`,frontmatterCollapseAriaLabel:`折叠元数据`,frontmatterExpandAriaLabel:`展开元数据`,frontmatterCopyAriaLabel:`复制元数据`,frontmatterDeleteAriaLabel:`删除元数据`},we=`zh-CN`,Te={"zh-CN":{translation:Ce},"en-US":{translation:Se}},Ee=_.default.createInstance(),De=!1,Oe=()=>{De||=(Ee.init({resources:Te,fallbackLng:we,lng:we,interpolation:{escapeValue:!1}}),!0)},U=(e=we,t,n)=>{Oe();let r={...Ee.getResourceBundle(e,`translation`),...t};return n!==void 0&&(r.placeholder=n),r},ke=new WeakMap,W=(e,t)=>{let n=ke.get(e)??new Set;return ke.set(e,n),n.add(t),()=>{n.delete(t)}},Ae=(e,t)=>{Object.keys(t).every(n=>e[n]===t[n])||(Object.assign(e,t),ke.get(e)?.forEach(e=>e()))},je=[j.default,re.default,O.default,ne.default,k.default,ee.default,N.default,M.default,P.default,D.default,te.default,A.default,ie.default];function Me(e){e.languages.text={}}Me.displayName=`text`;function Ne(e){je.forEach(t=>{e.registered(t.displayName)||e.register(t)}),e.register(Me)}Ne(E.refractor);var Pe=`code_block`,Fe=new v.PluginKey(`MILKDOWN_PRISM`),Ie=(e,t=[])=>{let n=[];for(let r of e)if(r.type===`element`){let e=Array.isArray(r.properties?.className)?[...t,...r.properties.className.map(String)]:t;n.push(...Ie(r.children,e))}else r.type===`text`&&r.value&&n.push({text:r.value,classNames:t});return n},Le=e=>{let t=[];return e.descendants((e,n)=>e.type.name===Pe?(t.push({pos:n,node:e}),!1):!0),t},Re=(e,t,n)=>{let r=typeof e.node.attrs.language==`string`?e.node.attrs.language:``;if(!r||!n.has(r))return[];let i=e.pos+1,a=[],o=Ie(t.highlight(e.node.textContent,r).children);for(let e of o){let t=i+e.text.length;e.classNames.length>0&&t>i&&a.push(F.Decoration.inline(i,t,{class:e.classNames.join(` `)})),i=t}return a},ze=(e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n].node!==t[n].node)return!1;return!0},Be=(e,t)=>{let n=Math.max(0,Math.min(e.content.size,t)),r=e.resolve(n);for(let e=r.depth;e>=0;--e)if(r.node(e).type.name===Pe)return!0;return!1},Ve=e=>{let t=1/0;for(let n=0;n<e.steps.length;n+=1){let r=e.mapping.maps[n],i=n>0?e.mapping.slice(0,n).invert():null;r.forEach(e=>{let n=i?i.map(e,-1):e;n<t&&(t=n)})}return t},He=(e,t,n)=>{for(let r=0;r<e.steps.length;r+=1){let i=e.steps[r],a=e.mapping.maps[r],o=[];if(a.forEach((e,t,n,r)=>{o.push([e,t,n,r])}),o.length===0){if(`mark`in i)continue;return!0}let s=r>0?e.mapping.slice(0,r).invert():null,c=r+1<e.mapping.maps.length?e.mapping.slice(r+1):null;for(let[e,r,i,a]of o){let o=s?s.map(e,-1):e,l=s?s.map(r,1):r;for(let e of t){if(e.pos>l)break;if(o<=e.pos+e.node.nodeSize&&l>=e.pos)return!0}let u=Math.max(0,Math.min(n.content.size,c?c.map(i,-1):i)),d=Math.max(u,Math.min(n.content.size,c?c.map(a,1):a));if(u===d){if(Be(n,u))return!0;continue}let f=!1;if(n.nodesBetween(u,d,e=>e.type.name===Pe?(f=!0,!1):!f),f)return!0}}return!1},Ue=(0,I.$prose)(e=>{let{configureRefractor:t}=e.get(T.prismConfig.key),n=t?.(E.refractor)??E.refractor,r=new Set(n.listLanguages());return new v.Plugin({key:Fe,state:{init:(e,{doc:t})=>{let i=Le(t),a=[];for(let e of i)a.push(...Re(e,n,r));return{decorations:F.DecorationSet.create(t,a),blocks:i}},apply:(e,t,i,a)=>{if(!e.docChanged)return t;if(!He(e,t.blocks,a.doc)){if(t.blocks.length===0)return t;let n=t.blocks[t.blocks.length-1],r=n.pos+n.node.nodeSize;if(Ve(e)>r)return t;let i=t.blocks.map(t=>({pos:e.mapping.map(t.pos,1),node:t.node}));return{decorations:t.decorations.map(e.mapping,e.doc),blocks:i}}let o=Le(a.doc);if(ze(t.blocks,o))return{decorations:t.decorations.map(e.mapping,e.doc),blocks:o};let s=t.decorations.map(e.mapping,e.doc),c=new Set;for(let n of t.blocks){let t=e.mapping.map(n.pos,1);a.doc.nodeAt(t)===n.node&&c.add(t)}let l=[];for(let e of o){if(c.has(e.pos))continue;let t=s.find(e.pos,e.pos+e.node.nodeSize);t.length>0&&(s=s.remove(t)),l.push(...Re(e,n,r))}return l.length>0&&(s=s.add(a.doc,l)),{decorations:s,blocks:o}}},props:{decorations(e){return this.getState(e)?.decorations??F.DecorationSet.empty}}})}),We=(e,t)=>typeof e==`function`?n=>{t.action(e(n))}:()=>void 0,Ge=`zt-md-ime-isolating`,Ke=new v.PluginKey(`ZT_MD_IME_COMPOSITION_ISOLATION`),qe=30,Je=4e3,Ye=150,Xe=e=>e.isComposing||e.key===`Process`||e.keyCode===229,Ze=e=>e.key.length===1&&!e.ctrlKey&&!e.metaKey&&!e.altKey,Qe=(e,t)=>{let n=t;for(;n&&n.parentNode!==e;)n=n.parentNode;return n instanceof HTMLElement?n:null},$e=e=>{let t=e.ownerDocument.defaultView?.getSelection();if(!t||t.rangeCount===0||!t.isCollapsed)return null;let n=Qe(e,t.anchorNode);return!n||n.getAttribute(`contenteditable`)===`false`?null:n},et=e=>{let t=e.ownerDocument.defaultView?.getSelection();return!t||t.rangeCount===0||!t.isCollapsed||!t.anchorNode||!e.contains(t.anchorNode)?null:{node:t.anchorNode,offset:t.anchorOffset}},tt=(e,t)=>{if(!t||!t.node.isConnected||!e.contains(t.node))return;let n=e.ownerDocument.defaultView?.getSelection();if(!n||n.rangeCount>0&&n.isCollapsed&&n.anchorNode===t.node&&n.anchorOffset===t.offset)return;let r=e.ownerDocument.createRange();r.setStart(t.node,t.offset),r.collapse(!0),n.removeAllRanges(),n.addRange(r)},nt=(0,I.$prose)(()=>new v.Plugin({key:Ke,view(e){let t=e.dom,n=e,r=!1,i=null,a=!1,o=()=>{i!==null&&(clearTimeout(i),i=null)},s=()=>t.getAttribute(`contenteditable`)===`true`&&(n.state.doc.content.size>=Je||t.childElementCount>=qe),c=()=>{if(r||n.composing||!s())return;let e=t.ownerDocument.activeElement;if(!(e instanceof Node)||!t.contains(e))return;let i=$e(t);if(!i)return;let a=et(t);t.classList.add(Ge),r=!0,t.ownerDocument.activeElement!==i&&(i.focus({preventScroll:!0}),tt(t,a))},l=(e=!1)=>{if(o(),!r)return;let n=t.ownerDocument.activeElement,i=e&&n instanceof Node&&t.contains(n)&&n!==t,a=i?et(t):null;t.classList.remove(Ge),r=!1,i&&(t.focus({preventScroll:!0}),tt(t,a))},u=(e=0)=>{o(),!(r||n.composing||!s())&&(i=setTimeout(()=>{i=null,c()},e))},d=e=>{if(Xe(e)){o();return}e.key!==`Shift`&&l(!0)},f=e=>{if(!(Xe(e)||n.composing)){if(Ze(e)){u(Ye);return}u(0)}},p=()=>{l(!1)},m=()=>{u(0)},h=e=>{e.target===t&&u(0)},g=()=>{r||u(0)},_=e=>{if(a)return;if(e.relatedTarget instanceof Node&&t.contains(e.relatedTarget)){r&&e.target===t&&e.stopImmediatePropagation();return}let n=e.target!==t;if(l(!1),n){a=!0;try{t.dispatchEvent(new FocusEvent(`blur`,{relatedTarget:e.relatedTarget}))}finally{a=!1}}};return t.addEventListener(`keydown`,d,!0),t.addEventListener(`keyup`,f,!0),t.addEventListener(`pointerdown`,p,!0),t.addEventListener(`mouseup`,m,!0),t.addEventListener(`focus`,h,!0),t.addEventListener(`compositionend`,g,!1),t.addEventListener(`blur`,_,!0),{update(e){n=e,r&&(!s()||!e.composing&&!e.state.selection.empty)&&l(!1)},destroy(){o(),l(!1),t.removeEventListener(`keydown`,d,!0),t.removeEventListener(`keyup`,f,!0),t.removeEventListener(`pointerdown`,p,!0),t.removeEventListener(`mouseup`,m,!0),t.removeEventListener(`focus`,h,!0),t.removeEventListener(`compositionend`,g,!1),t.removeEventListener(`blur`,_,!0)}}}})),rt=new v.PluginKey(`ZT_MD_MARKDOWN_SYNC`),it=30,at=8e3,ot=450,st=30,ct=1e3,lt=400,ut=e=>{let t=Math.max(0,e.debounceMs),n=!1,r=null,i=null,a=null,o=null,s=null,c=!1,l=null,u=null,d=null,f=0,p=()=>{l!==null&&(clearTimeout(l),l=null)},m=()=>{u!==null&&(clearTimeout(u),u=null),d!==null&&(typeof cancelIdleCallback==`function`&&cancelIdleCallback(d),d=null)},h=t=>{if(t.composing){c=!0;return}if(c=!1,t.state.doc===a||(s||=e.getSerializer(),!s))return;let n=typeof performance<`u`?performance.now():Date.now(),r=s(t.state.doc),o=typeof performance<`u`?performance.now():Date.now();f=Math.max(0,o-n),a=t.state.doc,r!==i&&(i=r,e.onChange(r))},g=e=>{if(t<=0)return 0;if(e<at&&f<st)return t;let n=e>=at?ot:0,r=f>=st?Math.min(ct,Math.round(f*4)):0;return Math.max(t,n,r)},_=e=>{m();let t=g(e.state.doc.content.size);if(t<=0){h(e);return}u=setTimeout(()=>{if(u=null,!(!o||o.composing||n)){if(o.state.doc.content.size>=at&&typeof requestIdleCallback==`function`){d=requestIdleCallback(()=>{d=null,o&&!o.composing&&!n&&h(o)},{timeout:lt});return}h(o)}},t)};return{plugin:(0,I.$prose)(()=>new v.Plugin({key:rt,props:{handleDOMEvents:{keydown:(e,t)=>((t.isComposing||t.key===`Process`||t.keyCode===229)&&(p(),m()),!1),compositionstart:()=>(p(),m(),!1),compositionend:()=>(p(),l=setTimeout(()=>{l=null,o&&!o.composing&&!n&&(c||o.state.doc!==a)&&(c=!1,_(o))},it),!1),blur:(e,t)=>e.composing||n||t instanceof FocusEvent&&t.relatedTarget instanceof Node&&e.dom.contains(t.relatedTarget)?!1:(p(),m(),h(e),!1)}},view:e=>(o=e,a=e.state.doc,{update:(e,t)=>{if(o=e,n){a=e.state.doc,i=r,c=!1,p(),m();return}if(e.composing){(t.doc!==e.state.doc||e.state.doc!==a)&&(c=!0),p(),m();return}let s=t.doc!==e.state.doc,l=c&&e.state.doc!==a;!s&&!l||(c=!1,p(),_(e))},destroy:()=>{p(),c=!1,m(),s=null,o=null}})})),setDebounceMs:e=>{let n=Math.max(0,e);t!==n&&(t=n,m())},runWithExternalMarkdown:(e,t)=>{p(),c=!1,m(),r=e,n=!0;try{t()}finally{n=!1,r=null}}}},G=(e,t,n)=>{if(Array.isArray(n)){n.forEach((n,r)=>{e.push({name:`${t}-${r}`,plugin:n})});return}e.push({name:t,plugin:n})},dt=(e,t={})=>{let n=[],r=t.includeRuntime??!0;return e.listener&&G(n,`listener`,e.listener),G(n,`commonmark`,e.commonmark),G(n,`frontmatter`,e.frontmatter),G(n,`task-list-transform-keymap`,e.taskListTransformKeymap),G(n,`inline-code-boundary-navigation`,e.inlineCodeBoundaryNavigation),G(n,`gfm`,e.gfm),G(n,`cjk-friendly`,e.cjkFriendly),G(n,`history`,e.history),G(n,`editor-search`,e.editorSearch),G(n,`code-block-prism`,e.codeBlockPrism),G(n,`code-block-language-picker`,e.codeBlockLanguagePicker),r&&(G(n,`clipboard`,e.clipboard),G(n,`indent`,e.indent)),G(n,`image-delete-selection`,e.imageDeleteSelection),G(n,`image-paste`,e.imagePaste),G(n,`table-arrow-entry`,e.tableArrowEntry),G(n,`block-boundary-navigation`,e.blockBoundaryNavigation),G(n,`heading-backspace-empty-paragraph`,e.headingBackspaceEmptyParagraph),G(n,`heading-focus-indicator`,e.headingFocusIndicator),G(n,`math-backspace-entry`,e.mathBackspaceEntry),G(n,`blockquote-backspace-lift`,e.blockquoteBackspaceLift),G(n,`table-focus-actions`,e.tableFocusActions),G(n,`selection-tooltip`,e.selectionTooltip),G(n,`gap-cursor`,e.gapCursor),G(n,`drop-cursor`,e.dropCursor),G(n,`math`,e.math),G(n,`math-inline-edit`,e.mathInlineEdit),G(n,`math-inline-arrow-navigation`,e.mathInlineArrowNavigation),G(n,`task-list-toggle`,e.taskListToggle),G(n,`tab-space-indent`,e.tabSpaceIndent),G(n,`code-block-mod-a-select`,e.codeBlockModASelect),e.slash&&G(n,`slash`,e.slash),n},ft=2,pt=`var(--zt-primary)`,mt=(0,I.$prose)(()=>(0,ae.dropCursor)({color:pt,width:ft})),ht=(0,I.$prose)(()=>(0,L.gapCursor)()),K=-1,gt=1,_t=new Set([`math_block`,`code_block`,`frontmatter`,`table`,`image`,`hr`]),vt=e=>typeof e.props.editable==`function`?e.props.editable(e.state):e.editable,yt=(e,t,n)=>{let r=e.state.doc.resolve(t);return L.GapCursor.valid(r)?new L.GapCursor(r):v.TextSelection.near(r,n)},bt=(e,t)=>t===K?e.nodeBefore!==null:e.nodeAfter!==null,xt=(e,t)=>{let n=e.state.schema.nodes.paragraph;if(!n)return!1;let r=e.state.doc.resolve(t),i=r.index();if(!r.parent.canReplaceWith(i,i,n))return!1;let a=n.createAndFill();if(!a)return!1;let o=e.state.tr.insert(t,a),s=t+1;return o.setSelection(v.TextSelection.near(o.doc.resolve(s),1)).scrollIntoView(),e.dispatch(o),e.focus(),!0},St=(e,t,n,r)=>{if(!_t.has(n.type.name)||n.type.name===`frontmatter`&&r===K)return!1;let i=r===K?t:t+n.nodeSize;if(i<0||i>e.state.doc.content.size)return!1;if(!bt(e.state.doc.resolve(i),r)&&xt(e,i))return!0;let a=e.state.tr.setSelection(yt(e,i,r)).scrollIntoView();return e.dispatch(a),e.focus(),!0},Ct=e=>{for(let t=e.depth;t>0;--t){let n=e.node(t);if(_t.has(n.type.name))return{node:n,position:e.before(t),depth:t}}return null},wt=(e,t,n)=>{for(let r=t;r<e.depth;r+=1){let t=e.node(r);if(e.index(r)!==(n===K?0:t.childCount-1))return!1}return!0},Tt=(e,t)=>{let{selection:n}=e.state;if(n instanceof v.NodeSelection)return St(e,n.from,n.node,t);if(!n.empty)return!1;let r=Ct(n.$from);return!r||!wt(n.$from,r.depth,t)||!e.endOfTextblock(t===K?`up`:`down`)?!1:St(e,r.position,r.node,t)},Et=e=>{let{doc:t,selection:n}=e.state;return!(n instanceof v.TextSelection)||!n.empty||!(n.$from.after(1)===t.content.size&&wt(n.$from,1,gt))||!e.endOfTextblock(`down`)?!1:xt(e,t.content.size)},Dt={ArrowUp:e=>Tt(e,K),ArrowDown:e=>Tt(e,gt)||Et(e)},Ot=(e,t)=>t.defaultPrevented||t.altKey||t.ctrlKey||t.metaKey||t.shiftKey||!vt(e),kt=(e,t,n,r)=>{let i=r===`ArrowUp`?K:r===`ArrowDown`?gt:null;return i===null||!vt(e)?!1:St(e,t,n,i)},At=(0,I.$prose)(()=>new v.Plugin({key:new v.PluginKey(`zt-md-block-boundary-navigation`),props:{handleKeyDown:(e,t)=>{let n=Dt[t.key];if(!n||Ot(e,t))return!1;let r=n(e);return r&&t.preventDefault(),r}}})),jt={AlignCenter:[[`path`,{d:`M21 5H3`}],[`path`,{d:`M17 12H7`}],[`path`,{d:`M19 19H5`}]],AlignLeft:[[`path`,{d:`M21 5H3`}],[`path`,{d:`M15 12H3`}],[`path`,{d:`M17 19H3`}]],AlignRight:[[`path`,{d:`M21 5H3`}],[`path`,{d:`M21 12H9`}],[`path`,{d:`M21 19H7`}]],Bold:[[`path`,{d:`M6 12h9a4 4 0 0 1 0 8H7a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h7a4 4 0 0 1 0 8`}]],Check:[[`path`,{d:`M20 6 9 17l-5-5`}]],ChevronDown:[[`path`,{d:`m6 9 6 6 6-6`}]],Circle:[[`circle`,{cx:`12`,cy:`12`,r:`10`}]],Code:[[`path`,{d:`m16 18 6-6-6-6`}],[`path`,{d:`m8 6-6 6 6 6`}]],Code2:[[`path`,{d:`m18 16 4-4-4-4`}],[`path`,{d:`m6 8-4 4 4 4`}],[`path`,{d:`m14.5 4-5 16`}]],Copy:[[`rect`,{width:`14`,height:`14`,x:`8`,y:`8`,rx:`2`,ry:`2`}],[`path`,{d:`M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2`}]],Eye:[[`path`,{d:`M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0`}],[`circle`,{cx:`12`,cy:`12`,r:`3`}]],Heading1:[[`path`,{d:`M4 12h8`}],[`path`,{d:`M4 18V6`}],[`path`,{d:`M12 18V6`}],[`path`,{d:`m17 12 3-2v8`}]],Heading2:[[`path`,{d:`M4 12h8`}],[`path`,{d:`M4 18V6`}],[`path`,{d:`M12 18V6`}],[`path`,{d:`M21 18h-4c0-4 4-3 4-6 0-1.5-2-2.5-4-1`}]],Heading3:[[`path`,{d:`M4 12h8`}],[`path`,{d:`M4 18V6`}],[`path`,{d:`M12 18V6`}],[`path`,{d:`M17.5 10.5c1.7-1 3.5 0 3.5 1.5a2 2 0 0 1-2 2`}],[`path`,{d:`M17 17.5c2 1.5 4 .3 4-1.5a2 2 0 0 0-2-2`}]],Heading4:[[`path`,{d:`M12 18V6`}],[`path`,{d:`M17 10v3a1 1 0 0 0 1 1h3`}],[`path`,{d:`M21 10v8`}],[`path`,{d:`M4 12h8`}],[`path`,{d:`M4 18V6`}]],Heading5:[[`path`,{d:`M4 12h8`}],[`path`,{d:`M4 18V6`}],[`path`,{d:`M12 18V6`}],[`path`,{d:`M17 13v-3h4`}],[`path`,{d:`M17 17.7c.4.2.8.3 1.3.3 1.5 0 2.7-1.1 2.7-2.5S19.8 13 18.3 13H17`}]],Heading6:[[`path`,{d:`M4 12h8`}],[`path`,{d:`M4 18V6`}],[`path`,{d:`M12 18V6`}],[`circle`,{cx:`19`,cy:`16`,r:`2`}],[`path`,{d:`M20 10c-2 2-3 3.5-3 6`}]],Image:[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,ry:`2`}],[`circle`,{cx:`9`,cy:`9`,r:`2`}],[`path`,{d:`m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21`}]],ImageOff:[[`line`,{x1:`2`,x2:`22`,y1:`2`,y2:`22`}],[`path`,{d:`M10.41 10.41a2 2 0 1 1-2.83-2.83`}],[`line`,{x1:`13.5`,x2:`6`,y1:`13.5`,y2:`21`}],[`line`,{x1:`18`,x2:`21`,y1:`12`,y2:`15`}],[`path`,{d:`M3.59 3.59A1.99 1.99 0 0 0 3 5v14a2 2 0 0 0 2 2h14c.55 0 1.052-.22 1.41-.59`}],[`path`,{d:`M21 15V5a2 2 0 0 0-2-2H9`}]],Italic:[[`line`,{x1:`19`,x2:`10`,y1:`4`,y2:`4`}],[`line`,{x1:`14`,x2:`5`,y1:`20`,y2:`20`}],[`line`,{x1:`15`,x2:`9`,y1:`4`,y2:`20`}]],List:[[`path`,{d:`M3 5h.01`}],[`path`,{d:`M3 12h.01`}],[`path`,{d:`M3 19h.01`}],[`path`,{d:`M8 5h13`}],[`path`,{d:`M8 12h13`}],[`path`,{d:`M8 19h13`}]],ListOrdered:[[`path`,{d:`M11 5h10`}],[`path`,{d:`M11 12h10`}],[`path`,{d:`M11 19h10`}],[`path`,{d:`M4 4h1v5`}],[`path`,{d:`M4 9h2`}],[`path`,{d:`M6.5 20H3.4c0-1 2.6-1.925 2.6-3.5a1.5 1.5 0 0 0-2.6-1.02`}]],ListTodo:[[`path`,{d:`M13 5h8`}],[`path`,{d:`M13 12h8`}],[`path`,{d:`M13 19h8`}],[`path`,{d:`m3 17 2 2 4-4`}],[`rect`,{x:`3`,y:`4`,width:`6`,height:`6`,rx:`1`}]],Sigma:[[`path`,{d:`M18 7V5a1 1 0 0 0-1-1H6.5a.5.5 0 0 0-.4.8l4.5 6a2 2 0 0 1 0 2.4l-4.5 6a.5.5 0 0 0 .4.8H17a1 1 0 0 0 1-1v-2`}]],SquareCode:[[`path`,{d:`m10 9-3 3 3 3`}],[`path`,{d:`m14 15 3-3-3-3`}],[`rect`,{x:`3`,y:`3`,width:`18`,height:`18`,rx:`2`}]],SquareFunction:[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,ry:`2`}],[`path`,{d:`M9 17c2 0 2.8-1 2.8-2.8V10c0-2 1-3.3 3.2-3`}],[`path`,{d:`M9 11.2h5.7`}]],Strikethrough:[[`path`,{d:`M16 4H9a3 3 0 0 0-2.83 4`}],[`path`,{d:`M14 12a4 4 0 0 1 0 8H6`}],[`line`,{x1:`4`,x2:`20`,y1:`12`,y2:`12`}]],Table:[[`path`,{d:`M12 3v18`}],[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`}],[`path`,{d:`M3 9h18`}],[`path`,{d:`M3 15h18`}]],TextQuote:[[`path`,{d:`M17 5H3`}],[`path`,{d:`M21 12H8`}],[`path`,{d:`M21 19H8`}],[`path`,{d:`M3 12v7`}]],Trash2:[[`path`,{d:`M10 11v6`}],[`path`,{d:`M14 11v6`}],[`path`,{d:`M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6`}],[`path`,{d:`M3 6h18`}],[`path`,{d:`M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2`}]],Type:[[`path`,{d:`M12 4v16`}],[`path`,{d:`M4 7V5a1 1 0 0 1 1-1h14a1 1 0 0 1 1 1v2`}],[`path`,{d:`M9 20h6`}]]},Mt=new Map,Nt=e=>Object.entries(e).map(([e,t])=>`${e}="${t}"`).join(` `),Pt=(e,t)=>e&&Object.prototype.hasOwnProperty.call(jt,e)?e:t,q=(e,t={})=>{let n=t.size??16,r=t.strokeWidth??2,i=t.ariaHidden??!0,a=`${e}:${n}:${r}:${i}`,o=Mt.get(a);if(o!==void 0)return o;let s=jt[e].map(([e,t])=>`<${e} ${Nt(t)}></${e}>`).join(``),c=`<svg xmlns="http://www.w3.org/2000/svg" width="${n}" height="${n}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="${r}" stroke-linecap="round" stroke-linejoin="round"${i?` aria-hidden="true"`:``}>${s}</svg>`;return Mt.set(a,c),c},Ft=new Set([`http:`,`https:`,`mailto:`,`tel:`]),It=new Set([`data:`]),Lt=/[\u0000-\u0020\u007f]+/g,Rt=/^([a-z][a-z\d+\-.]*:)/i,zt=/[<>"'`]/,Bt=new Set([`src`,`alt`,`title`,`style`]),Vt=(e,t)=>{if(typeof e!=`string`)return``;let n=e.trim();if(!n||zt.test(n)||/[\u0000-\u001f\u007f]/.test(n))return``;let r=n.replace(Lt,``);if(r.startsWith(`//`))return``;let i=r.match(Rt)?.[1]?.toLowerCase()??``;if(!i)return n;if(!t.has(i))return``;try{return new URL(n).toString()}catch{return``}},Ht=e=>Vt(e,Ft),Ut=(e,t=[])=>Vt(e,new Set([...Ft,...It,...t.map(e=>e.trim().toLowerCase())])),Wt=(e,t,n=[])=>{if(typeof e!=`string`)return null;let r=e.trim();if(!r)return null;let i=new DOMParser().parseFromString(r,`text/html`),a=null;for(let e of Array.from(i.body.childNodes))if(!(e.nodeType===Node.TEXT_NODE&&!(e.textContent??``).trim())){if(e instanceof HTMLImageElement&&a===null){a=e;continue}return null}if(!a||a.tagName.toLowerCase()!==`img`)return null;for(let e of Array.from(a.attributes))if(!Bt.has(e.name.toLowerCase()))return null;let o=Ut(a.getAttribute(`src`)??``,n);return o?{src:o,alt:a.getAttribute(`alt`)??``,title:a.getAttribute(`title`)??``,style:t(a.getAttribute(`style`)??``)}:null},Gt=/^\s*width\s*:\s*(\d{1,3})%\s*;?\s*$/i,Kt=(e,t)=>{let n=Array.isArray(e.children)?e.children:[],r=n[0];return n.length===1&&(r?.type===`image`||r?.type===`html`&&Wt(r.value,Xt,t)!==null)?r:null},qt=e=>Math.min(100,Math.max(10,e)),Jt=e=>`width: ${qt(Math.round(e))}%;`,Yt=e=>{if(typeof e!=`string`)return null;let t=e.match(Gt);if(!t)return null;let n=Number(t[1]);return Number.isFinite(n)?qt(n):null},Xt=e=>{let t=Yt(e);return t===null?``:Jt(t)},Zt=e=>typeof e==`string`?e.replace(/&/g,`&`).replace(/"/g,`"`).replace(/</g,`<`).replace(/>/g,`>`):``,Qt=(e,t)=>{let n=Ut(e.src,t);if(!n)return``;let r=typeof e.alt==`string`?e.alt:``,i=typeof e.title==`string`?e.title:``,a=i?` title="${Zt(i)}"`:``,o=Xt(e.style);return`<img src="${Zt(n)}" alt="${Zt(r)}"${a} style="${Zt(o)}">`},$t=(e,t)=>n=>{let r=e(n);return{...r,inline:!1,group:`block`,attrs:{...r.attrs,style:{default:``,validate:`string`}},parseDOM:[{tag:`img[src]`,getAttrs:e=>{let n=e,r=Ut(n.getAttribute(`src`)??``,t);return r?{src:r,alt:n.getAttribute(`alt`)??``,title:n.getAttribute(`title`)??n.getAttribute(`alt`)??``,style:Xt(n.getAttribute(`style`)??``)}:!1}}],parseMarkdown:{match:e=>e.type===`image`||e.type===`html`&&Wt(e.value,Xt,t)!==null,runner:(e,n,r)=>{if(n.type===`html`){let i=Wt(n.value,Xt,t);i&&e.addNode(r,i);return}let i=Ut(String(n.url??``),t);i&&e.addNode(r,{src:i,alt:String(n.alt??``),title:String(n.title??``),style:``})}},toMarkdown:{match:e=>e.type.name===`image`,runner:(e,n)=>{let r=Ut(n.attrs.src,t);if(!r)return;let i=Xt(n.attrs.style);if(i){let a=Qt({...n.attrs,src:r,style:i},t);a&&e.addNode(`html`,void 0,a);return}let a={type:`image`,title:n.attrs.title,url:r,alt:n.attrs.alt};e.addNode(`paragraph`,[a])}}}},en=(e,t)=>n=>{let r=e(n);return{...r,parseMarkdown:{...r.parseMarkdown,runner:(e,n,i)=>{let a=Kt(n,t);if(a){e.next(a);return}r.parseMarkdown.runner(e,n,i)}}}},tn=(e,t=[])=>{let n=e.get(C.imageSchema.key),r=e.get(C.paragraphSchema.key);e.set(C.imageSchema.key,$t(n,t)),e.set(C.paragraphSchema.key,en(r,t))},nn=`image`,rn=`left`,an=`right`,on=160,sn=q(`Trash2`,{size:14,strokeWidth:2}),cn=q(`ImageOff`,{size:14,strokeWidth:2}),ln=e=>typeof e==`function`?e():null,un=e=>typeof e.props.editable==`function`?e.props.editable(e.state):e.editable,dn=class{constructor(e,t,n,r){this.resizeState=null,this.isSelected=!1,this.currentImageSrc=``,this.imageLoadingStartedAt=0,this.imageLoadingFinishTimer=null,this.handleDeleteClick=e=>{e.preventDefault(),e.stopPropagation(),un(this.view)&&this.deleteCurrentImage()},this.handleImageLoad=()=>{delete this.dom.dataset.loadError,this.finishImageLoadingWithMinimumDuration()},this.handleImageError=()=>{this.dom.dataset.loadError=`true`,this.finishImageLoadingWithMinimumDuration()},this.handleResizePointerDown=e=>{if(e.preventDefault(),e.stopPropagation(),!un(this.view))return;let t=e.currentTarget;if(!(t instanceof HTMLElement))return;let n=t.dataset.side===rn?rn:an,r=this.dom.parentElement;if(!r)return;let i=this.imageElement.getBoundingClientRect(),a=r.getBoundingClientRect();if(i.width<=0||a.width<=0)return;let o=qt(i.width/a.width*100);this.resizeState={side:n,startClientX:e.clientX,startWidth:i.width,containerWidth:a.width,widthPercent:o},this.dom.dataset.resizing=`true`,this.applyPreviewWidth(o),window.addEventListener(`pointermove`,this.handleResizePointerMove),window.addEventListener(`pointerup`,this.handleResizePointerUp),window.addEventListener(`pointercancel`,this.handleResizePointerUp)},this.handleResizePointerMove=e=>{if(!this.resizeState)return;e.preventDefault();let t=e.clientX-this.resizeState.startClientX,n=this.resizeState.side===rn?-t:t,r=qt((this.resizeState.startWidth+n)/this.resizeState.containerWidth*100);this.resizeState.widthPercent=r,this.applyPreviewWidth(r)},this.handleResizePointerUp=e=>{if(e.preventDefault(),!this.resizeState)return;let t=Math.round(this.resizeState.widthPercent);this.resizeState=null,delete this.dom.dataset.resizing,this.removeResizeWindowListeners(),this.commitImageWidth(t)},this.node=e,this.view=t,this.getPos=n,this.deleteAriaLabel=r.imageDeleteAriaLabel,this.dom=document.createElement(`span`),this.dom.dataset.type=nn,this.dom.className=`zt-md-image`,this.updateEditableState(),this.syncSelectedState(),this.imageElement=document.createElement(`img`),this.imageElement.loading=`lazy`,this.imageElement.decoding=`async`,this.imageElement.addEventListener(`load`,this.handleImageLoad),this.imageElement.addEventListener(`error`,this.handleImageError),this.imageLoadErrorElement=document.createElement(`span`),this.imageLoadErrorElement.className=`zt-md-image-load-error`,this.imageLoadErrorElement.contentEditable=`false`,this.imageLoadErrorElement.innerHTML=cn,this.imageLoadErrorElement.append(r.imageUploadLoadFailed),this.leftResizeHandle=this.createResizeHandle(rn),this.rightResizeHandle=this.createResizeHandle(an),this.actionsContainer=document.createElement(`span`),this.actionsContainer.className=`zt-md-image-actions`,this.deleteButton=document.createElement(`button`),this.deleteButton.type=`button`,this.deleteButton.className=`zt-md-image-action-button zt-md-image-action-button-danger`,this.deleteButton.setAttribute(`aria-label`,this.deleteAriaLabel),this.deleteButton.innerHTML=sn,this.actionsContainer.appendChild(this.deleteButton),this.dom.append(this.imageElement,this.imageLoadErrorElement,this.leftResizeHandle,this.rightResizeHandle,this.actionsContainer),this.syncFromNode(e),this.deleteButton.addEventListener(`click`,this.handleDeleteClick),this.leftResizeHandle.addEventListener(`pointerdown`,this.handleResizePointerDown),this.rightResizeHandle.addEventListener(`pointerdown`,this.handleResizePointerDown),this.stopObservingMessages=W(r,()=>{this.deleteButton.setAttribute(`aria-label`,r.imageDeleteAriaLabel);let e=this.imageLoadErrorElement.lastChild;e&&(e.textContent=r.imageUploadLoadFailed)})}createResizeHandle(e){let t=document.createElement(`span`);return t.className=`zt-md-image-resize-handle zt-md-image-resize-handle-${e}`,t.dataset.side=e,t.setAttribute(`aria-hidden`,`true`),t}deleteCurrentImage(){let e=ln(this.getPos);if(e===null)return;let t=this.view.state.tr.delete(e,e+this.node.nodeSize).scrollIntoView();this.view.dispatch(t),requestAnimationFrame(()=>{this.view.focus()})}updateEditableState(){this.dom.dataset.editable=un(this.view)?`true`:`false`}syncSelectedState(){this.dom.dataset.selected=this.isSelected?`true`:`false`}markImageLoading(){this.clearImageLoadingFinishTimer(),this.imageLoadingStartedAt=performance.now(),delete this.dom.dataset.loadError,this.dom.dataset.loading=`true`}finishImageLoading(){this.clearImageLoadingFinishTimer(),delete this.dom.dataset.loading}finishImageLoadingWithMinimumDuration(){let e=performance.now()-this.imageLoadingStartedAt,t=Math.max(0,on-e);if(t<=0){this.finishImageLoading();return}this.clearImageLoadingFinishTimer(),this.imageLoadingFinishTimer=window.setTimeout(()=>{this.finishImageLoading()},t)}clearImageLoadingFinishTimer(){this.imageLoadingFinishTimer!==null&&(window.clearTimeout(this.imageLoadingFinishTimer),this.imageLoadingFinishTimer=null)}removeResizeWindowListeners(){window.removeEventListener(`pointermove`,this.handleResizePointerMove),window.removeEventListener(`pointerup`,this.handleResizePointerUp),window.removeEventListener(`pointercancel`,this.handleResizePointerUp)}applyPreviewWidth(e){this.dom.style.width=`${Math.round(e)}%`,this.dom.dataset.hasWidth=`true`}commitImageWidth(e){let t=ln(this.getPos);if(t===null)return;let n={...this.node.attrs,style:Jt(e)},r=this.view.state.tr.setNodeMarkup(t,void 0,n);this.view.dispatch(r),requestAnimationFrame(()=>{this.view.focus()})}syncFromNode(e){this.updateEditableState();let t=typeof e.attrs.src==`string`?e.attrs.src:``,n=typeof e.attrs.alt==`string`?e.attrs.alt:``,r=typeof e.attrs.title==`string`?e.attrs.title:``,i=Yt(Xt(e.attrs.style));t!==this.currentImageSrc&&(delete this.dom.dataset.loadError,t&&this.markImageLoading()),this.imageElement.setAttribute(`src`,t),this.currentImageSrc=t,this.imageElement.setAttribute(`alt`,n),r?this.imageElement.title=r:this.imageElement.removeAttribute(`title`),i===null?(this.dom.style.removeProperty(`width`),delete this.dom.dataset.hasWidth):(this.dom.style.width=`${i}%`,this.dom.dataset.hasWidth=`true`),t?this.imageElement.complete&&this.imageElement.naturalWidth>0&&this.finishImageLoadingWithMinimumDuration():this.finishImageLoading()}update(e){return e.type.name===nn?(this.node=e,this.syncFromNode(e),!0):!1}selectNode(){this.isSelected=!0,this.syncSelectedState()}deselectNode(){this.isSelected=!1,this.syncSelectedState()}stopEvent(e){let t=e.target;return t instanceof Node?this.deleteButton.contains(t)||this.leftResizeHandle.contains(t)||this.rightResizeHandle.contains(t)||this.resizeState!==null:!1}ignoreMutation(){return!0}destroy(){this.stopObservingMessages(),this.removeResizeWindowListeners(),this.clearImageLoadingFinishTimer(),this.imageElement.removeEventListener(`load`,this.handleImageLoad),this.imageElement.removeEventListener(`error`,this.handleImageError),this.deleteButton.removeEventListener(`click`,this.handleDeleteClick),this.leftResizeHandle.removeEventListener(`pointerdown`,this.handleResizePointerDown),this.rightResizeHandle.removeEventListener(`pointerdown`,this.handleResizePointerDown)}},fn=(e=U())=>(t,n,r)=>new dn(t,n,typeof r==`function`?()=>{let e=r();return typeof e==`number`?e:0}:!1,e),pn=`image`,mn={Backspace:`before`,Delete:`after`},hn=e=>typeof e.props.editable==`function`?e.props.editable(e.state):e.editable,gn=e=>e instanceof Element?!!e.closest(`.zt-md-image-actions, .zt-md-image-resize-handle`):!1,_n=e=>e?.type.name===pn,vn=(e,t)=>!mn[t.key]||t.defaultPrevented||t.altKey||t.ctrlKey||t.metaKey||t.shiftKey||!hn(e)||gn(t.target)||gn(document.activeElement),yn=e=>{if(e.parent.type.name!==`paragraph`||e.parentOffset!==0||e.parent.textContent.length>0||e.depth<1)return null;let t=e.index(e.depth-1);if(t<=0)return null;let n=e.node(e.depth-1).child(t-1);return _n(n)?{previousBlockStart:e.before(e.depth)-n.nodeSize}:null},bn=(e,t)=>{try{return v.TextSelection.create(e,t)}catch{return v.TextSelection.near(e.resolve(t),-1)}},xn=(e,t,n)=>{n.preventDefault();let r=t.from,i=e.state.tr.delete(t.from,t.to),a=i.doc.content.size,o=Math.min(r,a);return i.setSelection(bn(i.doc,o)).scrollIntoView(),e.dispatch(i),e.focus(),!0},Sn=(e,t)=>{if(t.key!==`Backspace`)return!1;let{selection:n}=e.state;if(!n.empty)return!1;let r=n.$from,i=yn(r);if(!i)return!1;let a=r.before(r.depth),o=a+r.parent.nodeSize;t.preventDefault();let s=e.state.tr;return s.delete(a,o),s.setSelection(v.NodeSelection.create(s.doc,i.previousBlockStart)).scrollIntoView(),e.dispatch(s),e.focus(),!0},Cn=(e,t)=>{if(Sn(e,t))return!0;let n=mn[t.key];if(!n)return!1;let{selection:r}=e.state;if(!r.empty)return!1;let i=r.$from,a=n===`before`?i.nodeBefore:i.nodeAfter;if(!_n(a))return!1;t.preventDefault();let o=n===`before`?r.from-a.nodeSize:r.from;return e.dispatch(e.state.tr.setSelection(v.NodeSelection.create(e.state.doc,o)).scrollIntoView()),e.focus(),!0},wn=(e,t)=>{if(vn(e,t))return!1;let{selection:n}=e.state;return n instanceof v.NodeSelection&&_n(n.node)?xn(e,n,t):Cn(e,t)},Tn=(0,I.$prose)(()=>new v.Plugin({key:new v.PluginKey(`zt-md-image-delete-selection`),props:{handleKeyDown:(e,t)=>wn(e,t)}})),En=e=>e.state.schema.nodes.paragraph?.createAndFill()??null,Dn=(e,t)=>e.state.schema.nodes.image?.create(t)??null,On=e=>{let t=e.$to.parent;if(e.$to.parentOffset<t.content.size)return!0;if(e.$to.depth<1)return!1;let n=e.$to.node(e.$to.depth-1);return e.$to.index(e.$to.depth-1)<n.childCount-1},kn=(e,t)=>{let n=[t,t-1,t+1];for(let t of n)if(!(t<0||t>e.content.size)&&e.nodeAt(t)?.type.name===`image`)return t;return null},An=(e,t)=>{let n=e.selection.from-t,r=kn(e.doc,n);return r===null?null:v.NodeSelection.create(e.doc,r)},jn=(e,t,n=e.state.selection)=>{let r=Dn(e,t);if(!r)return!1;let i=On(n),a=e.state.tr.setSelection(n).replaceSelectionWith(r),o=a.selection.to;if(!i){let t=En(e);t&&a.insert(o,t)}let s=An(a,r.nodeSize);return s?(a.setSelection(s).scrollIntoView(),e.dispatch(a),!0):!1},Mn=`zt-md-image-upload-file-input`,Nn=`zt-md-image-upload-alt-input`,Pn=e=>new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let e=r.result;if(typeof e==`string`){t(e);return}n(Error(`Invalid file result`))},r.onerror=()=>{n(r.error??Error(`File read failed`))},r.readAsDataURL(e)}),Fn=e=>e<1024*1024?`${Math.ceil(e/1024)}KB`:`${(e/1024/1024).toFixed(1)}MB`,In=e=>{try{let t=new URL(e);return!!(t.protocol&&t.host)}catch{return!1}},Ln=e=>new Promise((t,n)=>{let r=new Image;r.onload=()=>{t()},r.onerror=()=>{n(Error(`Image load failed`))},r.src=e}),Rn=e=>e.replace(/\.[^/.]+$/,``),zn=new v.PluginKey(`zt-md-image-paste`),Bn=0,Vn=e=>(typeof e.props.editable==`function`?e.props.editable(e.state):e.editable)&&!e.state.selection.$from.parent.type.spec.code,Hn=e=>Array.from(e.items).find(e=>e.kind===`file`&&e.type.startsWith(`image/`))?.getAsFile()||(Array.from(e.files).find(e=>e.type.startsWith(`image/`))??null),Un=()=>(Bn+=1,`image-paste-${Bn}`),Wn=(e,t)=>{let n=new Map;t.forEach((t,r)=>{n.set(r,t.map(e.mapping))});let r=e.getMeta(zn);return r?.type===`add`&&n.set(r.requestId,r.bookmark),r?.type===`remove`&&n.delete(r.requestId),n},Gn=(e,t)=>{e.isDestroyed||!zn.getState(e.state)?.has(t)||e.dispatch(e.state.tr.setMeta(zn,{type:`remove`,requestId:t}))},Kn=async(e,t,n)=>{let r=t?.upload?await t.upload(e):await Pn(e);if(!r)throw Error(n.imageUploadFailed);return r},qn=async(e,t,n,r,i)=>{try{let a=await Kn(t,r,i);if(e.isDestroyed)return;let o=zn.getState(e.state)?.get(n);if(!o)return;let s=o.resolve(e.state.doc);Gn(e,n),jn(e,{src:a,alt:Rn(t.name),title:``},s)}catch(e){console.error(e)}finally{Gn(e,n)}},Jn=(e,t)=>(0,I.$prose)(()=>new v.Plugin({key:zn,state:{init:()=>new Map,apply:Wn},props:{handlePaste:(n,r)=>{if(!Vn(n))return!1;let i=r.clipboardData?Hn(r.clipboardData):null;if(!i)return!1;r.preventDefault();let a=e?.maxFileSize??5242880;if(i.size>a)return console.error(Error(t.imageUploadFileSizeExceeded.replace(`{size}`,Fn(a)))),!0;let o=Un(),s=n.state.selection.getBookmark();return n.dispatch(n.state.tr.setMeta(zn,{type:`add`,requestId:o,bookmark:s})),qn(n,i,o,e,t),!0}}}));function Yn({...e}){return(0,g.jsx)(m.Dialog.Root,{"data-slot":`dialog`,...e})}c.forwardRef(function({...e},t){return(0,g.jsx)(m.Dialog.Trigger,{ref:t,"data-slot":`dialog-trigger`,...e})});function Xn({container:e,...t}){return(0,g.jsx)(m.Dialog.Portal,{"data-slot":`dialog-portal`,container:e??void 0,...t})}c.forwardRef(function({...e},t){return(0,g.jsx)(m.Dialog.Close,{ref:t,"data-slot":`dialog-close`,...e})});var Zn=c.forwardRef(function({className:e,...t},n){return(0,g.jsx)(m.Dialog.Overlay,{ref:n,"data-slot":`dialog-overlay`,className:V(`fixed inset-0 isolate z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0`,e),...t})}),Qn=c.forwardRef(function({container:e,className:t,children:n,showCloseButton:r=!0,closeLabel:i=`Close`,...a},o){return(0,g.jsxs)(Xn,{container:e,children:[(0,g.jsx)(Zn,{}),(0,g.jsxs)(m.Dialog.Content,{ref:o,"data-slot":`dialog-content`,className:V(`fixed top-1/2 left-1/2 z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-xl bg-popover p-4 text-sm text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95`,t),...a,children:[n,r&&(0,g.jsx)(m.Dialog.Close,{"data-slot":`dialog-close`,asChild:!0,children:(0,g.jsxs)(H,{variant:`ghost`,className:`absolute top-2 right-2`,size:`icon-sm`,children:[(0,g.jsx)(f.XIcon,{}),(0,g.jsx)(`span`,{className:`sr-only`,children:i})]})})]})]})});function $n({className:e,...t}){return(0,g.jsx)(`div`,{"data-slot":`dialog-header`,className:V(`flex flex-col gap-2`,e),...t})}function er({className:e,showCloseButton:t=!1,children:n,...r}){return(0,g.jsxs)(`div`,{"data-slot":`dialog-footer`,className:V(`-mx-4 -mb-4 flex flex-col-reverse gap-2 rounded-b-xl border-t bg-muted/50 p-4 sm:flex-row sm:justify-end`,e),...r,children:[n,t&&(0,g.jsx)(m.Dialog.Close,{asChild:!0,children:(0,g.jsx)(H,{variant:`outline`,children:`Close`})})]})}var tr=c.forwardRef(function({className:e,...t},n){return(0,g.jsx)(m.Dialog.Title,{ref:n,"data-slot":`dialog-title`,className:V(`text-base leading-none font-medium`,e),...t})}),nr=c.forwardRef(function({className:e,...t},n){return(0,g.jsx)(m.Dialog.Description,{ref:n,"data-slot":`dialog-description`,className:V(`text-sm text-muted-foreground *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground`,e),...t})}),rr=({messages:e,portalContainer:t,imageUpload:n,onConfirm:r,onCancel:i})=>{let[a,o]=(0,c.useState)(`file`),[s,l]=(0,c.useState)(``),[u,d]=(0,c.useState)(``),[p,m]=(0,c.useState)(!1),[h,_]=(0,c.useState)(null),[v,y]=(0,c.useState)(!1),[b,x]=(0,c.useState)(!1),[S,C]=(0,c.useState)(!1),w=(0,c.useRef)(null),T=(0,c.useRef)(null),E=(0,c.useRef)(!0),D=n?.maxFileSize??5242880,O=v||b,k=a===`file`&&!!s&&!O,A=(h?`key`in h?e[h.key].replace(`{size}`,Fn(D)):h.text:``)||(k?e.imageUploadReselectHint:``),j=!!h,M=!!A,N=!!s&&!h&&!v&&!p,ee=!s||!!h||O||p,P=(0,c.useCallback)(async e=>{if(!e.type.startsWith(`image/`)){l(``),d(``),_({key:`imageUploadInvalidType`});return}if(e.size>D){l(``),d(``),_({key:`imageUploadFileSizeExceeded`});return}_(null),d(Rn(e.name)),m(!1),y(!0);try{let t=n?.upload?await n.upload(e):await Pn(e);if(!E.current)return;if(!t){l(``),_({key:`imageUploadFailed`});return}l(t)}catch(e){if(!E.current)return;let t=n?.upload&&e instanceof Error?e.message:``,r=n?.upload?`imageUploadFailed`:`imageUploadFileReadFailed`;l(``),_(t?{text:t}:{key:r})}finally{E.current&&y(!1)}},[n,D]),te=(0,c.useCallback)(()=>{let e=w.current?.files?.[0];e&&(P(e),w.current.value=``)},[P]),ne=(0,c.useCallback)(e=>{if(m(!1),l(e),!e){_(null);return}_(In(e)?null:{key:`imageUploadInvalidUrl`})},[]),re=(0,c.useCallback)(e=>{e.preventDefault(),e.stopPropagation(),!O&&(e.dataTransfer.dropEffect=`copy`,C(!0))},[O]),ie=(0,c.useCallback)(e=>{e.preventDefault(),e.stopPropagation(),e.currentTarget.contains(e.relatedTarget)||C(!1)},[]),F=(0,c.useCallback)(e=>{if(e.preventDefault(),e.stopPropagation(),C(!1),O)return;let t=e.dataTransfer.files?.[0];t&&P(t)},[O,P]),I=(0,c.useCallback)(e=>{O||(o(e),l(``),d(``),m(!1),_(null))},[O]),ae=(0,c.useCallback)(async()=>{if(O){_({key:`imageUploadUploadingWait`});return}if(!s){_({key:`imageUploadSelectOrEnterImage`});return}if(a===`url`&&!In(s)){_({key:`imageUploadInvalidUrl`});return}_(null),x(!0);try{if(await Ln(s),!E.current)return;r({src:s,alt:u.trim()})}catch{E.current&&(m(!0),_({key:`imageUploadLoadFailed`}))}finally{E.current&&x(!1)}},[u,s,O,r,a]),L=(0,c.useCallback)(e=>{e.key===`Enter`&&!e.shiftKey&&a===`url`&&(e.preventDefault(),ae())},[ae,a]);return(0,c.useEffect)(()=>(E.current=!0,()=>{E.current=!1}),[]),(0,c.useEffect)(()=>{a===`url`&&T.current?.focus()},[a]),(0,g.jsx)(Yn,{open:!0,onOpenChange:e=>!e&&i(),children:(0,g.jsxs)(Qn,{container:t,className:`zt-md-image-upload-content-shell max-w-2xl sm:!max-w-2xl max-h-[90vh] overflow-hidden flex flex-col`,closeLabel:e.imageUploadCancelLabel,onCloseAutoFocus:e=>e.preventDefault(),onMouseDown:e=>e.stopPropagation(),onKeyDown:L,children:[(0,g.jsxs)($n,{children:[(0,g.jsx)(tr,{children:e.imageUploadDialogTitle}),(0,g.jsx)(nr,{className:`sr-only`,children:`${e.imageUploadFileTab},${e.imageUploadUrlTab}`})]}),(0,g.jsxs)(`div`,{className:`zt-md-image-upload-segmented`,role:`group`,"aria-label":e.imageUploadDialogTitle,children:[(0,g.jsx)(H,{type:`button`,variant:`ghost`,className:`zt-md-image-upload-segment`,"data-active":a===`file`?`true`:`false`,"aria-pressed":a===`file`,disabled:O,onClick:()=>I(`file`),children:e.imageUploadFileTab}),(0,g.jsx)(H,{type:`button`,variant:`ghost`,className:`zt-md-image-upload-segment`,"data-active":a===`url`?`true`:`false`,"aria-pressed":a===`url`,disabled:O,onClick:()=>I(`url`),children:e.imageUploadUrlTab})]}),(0,g.jsx)(`div`,{className:`zt-md-image-upload-content`,children:(0,g.jsxs)(`div`,{className:`zt-md-image-upload-control`,children:[a===`file`?(0,g.jsxs)(`div`,{className:`zt-md-image-upload-file`,children:[(0,g.jsx)(`input`,{ref:w,id:Mn,type:`file`,accept:`image/*`,className:`zt-md-image-upload-file-input`,disabled:O,onChange:te}),(0,g.jsx)(`label`,{htmlFor:Mn,className:`zt-md-image-upload-file-label`,"data-drag-over":S?`true`:`false`,"data-has-preview":s?`true`:`false`,"data-disabled":O?`true`:`false`,"aria-disabled":O,onClick:e=>{O&&e.preventDefault()},onDragOver:re,onDragLeave:ie,onDrop:F,children:v?(0,g.jsxs)(g.Fragment,{children:[(0,g.jsx)(`div`,{className:`zt-md-image-upload-file-icon`,children:(0,g.jsx)(f.Loader2,{size:40,className:`zt-md-image-upload-spin`})}),(0,g.jsx)(`div`,{className:`zt-md-image-upload-file-text`,children:e.imageUploadUploadingLabel})]}):s?(0,g.jsx)(`div`,{className:`zt-md-image-upload-file-preview`,children:p?(0,g.jsxs)(`div`,{className:`zt-md-image-upload-preview-error`,children:[(0,g.jsx)(f.ImageOff,{size:40}),(0,g.jsx)(`span`,{children:e.imageUploadLoadFailed})]}):(0,g.jsx)(`img`,{src:s,alt:``,onLoad:()=>m(!1),onError:()=>m(!0)})}):(0,g.jsxs)(g.Fragment,{children:[(0,g.jsx)(`div`,{className:`zt-md-image-upload-file-icon`,children:(0,g.jsx)(f.ImagePlus,{size:40})}),(0,g.jsx)(`div`,{className:`zt-md-image-upload-file-text`,children:e.imageUploadDropLabel}),(0,g.jsx)(`div`,{className:`zt-md-image-upload-file-hint`,children:e.imageUploadSupportsAndMax.replace(`{size}`,Fn(D))})]})})]}):(0,g.jsxs)(`div`,{className:`zt-md-image-upload-url`,children:[(0,g.jsx)(`label`,{className:`zt-md-image-upload-label`,htmlFor:`zt-md-image-upload-url-input`,children:e.imageUploadUrlTab}),(0,g.jsx)(`input`,{ref:T,id:`zt-md-image-upload-url-input`,type:`url`,className:`zt-md-image-upload-url-input`,placeholder:e.imageUploadUrlPlaceholder,value:s,disabled:O,onChange:e=>ne(e.target.value)}),s&&!h?(0,g.jsx)(`div`,{className:`zt-md-image-upload-url-preview`,children:p?(0,g.jsxs)(`div`,{className:`zt-md-image-upload-preview-error`,children:[(0,g.jsx)(f.ImageOff,{size:32}),(0,g.jsx)(`span`,{children:e.imageUploadLoadFailed})]}):(0,g.jsx)(`img`,{src:s,alt:``,onLoad:()=>m(!1),onError:()=>m(!0)})}):null]}),N?(0,g.jsxs)(`div`,{className:`zt-md-image-upload-alt`,children:[(0,g.jsx)(`label`,{className:`zt-md-image-upload-label`,htmlFor:Nn,children:e.imageUploadAltLabel}),(0,g.jsx)(`input`,{id:Nn,type:`text`,className:`zt-md-image-upload-alt-input`,placeholder:e.imageUploadAltPlaceholder,value:u,disabled:O,onChange:e=>d(e.target.value)})]}):null,(0,g.jsxs)(`div`,{className:`zt-md-image-upload-file-hint zt-md-image-upload-reselect-hint`,"data-error":j?`true`:`false`,"data-placeholder":M?`false`:`true`,role:j?`alert`:void 0,"aria-live":j?`polite`:`off`,"aria-hidden":!M,children:[j?(0,g.jsx)(f.AlertCircle,{size:14,className:`zt-md-image-upload-hint-icon`}):null,(0,g.jsx)(`span`,{className:`zt-md-image-upload-hint-text`,children:A||e.imageUploadReselectHint})]})]})}),(0,g.jsxs)(er,{children:[(0,g.jsx)(H,{type:`button`,variant:`outline`,onClick:i,children:e.imageUploadCancelLabel}),(0,g.jsx)(H,{type:`button`,disabled:ee,onClick:()=>{ae()},children:v?e.imageUploadUploadingLabel:b?e.imageUploadInsertingLabel:e.imageUploadConfirmLabel})]})]})})},ir=[`--zt-font`,`--zt-font-mono`,`--zt-bg`,`--zt-surface`,`--zt-elevated`,`--zt-popover`,`--zt-hover`,`--zt-active`,`--zt-control-active`,`--zt-fg`,`--zt-muted`,`--zt-border`,`--zt-border-strong`,`--zt-primary`,`--zt-primary-foreground`,`--zt-secondary`,`--zt-accent`,`--zt-destructive`,`--zt-destructive-foreground`,`--zt-overlay`,`--zt-shadow-sm`,`--zt-shadow-md`,`--zt-shadow-lg`,`--zt-radius`,`--zt-radius-lg`],ar=(e,t)=>{if(!t)return;let n=window.getComputedStyle(t);ir.forEach(t=>{let r=n.getPropertyValue(t);r&&e.style.setProperty(t,r.trim())})},or=(e,t)=>{let n=e.closest(`.zt-md`),r=n?.classList.contains(`zt-md-dark`)?`zt-md-dark`:`zt-md-light`,i=document.createElement(`div`);return i.className=`zt-md zt-md-dialog-host ${t} ${r}`,ar(i,n),document.body.appendChild(i),i},sr=e=>{let t=or(e.portalContainer,`zt-md-image-upload-host`),n=(0,oe.createRoot)(t),r=e=>{o(),queueMicrotask(()=>{n.unmount(),t.remove(),e?.()})},i=()=>{r(()=>{e.view?.focus?.()})},a=()=>{n.render((0,c.createElement)(rr,{messages:{...e.messages},portalContainer:t,imageUpload:e.imageUpload,onConfirm:t=>{let n=jn(e.view,{src:t.src,alt:t.alt,title:``});r(()=>{n&&e.view?.focus?.()})},onCancel:i}))},o=W(e.messages,a);a()},cr=`math_block`,lr=`Backspace`,ur=e=>e.key!==lr||e.defaultPrevented||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey,dr=e=>{if(e.parent.type.name!==`paragraph`||e.parentOffset!==0||e.depth<1)return null;let t=e.index(e.depth-1);if(t<=0)return null;let n=e.node(e.depth-1).child(t-1);return n.type.name===cr?{previousBlock:n,previousBlockStart:e.before(e.depth)-n.nodeSize}:null},fr=(e,t)=>{let{selection:n}=e.state;if(!n.empty)return!1;let r=n.$from,i=dr(r);if(!i)return!1;let a=r.parent.textContent.length===0,o=r.before(r.depth),s=o+r.parent.nodeSize;t.preventDefault();let c=e.state.tr;return a&&c.delete(o,s),c.setSelection(v.NodeSelection.create(c.doc,i.previousBlockStart)).scrollIntoView(),e.dispatch(c),!0},pr=(0,I.$prose)(()=>new v.Plugin({key:new v.PluginKey(`zt-md-math-backspace-entry`),props:{handleKeyDown:(e,t)=>ur(t)?!1:fr(e,t)}})),mr=`math_block`,hr=5,gr=1200,_r=q(`Copy`,{size:14,strokeWidth:2}),vr=q(`Check`,{size:14,strokeWidth:2}),yr=q(`Trash2`,{size:14,strokeWidth:2}),br=e=>typeof e==`function`?e():null,xr=e=>typeof e.props.editable==`function`?e.props.editable(e.state):e.editable,Sr=class{syncEditableState(){this.dom.dataset.editable=xr(this.view)?`true`:`false`}constructor(e,t,n,r){this.pointerStartX=null,this.pointerStartY=null,this.hasDragged=!1,this.isDeletingByBackspace=!1,this.copyFeedbackTimer=null,this.handleClick=()=>{if(this.hasDragged){this.hasDragged=!1;return}this.enterEditMode()},this.handlePointerDown=e=>{this.pointerStartX=e.clientX,this.pointerStartY=e.clientY,this.hasDragged=!1},this.handlePointerMove=e=>{if(this.pointerStartX===null||this.pointerStartY===null)return;let t=Math.abs(e.clientX-this.pointerStartX),n=Math.abs(e.clientY-this.pointerStartY);(t>=hr||n>=hr)&&(this.hasDragged=!0)},this.handlePointerUp=()=>{this.pointerStartX=null,this.pointerStartY=null},this.handleCopyClick=e=>{if(e.preventDefault(),e.stopPropagation(),!xr(this.view))return;let t=typeof this.node.attrs.value==`string`?this.node.attrs.value:``;(typeof navigator<`u`&&navigator.clipboard?.writeText?navigator.clipboard.writeText(t):Promise.resolve()).then(()=>{this.copyButton.innerHTML=vr,this.copyButton.dataset.copied=`true`,this.copyFeedbackTimer!==null&&clearTimeout(this.copyFeedbackTimer),this.copyFeedbackTimer=setTimeout(()=>{this.copyButton.innerHTML=_r,delete this.copyButton.dataset.copied,this.copyFeedbackTimer=null},gr)}).catch(()=>{})},this.handleDeleteClick=e=>{e.preventDefault(),e.stopPropagation(),xr(this.view)&&this.deleteCurrentMathBlock()},this.handleInput=()=>{let e=this.sourceTextarea.value,t=br(this.getPos);if(t===null)return;this.renderMath(e);let n=this.view.state.tr.setNodeMarkup(t,void 0,{...this.node.attrs,value:e});n.docChanged&&this.view.dispatch(n)},this.handleKeyDown=e=>{let t=this.sourceTextarea.selectionStart,n=this.sourceTextarea.selectionEnd;if(e.key===`Backspace`){if(!(t===0&&n===0)||br(this.getPos)===null)return;e.preventDefault(),this.deleteCurrentMathBlock();return}if(e.key!==`ArrowUp`&&e.key!==`ArrowDown`||e.defaultPrevented||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey||t!==n)return;let r=this.sourceTextarea.value,i=r.slice(0,t),a=r.slice(n),o=!i.includes(`
|
|
2
2
|
`),s=!a.includes(`
|
|
3
|
-
`);if(!(e.key===`ArrowUp`&&o||e.key===`ArrowDown`&&s))return;let c=er(this.getPos);c!==null&<(this.view,c,this.node,e.key)&&e.preventDefault()},this.handleBlur=()=>{this.isDeletingByBackspace||this.exitEditMode()},this.node=e,this.view=t,this.getPos=n,this.messages=r,this.dom=document.createElement(`div`),this.dom.dataset.type=Jn,this.dom.className=`zt-md-math-block`,this.syncEditableState(),this.sourceContainer=document.createElement(`div`),this.sourceContainer.className=`zt-md-math-block-source`,this.sourceContainer.hidden=!0,this.sourceTextarea=document.createElement(`textarea`),this.sourceTextarea.className=`zt-md-math-block-textarea`,this.sourceTextarea.setAttribute(`aria-label`,this.messages.mathBlockSourceAriaLabel),this.sourceTextarea.spellcheck=!1,this.previewContainer=document.createElement(`div`),this.previewContainer.className=`zt-md-math-block-preview`,this.actionsContainer=document.createElement(`div`),this.actionsContainer.className=`zt-md-math-block-actions`,this.copyButton=document.createElement(`button`),this.copyButton.type=`button`,this.copyButton.className=`zt-md-math-block-action-button`,this.copyButton.setAttribute(`aria-label`,this.messages.mathBlockCopyAriaLabel),this.copyButton.innerHTML=Zn,this.deleteButton=document.createElement(`button`),this.deleteButton.type=`button`,this.deleteButton.className=`zt-md-math-block-action-button zt-md-math-block-action-button-danger`,this.deleteButton.setAttribute(`aria-label`,this.messages.mathBlockDeleteAriaLabel),this.deleteButton.innerHTML=$n,this.errorContainer=document.createElement(`div`),this.errorContainer.className=`zt-md-math-block-error`,this.errorContainer.hidden=!0,this.actionsContainer.append(this.copyButton,this.deleteButton),this.sourceContainer.appendChild(this.sourceTextarea),this.previewContainer.appendChild(this.errorContainer),this.dom.append(this.actionsContainer,this.sourceContainer,this.previewContainer),this.syncFromNode(e),this.dom.addEventListener(`click`,this.handleClick),this.dom.addEventListener(`pointerdown`,this.handlePointerDown),this.dom.addEventListener(`pointermove`,this.handlePointerMove),this.dom.addEventListener(`pointerup`,this.handlePointerUp),this.dom.addEventListener(`pointercancel`,this.handlePointerUp),this.copyButton.addEventListener(`click`,this.handleCopyClick),this.deleteButton.addEventListener(`click`,this.handleDeleteClick),this.sourceTextarea.addEventListener(`input`,this.handleInput),this.sourceTextarea.addEventListener(`keydown`,this.handleKeyDown),this.sourceTextarea.addEventListener(`blur`,this.handleBlur),this.stopObservingMessages=W(r,()=>{this.sourceTextarea.setAttribute(`aria-label`,r.mathBlockSourceAriaLabel),this.copyButton.setAttribute(`aria-label`,r.mathBlockCopyAriaLabel),this.deleteButton.setAttribute(`aria-label`,r.mathBlockDeleteAriaLabel),this.errorContainer.hidden||(this.errorContainer.textContent=r.mathRenderError)})}deleteCurrentMathBlock(){let e=er(this.getPos);if(e===null)return;this.isDeletingByBackspace=!0;let t=this.view.state.tr.delete(e,e+this.node.nodeSize),n=Math.min(e,t.doc.content.size);t.setSelection(v.TextSelection.near(t.doc.resolve(n),-1)).scrollIntoView(),this.view.dispatch(t),requestAnimationFrame(()=>{this.view.focus(),this.isDeletingByBackspace=!1})}syncFromNode(e){let t=typeof e.attrs.value==`string`?e.attrs.value:``;this.dom.dataset.value=t,this.sourceTextarea.value=t,this.renderMath(t)}renderMath(e){this.errorContainer.hidden=!0,this.errorContainer.textContent=``;try{z.default.render(e,this.previewContainer,{displayMode:!0,throwOnError:!0}),this.previewContainer.appendChild(this.errorContainer)}catch{this.previewContainer.textContent=e,this.errorContainer.hidden=!1,this.errorContainer.textContent=this.messages.mathRenderError,this.previewContainer.appendChild(this.errorContainer)}}enterEditMode(){tr(this.view)&&(this.sourceContainer.hidden=!1,this.dom.classList.add(`zt-md-math-block-editing`),this.sourceTextarea.focus())}exitEditMode(){this.sourceContainer.hidden=!0,this.dom.classList.remove(`zt-md-math-block-editing`)}update(e){return e.type.name===Jn?(this.node=e,this.syncEditableState(),this.syncFromNode(e),!0):!1}selectNode(){this.enterEditMode()}deselectNode(){this.exitEditMode()}stopEvent(e){let t=e.target;return t instanceof Node?this.sourceContainer.contains(t)||this.actionsContainer.contains(t):!1}ignoreMutation(){return!0}destroy(){this.stopObservingMessages(),this.dom.removeEventListener(`click`,this.handleClick),this.dom.removeEventListener(`pointerdown`,this.handlePointerDown),this.dom.removeEventListener(`pointermove`,this.handlePointerMove),this.dom.removeEventListener(`pointerup`,this.handlePointerUp),this.dom.removeEventListener(`pointercancel`,this.handlePointerUp),this.copyButton.removeEventListener(`click`,this.handleCopyClick),this.deleteButton.removeEventListener(`click`,this.handleDeleteClick),this.sourceTextarea.removeEventListener(`input`,this.handleInput),this.sourceTextarea.removeEventListener(`keydown`,this.handleKeyDown),this.sourceTextarea.removeEventListener(`blur`,this.handleBlur),this.copyFeedbackTimer!==null&&(clearTimeout(this.copyFeedbackTimer),this.copyFeedbackTimer=null),this.copyButton.innerHTML=Zn,delete this.copyButton.dataset.copied}},rr=(e=U())=>(t,n,r)=>new nr(t,n,typeof r==`function`?()=>{let e=r();return typeof e==`number`?e:0}:!1,e),ir=`math_inline`,q=new v.PluginKey(`zt-md-math-inline-edit`),ar=e=>typeof e.props.editable==`function`?e.props.editable(e.state):e.editable,or=e=>e?.type.name===ir,sr=e=>String(e.attrs.value??e.textContent??``),cr=(e,t,n)=>{ar(e)&&e.dispatch(e.state.tr.setMeta(q,{type:`open`,position:t,caret:n?.caret===`start`?`start`:`end`}))},lr=class{createSafeTextSelection(e,t){try{return v.TextSelection.create(e,t)}catch{return v.TextSelection.near(e.resolve(t),-1)}}resolveArrowExitTarget(e){if(this.currentPosition===null)return null;let t=this.resolveCurrentNode();if(!t)return null;let n=this.sourceInput.selectionStart,r=this.sourceInput.selectionEnd;if(n===null||r===null||n!==r)return null;if(e.key===`ArrowLeft`&&n===0||e.key===`ArrowUp`)return this.currentPosition;let i=this.sourceInput.value.length;return e.key===`ArrowRight`&&n===i||e.key===`ArrowDown`?this.currentPosition+t.nodeSize:null}shouldDeleteMathInlineOnBackspace(e){if(e.key!==`Backspace`||this.currentPosition===null)return!1;let t=this.sourceInput.selectionStart,n=this.sourceInput.selectionEnd;return t===null||n===null||t!==0||n!==0?!1:!!this.resolveCurrentNode()}deleteCurrentMathInlineAndFocusEditor(){if(this.currentPosition===null)return;let e=this.resolveCurrentNode();if(!e){this.closeEditor(!1);return}let t=this.currentPosition,n=this.currentPosition+e.nodeSize,r=this.view.state.tr.delete(t,n);r.setSelection(this.createSafeTextSelection(r.doc,t)).setMeta(q,{type:`close`}).scrollIntoView(),this.view.dispatch(r),this.view.focus()}constructor(e,t){this.currentPosition=null,this.currentMathInlineElement=null,this.isCommitting=!1,this.currentCaret=`end`,this.handleMouseDown=e=>{e.stopPropagation()},this.handleBeforeInput=e=>{e.stopPropagation()},this.handleInput=e=>{e.stopPropagation(),this.renderMath(this.sourceInput.value)},this.handleKeyDown=e=>{if(e.stopPropagation(),this.shouldDeleteMathInlineOnBackspace(e)){e.preventDefault(),this.deleteCurrentMathInlineAndFocusEditor();return}let t=this.resolveArrowExitTarget(e);if(t!==null){e.preventDefault(),this.commitCurrentValue(t);return}if(e.key===`Enter`){e.preventDefault(),this.commitCurrentValue();return}e.key===`Escape`&&(e.preventDefault(),this.closeEditor(!0))},this.handleBlur=()=>{this.isCommitting||this.currentPosition===null||this.commitCurrentValue()},this.handleEditorFocusIn=e=>{if(this.isCommitting||this.currentPosition===null)return;let t=e.target;t instanceof Node&&this.host.contains(t)||this.commitCurrentValue()},this.view=e,this.messages=t,this.host=document.createElement(`span`),this.host.className=`zt-md-math-inline-editor`,this.host.hidden=!0,this.sourceInput=document.createElement(`input`),this.sourceInput.type=`text`,this.sourceInput.className=`zt-md-math-inline-editor-input`,this.sourceInput.setAttribute(`aria-label`,this.messages.mathBlockSourceAriaLabel),this.sourceInput.spellcheck=!1,this.previewContainer=document.createElement(`span`),this.previewContainer.className=`zt-md-math-inline-editor-preview`,this.errorContainer=document.createElement(`span`),this.errorContainer.className=`zt-md-math-inline-editor-error`,this.errorContainer.hidden=!0,this.host.append(this.sourceInput,this.previewContainer,this.errorContainer),this.sourceInput.addEventListener(`input`,this.handleInput),this.sourceInput.addEventListener(`beforeinput`,this.handleBeforeInput),this.sourceInput.addEventListener(`keydown`,this.handleKeyDown),this.sourceInput.addEventListener(`blur`,this.handleBlur),this.host.addEventListener(`mousedown`,this.handleMouseDown),this.view.dom.addEventListener(`focusin`,this.handleEditorFocusIn),this.update(e),this.stopObservingMessages=W(t,()=>{this.sourceInput.setAttribute(`aria-label`,t.mathBlockSourceAriaLabel),this.errorContainer.hidden||(this.errorContainer.textContent=t.mathRenderError)})}renderMath(e){this.errorContainer.hidden=!0,this.errorContainer.textContent=``,this.previewContainer.textContent=``;try{z.default.render(e,this.previewContainer,{displayMode:!1,throwOnError:!0})}catch{this.previewContainer.textContent=e,this.errorContainer.hidden=!1,this.errorContainer.textContent=this.messages.mathRenderError}}resolveCurrentNode(){if(this.currentPosition===null)return null;let e=this.view.state.doc.nodeAt(this.currentPosition);return or(e)?e:null}openEditor(e){if(!ar(this.view)){this.closeEditor(!1);return}let t=this.view.state.doc.nodeAt(e);if(!or(t)){this.closeEditor(!1);return}this.currentPosition=e,this.sourceInput.value=sr(t),this.renderMath(this.sourceInput.value);let n=this.resolveMathInlineElement(e);if(!n){this.closeEditor(!1);return}this.currentMathInlineElement=n,n.dataset.editing=`true`,n.append(this.host),this.host.hidden=!1,requestAnimationFrame(()=>{if(this.currentPosition!==e)return;this.sourceInput.focus();let t=this.sourceInput.value.length;if(this.currentCaret===`start`){this.sourceInput.setSelectionRange(0,0);return}this.sourceInput.setSelectionRange(t,t)})}commitCurrentValue(e){if(this.currentPosition===null)return;let t=this.resolveCurrentNode();if(!t){this.closeEditor(!1);return}let n=this.sourceInput.value,r=typeof e==`number`?e:this.currentPosition+t.nodeSize,i=this.view.state.tr.setNodeMarkup(this.currentPosition,void 0,{...t.attrs,value:n});i.setSelection(this.createSafeTextSelection(i.doc,r)).setMeta(q,{type:`close`}).scrollIntoView(),this.isCommitting=!0,this.view.dispatch(i),this.isCommitting=!1,this.view.focus()}closeEditor(e){this.currentMathInlineElement&&(this.currentMathInlineElement.dataset.editing=`false`),this.currentPosition=null,this.currentMathInlineElement=null,this.host.hidden=!0,this.host.remove(),e&&this.view.dispatch(this.view.state.tr.setMeta(q,{type:`close`}))}resolveMathInlineElement(e){let t=this.view.nodeDOM(e);return t instanceof HTMLElement?t:null}update(e){if(this.view=e,!ar(e)){this.closeEditor(!1);return}let t=q.getState(e.state);if(!t||t.position===null){this.currentPosition!==null&&this.closeEditor(!1);return}if(this.currentPosition!==t.position){this.currentCaret=t.caret,this.openEditor(t.position);return}if(!this.resolveCurrentNode()){this.closeEditor(!0);return}}destroy(){this.stopObservingMessages(),this.sourceInput.removeEventListener(`input`,this.handleInput),this.sourceInput.removeEventListener(`beforeinput`,this.handleBeforeInput),this.sourceInput.removeEventListener(`keydown`,this.handleKeyDown),this.sourceInput.removeEventListener(`blur`,this.handleBlur),this.host.removeEventListener(`mousedown`,this.handleMouseDown),this.view.dom.removeEventListener(`focusin`,this.handleEditorFocusIn),this.closeEditor(!1)}},ur=(e,t)=>(0,L.$prose)(()=>new v.Plugin({key:q,state:{init:()=>({position:null,caret:`end`}),apply:(e,t)=>{let n=e.getMeta(q);if(n?.type===`open`&&typeof n.position==`number`)return{position:n.position,caret:n.caret===`start`?`start`:`end`};if(n?.type===`close`)return{position:null,caret:`end`};if(t.position===null||!e.docChanged)return t;let r=e.mapping.map(t.position,-1);return or(e.doc.nodeAt(r))?{position:r,caret:t.caret}:{position:null,caret:`end`}}},view:t=>new lr(t,e)})),dr=`math_inline`,fr=e=>typeof e==`function`?e():null,pr=e=>typeof e.props.editable==`function`?e.props.editable(e.state):e.editable,mr=e=>String(e.attrs.value??e.textContent??``),hr=class{syncEditableState(){this.dom.dataset.editable=pr(this.view)?`true`:`false`}constructor(e,t,n,r){this.handleMouseDown=e=>{pr(this.view)||(e.preventDefault(),e.stopPropagation())},this.handleClick=e=>{if(e.preventDefault(),e.stopPropagation(),!pr(this.view))return;let t=fr(this.getPos);t!==null&&cr(this.view,t)},this.node=e,this.view=t,this.getPos=n,this.messages=r,this.dom=document.createElement(`span`),this.dom.dataset.type=dr,this.dom.className=`zt-md-math-inline`,this.dom.dataset.editing=`false`,this.syncEditableState(),this.previewContainer=document.createElement(`span`),this.previewContainer.className=`zt-md-math-inline-preview`,this.errorContainer=document.createElement(`span`),this.errorContainer.className=`zt-md-math-inline-error`,this.errorContainer.hidden=!0,this.dom.append(this.previewContainer,this.errorContainer),this.syncFromNode(e),this.dom.addEventListener(`mousedown`,this.handleMouseDown),this.dom.addEventListener(`click`,this.handleClick),this.stopObservingMessages=W(r,()=>{this.errorContainer.hidden||(this.errorContainer.textContent=r.mathRenderError)})}syncFromNode(e){let t=mr(e);this.dom.dataset.value=t,this.renderMath(t)}renderMath(e){this.errorContainer.hidden=!0,this.errorContainer.textContent=``,this.previewContainer.textContent=``;try{z.default.render(e,this.previewContainer,{displayMode:!1,throwOnError:!0})}catch{this.previewContainer.textContent=e,this.errorContainer.hidden=!1,this.errorContainer.textContent=this.messages.mathRenderError}}update(e){return e.type.name===dr?(this.node=e,this.syncEditableState(),this.syncFromNode(e),!0):!1}stopEvent(e){let t=e.target;return t instanceof Element?e.type===`click`||!!t.closest(`.zt-md-math-inline-editor`):e.type===`click`}ignoreMutation(){return!0}destroy(){this.stopObservingMessages(),this.dom.removeEventListener(`mousedown`,this.handleMouseDown),this.dom.removeEventListener(`click`,this.handleClick)}},gr=(e=U())=>(t,n,r)=>new hr(t,n,typeof r==`function`?()=>{let e=r();return typeof e==`number`?e:0}:!1,e),_r=`math_inline`,vr=`zt-md-math-inline-arrow-navigation`,yr={ArrowLeft:{positionKey:`from`},ArrowRight:{positionKey:`to`}},br={ArrowLeft:`end`,ArrowRight:`start`},xr={Backspace:`before`,Delete:`after`},Sr=e=>e instanceof Element?!!e.closest(`.zt-md-math-inline-editor`):!1,Cr=e=>e?.type.name===_r,wr=e=>!xr[e.key]||e.defaultPrevented||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey||Sr(e.target)||Sr(document.activeElement),Tr=(e,t)=>{if(!yr[t.key]||Sr(t.target))return!1;let{selection:n}=e.state;return!(n instanceof v.NodeSelection)||n.node.type.name!==_r?!1:(t.preventDefault(),cr(e,n.from,{caret:br[t.key]??`end`}),!0)},Er=(e,t)=>{let n=yr[t.key];if(!n||Sr(t.target))return!1;let{selection:r}=e.state;if(!r.empty)return!1;let i=r.$from,a=n.positionKey===`from`?i.nodeBefore:i.nodeAfter;return Cr(a)?(t.preventDefault(),cr(e,n.positionKey===`from`?r.from-a.nodeSize:r.from,{caret:br[t.key]??`end`}),!0):!1},Dr=(e,t)=>{try{return v.TextSelection.create(e,t)}catch{return v.TextSelection.near(e.resolve(t),-1)}},Or=(e,t,n)=>{n.preventDefault();let r=t.from,i=e.state.tr.delete(t.from,t.to),a=i.doc.content.size,o=Math.min(r,a);return i.setSelection(Dr(i.doc,o)).scrollIntoView(),e.dispatch(i),e.focus(),!0},kr=(e,t)=>{let n=xr[t.key];if(!n)return!1;let{selection:r}=e.state;if(!r.empty)return!1;let i=r.$from,a=n===`before`?i.nodeBefore:i.nodeAfter;if(!Cr(a))return!1;t.preventDefault();let o=n===`before`?r.from-a.nodeSize:r.from;return e.dispatch(e.state.tr.setSelection(v.NodeSelection.create(e.state.doc,o)).scrollIntoView()),e.focus(),!0},Ar=(e,t)=>{if(wr(t))return!1;let{selection:n}=e.state;return n instanceof v.NodeSelection&&Cr(n.node)?Or(e,n,t):kr(e,t)},jr=(e,t)=>{if(Sr(document.activeElement))return!1;let{selection:n}=e.state;if(!(n instanceof v.NodeSelection)||n.node.type.name!==_r)return!1;let r=n.to,i=r+t.length,a=e.state.tr.insertText(t,r,r);return a.setSelection(v.TextSelection.create(a.doc,i)).scrollIntoView(),e.dispatch(a),e.focus(),!0},Mr=(0,L.$prose)(()=>new v.Plugin({key:new v.PluginKey(vr),props:{handleKeyDown:(e,t)=>Er(e,t)||Ar(e,t)?!0:Tr(e,t),handleTextInput:(e,t,n,r)=>jr(e,r)}})),Nr=`math_inline`,Pr=`math_block`,Fr=/(?:\$)([^$]+)(?:\$)$/,Ir=/^\$\$\s$/,Lr=(0,L.$remark)(`remarkMath`,()=>se.default),Rr=(0,L.$ctx)({},`katexOptions`),zr=(0,L.$nodeSchema)(Nr,e=>({group:`inline`,inline:!0,atom:!0,attrs:{value:{default:``}},parseDOM:[{tag:`span[data-type="${Nr}"]`,getAttrs:e=>{let t=e;return{value:t.dataset.value??t.textContent??``}}}],toDOM:t=>{let n=String(t.attrs.value??t.textContent??``),r=document.createElement(`span`);return r.dataset.type=Nr,r.dataset.value=n,z.default.render(n,r,e.get(Rr.key)),r},parseMarkdown:{match:e=>e.type===`inlineMath`,runner:(e,t,n)=>{let r=String(t.value??``);e.addNode(n,{value:r})}},toMarkdown:{match:e=>e.type.name===Nr,runner:(e,t)=>{let n=String(t.attrs.value??t.textContent??``);e.addNode(`inlineMath`,void 0,n)}}})),Br=(0,L.$nodeSchema)(Pr,e=>({content:`text*`,group:`block`,marks:``,defining:!0,atom:!0,isolating:!0,attrs:{value:{default:``}},parseDOM:[{tag:`div[data-type="${Pr}"]`,preserveWhitespace:`full`,getAttrs:e=>({value:e.dataset.value??``})}],toDOM:t=>{let n=String(t.attrs.value??``),r=document.createElement(`div`);return r.dataset.type=Pr,r.dataset.value=n,z.default.render(n,r,e.get(Rr.key)),r},parseMarkdown:{match:e=>e.type===`math`,runner:(e,t,n)=>{let r=String(t.value??``);e.addNode(n,{value:r})}},toMarkdown:{match:e=>e.type.name===Pr,runner:(e,t)=>{let n=String(t.attrs.value??``);e.addNode(`math`,void 0,n)}}})),Vr=(0,L.$inputRule)(e=>new oe.InputRule(Fr,(t,n,r,i)=>{let a=zr.type(e),o=n[1]??``,s=t.doc.resolve(r);return s.parent.canReplaceWith(s.index(),s.indexAfter(),a)?t.tr.replaceWith(r,i,a.create({value:o})):null})),Hr=[Lr,Rr,zr,Br,(0,L.$inputRule)(e=>new oe.InputRule(Ir,(t,n,r,i)=>{let a=t.doc.resolve(r),o=Br.type(e);return a.node(-1).canReplaceWith(a.index(-1),a.indexAfter(-1),o)?t.tr.delete(r,i).setBlockType(r,r,o):null})),Vr].flat(),Ur=`blockquote`,Wr=`paragraph`,Gr=`Backspace`,Kr=e=>e.key!==Gr||e.defaultPrevented||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey,qr=e=>{if(e.parent.type.name!==Wr||e.parentOffset!==0)return null;for(let t=e.depth;t>0;--t){let n=e.node(t);if(n.type.name!==Ur)continue;let r=e.depth,i=e.index(t);return r<=t||i!==0?null:{paragraphDepth:r,blockquoteDepth:t,blockquoteType:n.type}}return null},Jr=(e,t)=>{let{selection:n}=e.state;if(!n.empty)return!1;let r=n.$from,i=qr(r);if(!i)return!1;let a=r.blockRange(r,e=>e.type===i.blockquoteType);if(!a)return!1;let o=(0,ce.liftTarget)(a);if(o===null)return!1;t.preventDefault();let s=e.state.tr.lift(a,o).scrollIntoView();return e.dispatch(s),!0},Yr=(0,L.$prose)(()=>new v.Plugin({key:new v.PluginKey(`zt-md-blockquote-backspace-lift`),props:{handleKeyDown:(e,t)=>Kr(t)?!1:Jr(e,t)}})),Xr=`Backspace`,Zr=`heading`,Qr=`paragraph`,$r=e=>typeof e.props.editable==`function`?e.props.editable(e.state):e.editable,ei=e=>{if(e.type.name!==Qr)return!1;let t=e.textContent;return t.trim().length===0&&e.content.size===t.length},ti=e=>{if(e.parent.type.name!==Zr||e.parentOffset!==0||e.depth<1)return null;let t=e.index(e.depth-1);if(t<=0)return null;let n=e.node(e.depth-1).child(t-1);if(!ei(n))return null;let r=e.before(e.depth);return{from:r-n.nodeSize,to:r}},ni=(e,t)=>{if(t.key!==Xr||t.defaultPrevented||t.altKey||t.ctrlKey||t.metaKey||t.shiftKey||!$r(e))return!1;let{selection:n}=e.state;if(!n.empty)return!1;let r=ti(n.$from);if(!r)return!1;t.preventDefault();let i=e.state.tr.delete(r.from,r.to);return i.setSelection(v.TextSelection.create(i.doc,r.from+1)).scrollIntoView(),e.dispatch(i),!0},ri=(0,L.$prose)(()=>new v.Plugin({key:new v.PluginKey(`zt-md-heading-backspace-empty-paragraph`),props:{handleKeyDown:(e,t)=>ni(e,t)}})),ii=`heading`,ai=`zt-md-heading-focused`,oi=`zt-md-heading-focus-indicator`,si=e=>{let t=e.selection.$from;for(let n=t.depth;n>0;--n){let r=t.node(n);if(r.type.name!==ii)continue;let i=t.before(n),a=Number(r.attrs.level),o=I.Decoration.node(i,i+r.nodeSize,{class:ai,"data-heading-level":`H${a}`});return I.DecorationSet.create(e.doc,[o])}return I.DecorationSet.empty},ci=(0,L.$prose)(()=>new v.Plugin({key:new v.PluginKey(oi),props:{decorations:si}})),li=`text`,ui={svg:`svg`,html:`html`},di={html:!0,svg:!0},J=e=>{let t=e.trim().toLowerCase();return t?t.startsWith(`canvas-`)?Object.entries(ui).find(([e])=>t.includes(e))?.[1]??t:t:li},fi=e=>t=>{let n=e(t);return{...n,attrs:{...n.attrs,language:{default:li,validate:`string`}},parseMarkdown:{...n.parseMarkdown,runner:(e,t,r)=>{let i={...t,lang:J(String(t.lang??``))};n.parseMarkdown.runner(e,i,r)}},toMarkdown:{...n.toMarkdown,runner:(e,t)=>{let n=J(String(t.attrs.language??``));e.addNode(`code`,void 0,t.content.firstChild?.text||``,{lang:n})}}}},pi=e=>{let t=e.get(C.codeBlockSchema.key);e.set(C.codeBlockSchema.key,fi(t))},mi=e=>di[J(e)]===!0,hi=`code_block`,gi=1200,_i=`html`,vi=`ZT_MD_CODE_BLOCK_PREVIEW_LAYOUT`,yi=[`default-src 'none'`,`style-src 'unsafe-inline'`,`img-src data: blob:`,`font-src data:`,`media-src data: blob:`,`connect-src 'none'`,`frame-src 'none'`,`object-src 'none'`,`form-action 'none'`,`base-uri 'none'`],bi=K(`Copy`,{size:14,strokeWidth:2}),xi=K(`Check`,{size:14,strokeWidth:2}),Si=K(`Trash2`,{size:14,strokeWidth:2}),Ci=K(`Eye`,{size:14,strokeWidth:2}),wi=K(`Code2`,{size:14,strokeWidth:2}),Ti=(e,t)=>`<!doctype html>
|
|
3
|
+
`);if(!(e.key===`ArrowUp`&&o||e.key===`ArrowDown`&&s))return;let c=br(this.getPos);c!==null&&kt(this.view,c,this.node,e.key)&&e.preventDefault()},this.handleBlur=()=>{this.isDeletingByBackspace||this.exitEditMode()},this.node=e,this.view=t,this.getPos=n,this.messages=r,this.dom=document.createElement(`div`),this.dom.dataset.type=mr,this.dom.className=`zt-md-math-block`,this.syncEditableState(),this.sourceContainer=document.createElement(`div`),this.sourceContainer.className=`zt-md-math-block-source`,this.sourceContainer.hidden=!0,this.sourceTextarea=document.createElement(`textarea`),this.sourceTextarea.className=`zt-md-math-block-textarea`,this.sourceTextarea.setAttribute(`aria-label`,this.messages.mathBlockSourceAriaLabel),this.sourceTextarea.spellcheck=!1,this.previewContainer=document.createElement(`div`),this.previewContainer.className=`zt-md-math-block-preview`,this.actionsContainer=document.createElement(`div`),this.actionsContainer.className=`zt-md-math-block-actions`,this.copyButton=document.createElement(`button`),this.copyButton.type=`button`,this.copyButton.className=`zt-md-math-block-action-button`,this.copyButton.setAttribute(`aria-label`,this.messages.mathBlockCopyAriaLabel),this.copyButton.innerHTML=_r,this.deleteButton=document.createElement(`button`),this.deleteButton.type=`button`,this.deleteButton.className=`zt-md-math-block-action-button zt-md-math-block-action-button-danger`,this.deleteButton.setAttribute(`aria-label`,this.messages.mathBlockDeleteAriaLabel),this.deleteButton.innerHTML=yr,this.errorContainer=document.createElement(`div`),this.errorContainer.className=`zt-md-math-block-error`,this.errorContainer.hidden=!0,this.actionsContainer.append(this.copyButton,this.deleteButton),this.sourceContainer.appendChild(this.sourceTextarea),this.previewContainer.appendChild(this.errorContainer),this.dom.append(this.actionsContainer,this.sourceContainer,this.previewContainer),this.syncFromNode(e),this.dom.addEventListener(`click`,this.handleClick),this.dom.addEventListener(`pointerdown`,this.handlePointerDown),this.dom.addEventListener(`pointermove`,this.handlePointerMove),this.dom.addEventListener(`pointerup`,this.handlePointerUp),this.dom.addEventListener(`pointercancel`,this.handlePointerUp),this.copyButton.addEventListener(`click`,this.handleCopyClick),this.deleteButton.addEventListener(`click`,this.handleDeleteClick),this.sourceTextarea.addEventListener(`input`,this.handleInput),this.sourceTextarea.addEventListener(`keydown`,this.handleKeyDown),this.sourceTextarea.addEventListener(`blur`,this.handleBlur),this.stopObservingMessages=W(r,()=>{this.sourceTextarea.setAttribute(`aria-label`,r.mathBlockSourceAriaLabel),this.copyButton.setAttribute(`aria-label`,r.mathBlockCopyAriaLabel),this.deleteButton.setAttribute(`aria-label`,r.mathBlockDeleteAriaLabel),this.errorContainer.hidden||(this.errorContainer.textContent=r.mathRenderError)})}deleteCurrentMathBlock(){let e=br(this.getPos);if(e===null)return;this.isDeletingByBackspace=!0;let t=this.view.state.tr.delete(e,e+this.node.nodeSize),n=Math.min(e,t.doc.content.size);t.setSelection(v.TextSelection.near(t.doc.resolve(n),-1)).scrollIntoView(),this.view.dispatch(t),requestAnimationFrame(()=>{this.view.focus(),this.isDeletingByBackspace=!1})}syncFromNode(e){let t=typeof e.attrs.value==`string`?e.attrs.value:``;this.dom.dataset.value=t,this.sourceTextarea.value=t,this.renderMath(t)}renderMath(e){this.errorContainer.hidden=!0,this.errorContainer.textContent=``;try{R.default.render(e,this.previewContainer,{displayMode:!0,throwOnError:!0}),this.previewContainer.appendChild(this.errorContainer)}catch{this.previewContainer.textContent=e,this.errorContainer.hidden=!1,this.errorContainer.textContent=this.messages.mathRenderError,this.previewContainer.appendChild(this.errorContainer)}}enterEditMode(){xr(this.view)&&(this.sourceContainer.hidden=!1,this.dom.classList.add(`zt-md-math-block-editing`),this.sourceTextarea.focus())}exitEditMode(){this.sourceContainer.hidden=!0,this.dom.classList.remove(`zt-md-math-block-editing`)}update(e){return e.type.name===mr?(this.node=e,this.syncEditableState(),this.syncFromNode(e),!0):!1}selectNode(){this.enterEditMode()}deselectNode(){this.exitEditMode()}stopEvent(e){let t=e.target;return t instanceof Node?this.sourceContainer.contains(t)||this.actionsContainer.contains(t):!1}ignoreMutation(){return!0}destroy(){this.stopObservingMessages(),this.dom.removeEventListener(`click`,this.handleClick),this.dom.removeEventListener(`pointerdown`,this.handlePointerDown),this.dom.removeEventListener(`pointermove`,this.handlePointerMove),this.dom.removeEventListener(`pointerup`,this.handlePointerUp),this.dom.removeEventListener(`pointercancel`,this.handlePointerUp),this.copyButton.removeEventListener(`click`,this.handleCopyClick),this.deleteButton.removeEventListener(`click`,this.handleDeleteClick),this.sourceTextarea.removeEventListener(`input`,this.handleInput),this.sourceTextarea.removeEventListener(`keydown`,this.handleKeyDown),this.sourceTextarea.removeEventListener(`blur`,this.handleBlur),this.copyFeedbackTimer!==null&&(clearTimeout(this.copyFeedbackTimer),this.copyFeedbackTimer=null),this.copyButton.innerHTML=_r,delete this.copyButton.dataset.copied}},Cr=(e=U())=>(t,n,r)=>new Sr(t,n,typeof r==`function`?()=>{let e=r();return typeof e==`number`?e:0}:!1,e),wr=`math_inline`,J=new v.PluginKey(`zt-md-math-inline-edit`),Tr=e=>typeof e.props.editable==`function`?e.props.editable(e.state):e.editable,Er=e=>e?.type.name===wr,Dr=e=>String(e.attrs.value??e.textContent??``),Or=(e,t,n)=>{Tr(e)&&e.dispatch(e.state.tr.setMeta(J,{type:`open`,position:t,caret:n?.caret===`start`?`start`:`end`}))},kr=class{createSafeTextSelection(e,t){try{return v.TextSelection.create(e,t)}catch{return v.TextSelection.near(e.resolve(t),-1)}}resolveArrowExitTarget(e){if(this.currentPosition===null)return null;let t=this.resolveCurrentNode();if(!t)return null;let n=this.sourceInput.selectionStart,r=this.sourceInput.selectionEnd;if(n===null||r===null||n!==r)return null;if(e.key===`ArrowLeft`&&n===0||e.key===`ArrowUp`)return this.currentPosition;let i=this.sourceInput.value.length;return e.key===`ArrowRight`&&n===i||e.key===`ArrowDown`?this.currentPosition+t.nodeSize:null}shouldDeleteMathInlineOnBackspace(e){if(e.key!==`Backspace`||this.currentPosition===null)return!1;let t=this.sourceInput.selectionStart,n=this.sourceInput.selectionEnd;return t===null||n===null||t!==0||n!==0?!1:!!this.resolveCurrentNode()}deleteCurrentMathInlineAndFocusEditor(){if(this.currentPosition===null)return;let e=this.resolveCurrentNode();if(!e){this.closeEditor(!1);return}let t=this.currentPosition,n=this.currentPosition+e.nodeSize,r=this.view.state.tr.delete(t,n);r.setSelection(this.createSafeTextSelection(r.doc,t)).setMeta(J,{type:`close`}).scrollIntoView(),this.view.dispatch(r),this.view.focus()}constructor(e,t){this.currentPosition=null,this.currentMathInlineElement=null,this.isCommitting=!1,this.currentCaret=`end`,this.handleMouseDown=e=>{e.stopPropagation()},this.handleBeforeInput=e=>{e.stopPropagation()},this.handleInput=e=>{e.stopPropagation(),this.renderMath(this.sourceInput.value)},this.handleKeyDown=e=>{if(e.stopPropagation(),this.shouldDeleteMathInlineOnBackspace(e)){e.preventDefault(),this.deleteCurrentMathInlineAndFocusEditor();return}let t=this.resolveArrowExitTarget(e);if(t!==null){e.preventDefault(),this.commitCurrentValue(t);return}if(e.key===`Enter`){e.preventDefault(),this.commitCurrentValue();return}e.key===`Escape`&&(e.preventDefault(),this.closeEditor(!0))},this.handleBlur=()=>{this.isCommitting||this.currentPosition===null||this.commitCurrentValue()},this.handleEditorFocusIn=e=>{if(this.isCommitting||this.currentPosition===null)return;let t=e.target;t instanceof Node&&this.host.contains(t)||this.commitCurrentValue()},this.view=e,this.messages=t,this.host=document.createElement(`span`),this.host.className=`zt-md-math-inline-editor`,this.host.hidden=!0,this.sourceInput=document.createElement(`input`),this.sourceInput.type=`text`,this.sourceInput.className=`zt-md-math-inline-editor-input`,this.sourceInput.setAttribute(`aria-label`,this.messages.mathBlockSourceAriaLabel),this.sourceInput.spellcheck=!1,this.previewContainer=document.createElement(`span`),this.previewContainer.className=`zt-md-math-inline-editor-preview`,this.errorContainer=document.createElement(`span`),this.errorContainer.className=`zt-md-math-inline-editor-error`,this.errorContainer.hidden=!0,this.host.append(this.sourceInput,this.previewContainer,this.errorContainer),this.sourceInput.addEventListener(`input`,this.handleInput),this.sourceInput.addEventListener(`beforeinput`,this.handleBeforeInput),this.sourceInput.addEventListener(`keydown`,this.handleKeyDown),this.sourceInput.addEventListener(`blur`,this.handleBlur),this.host.addEventListener(`mousedown`,this.handleMouseDown),this.view.dom.addEventListener(`focusin`,this.handleEditorFocusIn),this.update(e),this.stopObservingMessages=W(t,()=>{this.sourceInput.setAttribute(`aria-label`,t.mathBlockSourceAriaLabel),this.errorContainer.hidden||(this.errorContainer.textContent=t.mathRenderError)})}renderMath(e){this.errorContainer.hidden=!0,this.errorContainer.textContent=``,this.previewContainer.textContent=``;try{R.default.render(e,this.previewContainer,{displayMode:!1,throwOnError:!0})}catch{this.previewContainer.textContent=e,this.errorContainer.hidden=!1,this.errorContainer.textContent=this.messages.mathRenderError}}resolveCurrentNode(){if(this.currentPosition===null)return null;let e=this.view.state.doc.nodeAt(this.currentPosition);return Er(e)?e:null}openEditor(e){if(!Tr(this.view)){this.closeEditor(!1);return}let t=this.view.state.doc.nodeAt(e);if(!Er(t)){this.closeEditor(!1);return}this.currentPosition=e,this.sourceInput.value=Dr(t),this.renderMath(this.sourceInput.value);let n=this.resolveMathInlineElement(e);if(!n){this.closeEditor(!1);return}this.currentMathInlineElement=n,n.dataset.editing=`true`,n.append(this.host),this.host.hidden=!1,requestAnimationFrame(()=>{if(this.currentPosition!==e)return;this.sourceInput.focus();let t=this.sourceInput.value.length;if(this.currentCaret===`start`){this.sourceInput.setSelectionRange(0,0);return}this.sourceInput.setSelectionRange(t,t)})}commitCurrentValue(e){if(this.currentPosition===null)return;let t=this.resolveCurrentNode();if(!t){this.closeEditor(!1);return}let n=this.sourceInput.value,r=typeof e==`number`?e:this.currentPosition+t.nodeSize,i=this.view.state.tr.setNodeMarkup(this.currentPosition,void 0,{...t.attrs,value:n});i.setSelection(this.createSafeTextSelection(i.doc,r)).setMeta(J,{type:`close`}).scrollIntoView(),this.isCommitting=!0,this.view.dispatch(i),this.isCommitting=!1,this.view.focus()}closeEditor(e){this.currentMathInlineElement&&(this.currentMathInlineElement.dataset.editing=`false`),this.currentPosition=null,this.currentMathInlineElement=null,this.host.hidden=!0,this.host.remove(),e&&this.view.dispatch(this.view.state.tr.setMeta(J,{type:`close`}))}resolveMathInlineElement(e){let t=this.view.nodeDOM(e);return t instanceof HTMLElement?t:null}update(e){if(this.view=e,!Tr(e)){this.closeEditor(!1);return}let t=J.getState(e.state);if(!t||t.position===null){this.currentPosition!==null&&this.closeEditor(!1);return}if(this.currentPosition!==t.position){this.currentCaret=t.caret,this.openEditor(t.position);return}if(!this.resolveCurrentNode()){this.closeEditor(!0);return}}destroy(){this.stopObservingMessages(),this.sourceInput.removeEventListener(`input`,this.handleInput),this.sourceInput.removeEventListener(`beforeinput`,this.handleBeforeInput),this.sourceInput.removeEventListener(`keydown`,this.handleKeyDown),this.sourceInput.removeEventListener(`blur`,this.handleBlur),this.host.removeEventListener(`mousedown`,this.handleMouseDown),this.view.dom.removeEventListener(`focusin`,this.handleEditorFocusIn),this.closeEditor(!1)}},Ar=(e,t)=>(0,I.$prose)(()=>new v.Plugin({key:J,state:{init:()=>({position:null,caret:`end`}),apply:(e,t)=>{let n=e.getMeta(J);if(n?.type===`open`&&typeof n.position==`number`)return{position:n.position,caret:n.caret===`start`?`start`:`end`};if(n?.type===`close`)return{position:null,caret:`end`};if(t.position===null||!e.docChanged)return t;let r=e.mapping.map(t.position,-1);return Er(e.doc.nodeAt(r))?{position:r,caret:t.caret}:{position:null,caret:`end`}}},view:t=>new kr(t,e)})),jr=`math_inline`,Mr=e=>typeof e==`function`?e():null,Nr=e=>typeof e.props.editable==`function`?e.props.editable(e.state):e.editable,Pr=e=>String(e.attrs.value??e.textContent??``),Fr=class{syncEditableState(){this.dom.dataset.editable=Nr(this.view)?`true`:`false`}constructor(e,t,n,r){this.handleMouseDown=e=>{Nr(this.view)||(e.preventDefault(),e.stopPropagation())},this.handleClick=e=>{if(e.preventDefault(),e.stopPropagation(),!Nr(this.view))return;let t=Mr(this.getPos);t!==null&&Or(this.view,t)},this.node=e,this.view=t,this.getPos=n,this.messages=r,this.dom=document.createElement(`span`),this.dom.dataset.type=jr,this.dom.className=`zt-md-math-inline`,this.dom.dataset.editing=`false`,this.syncEditableState(),this.previewContainer=document.createElement(`span`),this.previewContainer.className=`zt-md-math-inline-preview`,this.errorContainer=document.createElement(`span`),this.errorContainer.className=`zt-md-math-inline-error`,this.errorContainer.hidden=!0,this.dom.append(this.previewContainer,this.errorContainer),this.syncFromNode(e),this.dom.addEventListener(`mousedown`,this.handleMouseDown),this.dom.addEventListener(`click`,this.handleClick),this.stopObservingMessages=W(r,()=>{this.errorContainer.hidden||(this.errorContainer.textContent=r.mathRenderError)})}syncFromNode(e){let t=Pr(e);this.dom.dataset.value=t,this.renderMath(t)}renderMath(e){this.errorContainer.hidden=!0,this.errorContainer.textContent=``,this.previewContainer.textContent=``;try{R.default.render(e,this.previewContainer,{displayMode:!1,throwOnError:!0})}catch{this.previewContainer.textContent=e,this.errorContainer.hidden=!1,this.errorContainer.textContent=this.messages.mathRenderError}}update(e){return e.type.name===jr?(this.node=e,this.syncEditableState(),this.syncFromNode(e),!0):!1}stopEvent(e){let t=e.target;return t instanceof Element?e.type===`click`||!!t.closest(`.zt-md-math-inline-editor`):e.type===`click`}ignoreMutation(){return!0}destroy(){this.stopObservingMessages(),this.dom.removeEventListener(`mousedown`,this.handleMouseDown),this.dom.removeEventListener(`click`,this.handleClick)}},Ir=(e=U())=>(t,n,r)=>new Fr(t,n,typeof r==`function`?()=>{let e=r();return typeof e==`number`?e:0}:!1,e),Lr=`math_inline`,Rr=`zt-md-math-inline-arrow-navigation`,zr={ArrowLeft:{positionKey:`from`},ArrowRight:{positionKey:`to`}},Br={ArrowLeft:`end`,ArrowRight:`start`},Vr={Backspace:`before`,Delete:`after`},Hr=e=>e instanceof Element?!!e.closest(`.zt-md-math-inline-editor`):!1,Ur=e=>e?.type.name===Lr,Wr=e=>!Vr[e.key]||e.defaultPrevented||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey||Hr(e.target)||Hr(document.activeElement),Gr=(e,t)=>{if(!zr[t.key]||Hr(t.target))return!1;let{selection:n}=e.state;return!(n instanceof v.NodeSelection)||n.node.type.name!==Lr?!1:(t.preventDefault(),Or(e,n.from,{caret:Br[t.key]??`end`}),!0)},Kr=(e,t)=>{let n=zr[t.key];if(!n||Hr(t.target))return!1;let{selection:r}=e.state;if(!r.empty)return!1;let i=r.$from,a=n.positionKey===`from`?i.nodeBefore:i.nodeAfter;return Ur(a)?(t.preventDefault(),Or(e,n.positionKey===`from`?r.from-a.nodeSize:r.from,{caret:Br[t.key]??`end`}),!0):!1},qr=(e,t)=>{try{return v.TextSelection.create(e,t)}catch{return v.TextSelection.near(e.resolve(t),-1)}},Jr=(e,t,n)=>{n.preventDefault();let r=t.from,i=e.state.tr.delete(t.from,t.to),a=i.doc.content.size,o=Math.min(r,a);return i.setSelection(qr(i.doc,o)).scrollIntoView(),e.dispatch(i),e.focus(),!0},Yr=(e,t)=>{let n=Vr[t.key];if(!n)return!1;let{selection:r}=e.state;if(!r.empty)return!1;let i=r.$from,a=n===`before`?i.nodeBefore:i.nodeAfter;if(!Ur(a))return!1;t.preventDefault();let o=n===`before`?r.from-a.nodeSize:r.from;return e.dispatch(e.state.tr.setSelection(v.NodeSelection.create(e.state.doc,o)).scrollIntoView()),e.focus(),!0},Xr=(e,t)=>{if(Wr(t))return!1;let{selection:n}=e.state;return n instanceof v.NodeSelection&&Ur(n.node)?Jr(e,n,t):Yr(e,t)},Zr=(e,t)=>{if(Hr(document.activeElement))return!1;let{selection:n}=e.state;if(!(n instanceof v.NodeSelection)||n.node.type.name!==Lr)return!1;let r=n.to,i=r+t.length,a=e.state.tr.insertText(t,r,r);return a.setSelection(v.TextSelection.create(a.doc,i)).scrollIntoView(),e.dispatch(a),e.focus(),!0},Qr=(0,I.$prose)(()=>new v.Plugin({key:new v.PluginKey(Rr),props:{handleKeyDown:(e,t)=>Kr(e,t)||Xr(e,t)?!0:Gr(e,t),handleTextInput:(e,t,n,r)=>Zr(e,r)}})),$r=`math_inline`,ei=`math_block`,ti=/(?:\$)([^$]+)(?:\$)$/,ni=/^\$\$\s$/,ri=(0,I.$remark)(`remarkMath`,()=>ce.default),ii=(0,I.$ctx)({},`katexOptions`),ai=(0,I.$nodeSchema)($r,e=>({group:`inline`,inline:!0,atom:!0,attrs:{value:{default:``}},parseDOM:[{tag:`span[data-type="${$r}"]`,getAttrs:e=>{let t=e;return{value:t.dataset.value??t.textContent??``}}}],toDOM:t=>{let n=String(t.attrs.value??t.textContent??``),r=document.createElement(`span`);return r.dataset.type=$r,r.dataset.value=n,R.default.render(n,r,e.get(ii.key)),r},parseMarkdown:{match:e=>e.type===`inlineMath`,runner:(e,t,n)=>{let r=String(t.value??``);e.addNode(n,{value:r})}},toMarkdown:{match:e=>e.type.name===$r,runner:(e,t)=>{let n=String(t.attrs.value??t.textContent??``);e.addNode(`inlineMath`,void 0,n)}}})),oi=(0,I.$nodeSchema)(ei,e=>({content:`text*`,group:`block`,marks:``,defining:!0,atom:!0,isolating:!0,attrs:{value:{default:``}},parseDOM:[{tag:`div[data-type="${ei}"]`,preserveWhitespace:`full`,getAttrs:e=>({value:e.dataset.value??``})}],toDOM:t=>{let n=String(t.attrs.value??``),r=document.createElement(`div`);return r.dataset.type=ei,r.dataset.value=n,R.default.render(n,r,e.get(ii.key)),r},parseMarkdown:{match:e=>e.type===`math`,runner:(e,t,n)=>{let r=String(t.value??``);e.addNode(n,{value:r})}},toMarkdown:{match:e=>e.type.name===ei,runner:(e,t)=>{let n=String(t.attrs.value??``);e.addNode(`math`,void 0,n)}}})),si=(0,I.$inputRule)(e=>new se.InputRule(ti,(t,n,r,i)=>{let a=ai.type(e),o=n[1]??``,s=t.doc.resolve(r);return s.parent.canReplaceWith(s.index(),s.indexAfter(),a)?t.tr.replaceWith(r,i,a.create({value:o})):null})),ci=[ri,ii,ai,oi,(0,I.$inputRule)(e=>new se.InputRule(ni,(t,n,r,i)=>{let a=t.doc.resolve(r),o=oi.type(e);return a.node(-1).canReplaceWith(a.index(-1),a.indexAfter(-1),o)?t.tr.delete(r,i).setBlockType(r,r,o):null})),si].flat(),li=`blockquote`,ui=`paragraph`,di=`Backspace`,fi=e=>e.key!==di||e.defaultPrevented||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey,pi=e=>{if(e.parent.type.name!==ui||e.parentOffset!==0)return null;for(let t=e.depth;t>0;--t){let n=e.node(t);if(n.type.name!==li)continue;let r=e.depth,i=e.index(t);return r<=t||i!==0?null:{paragraphDepth:r,blockquoteDepth:t,blockquoteType:n.type}}return null},mi=(e,t)=>{let{selection:n}=e.state;if(!n.empty)return!1;let r=n.$from,i=pi(r);if(!i)return!1;let a=r.blockRange(r,e=>e.type===i.blockquoteType);if(!a)return!1;let o=(0,le.liftTarget)(a);if(o===null)return!1;t.preventDefault();let s=e.state.tr.lift(a,o).scrollIntoView();return e.dispatch(s),!0},hi=(0,I.$prose)(()=>new v.Plugin({key:new v.PluginKey(`zt-md-blockquote-backspace-lift`),props:{handleKeyDown:(e,t)=>fi(t)?!1:mi(e,t)}})),gi=`Backspace`,_i=`heading`,vi=`paragraph`,yi=e=>typeof e.props.editable==`function`?e.props.editable(e.state):e.editable,bi=e=>{if(e.type.name!==vi)return!1;let t=e.textContent;return t.trim().length===0&&e.content.size===t.length},xi=e=>{if(e.parent.type.name!==_i||e.parentOffset!==0||e.depth<1)return null;let t=e.index(e.depth-1);if(t<=0)return null;let n=e.node(e.depth-1).child(t-1);if(!bi(n))return null;let r=e.before(e.depth);return{from:r-n.nodeSize,to:r}},Si=(e,t)=>{if(t.key!==gi||t.defaultPrevented||t.altKey||t.ctrlKey||t.metaKey||t.shiftKey||!yi(e))return!1;let{selection:n}=e.state;if(!n.empty)return!1;let r=xi(n.$from);if(!r)return!1;t.preventDefault();let i=e.state.tr.delete(r.from,r.to);return i.setSelection(v.TextSelection.create(i.doc,r.from+1)).scrollIntoView(),e.dispatch(i),!0},Ci=(0,I.$prose)(()=>new v.Plugin({key:new v.PluginKey(`zt-md-heading-backspace-empty-paragraph`),props:{handleKeyDown:(e,t)=>Si(e,t)}})),wi=`heading`,Ti=`zt-md-heading-focused`,Ei=`zt-md-heading-focus-indicator`,Di=e=>{let t=e.selection.$from;for(let n=t.depth;n>0;--n){let r=t.node(n);if(r.type.name!==wi)continue;let i=t.before(n),a=Number(r.attrs.level),o=F.Decoration.node(i,i+r.nodeSize,{class:Ti,"data-heading-level":`H${a}`});return F.DecorationSet.create(e.doc,[o])}return F.DecorationSet.empty},Oi=(0,I.$prose)(()=>new v.Plugin({key:new v.PluginKey(Ei),props:{decorations:Di}})),ki=`MILKDOWN_HEADING_ID`,Ai=`table`,ji=(e,t,n,r)=>{let i=Math.max(0,Math.min(e.content.size,t)),a=Math.max(i,Math.min(e.content.size,n)),o=e.resolve(i);for(let e=o.depth;e>0;--e)if(o.node(e).type===r)return!0;if(a>i){let t=e.resolve(a);for(let e=t.depth;e>0;--e)if(t.node(e).type===r)return!0;let n=!1;if(e.nodesBetween(i,a,e=>e.type===r?(n=!0,!1):e.isTextblock||e.type.name===Ai?!1:!n),n)return!0}return!1},Mi=(e,t,n)=>{let r=e.content.findDiffStart(t.content);if(r==null)return!1;let i=e.content.findDiffEnd(t.content);if(!i)return!1;let a=Math.max(i.a,r),o=Math.max(i.b,r);return ji(e,r,a,n)||ji(t,r,o,n)},Ni=(0,I.$prose)(e=>{let t=new v.PluginKey(ki),n=C.headingSchema.type(e),r=r=>{if(r.composing)return;let i=e.get(C.headingIdGenerator.key),a=r.state.tr.setMeta(`addToHistory`,!1),o=!1,s={};r.state.doc.descendants((e,r)=>{if(e.type===n){if(e.textContent.trim().length===0)return!1;let n=e.attrs,c=i(e);return s[c]?(s[c]+=1,c+=`-#${s[c]}`):s[c]=1,n.id!==c&&(o=!0,a.setMeta(t,!0).setNodeMarkup(r,void 0,{...n,id:c})),!1}return!(e.isTextblock||e.type.name===Ai)}),o&&r.dispatch(a)};return new v.Plugin({key:t,view:e=>{let t=!1;return r(e),{update:(e,i)=>{if(e.state.doc===i.doc){!e.composing&&t&&(t=!1,r(e));return}if(Mi(i.doc,e.state.doc,n)){if(e.composing){t=!0;return}t=!1,r(e)}}}}})}),Pi=`text`,Fi={svg:`svg`,html:`html`},Ii={html:!0,svg:!0},Y=e=>{let t=e.trim().toLowerCase();return t?t.startsWith(`canvas-`)?Object.entries(Fi).find(([e])=>t.includes(e))?.[1]??t:t:Pi},Li=e=>t=>{let n=e(t);return{...n,attrs:{...n.attrs,language:{default:Pi,validate:`string`}},parseMarkdown:{...n.parseMarkdown,runner:(e,t,r)=>{let i={...t,lang:Y(String(t.lang??``))};n.parseMarkdown.runner(e,i,r)}},toMarkdown:{...n.toMarkdown,runner:(e,t)=>{let n=Y(String(t.attrs.language??``));e.addNode(`code`,void 0,t.content.firstChild?.text||``,{lang:n})}}}},Ri=e=>{let t=e.get(C.codeBlockSchema.key);e.set(C.codeBlockSchema.key,Li(t))},zi=e=>Ii[Y(e)]===!0,Bi=`code_block`,Vi=1200,Hi=`html`,Ui=`ZT_MD_CODE_BLOCK_PREVIEW_LAYOUT`,Wi=[`default-src 'none'`,`style-src 'unsafe-inline'`,`img-src data: blob:`,`font-src data:`,`media-src data: blob:`,`connect-src 'none'`,`frame-src 'none'`,`object-src 'none'`,`form-action 'none'`,`base-uri 'none'`],Gi=q(`Copy`,{size:14,strokeWidth:2}),Ki=q(`Check`,{size:14,strokeWidth:2}),qi=q(`Trash2`,{size:14,strokeWidth:2}),Ji=q(`Eye`,{size:14,strokeWidth:2}),Yi=q(`Code2`,{size:14,strokeWidth:2}),Xi=(e,t)=>`<!doctype html>
|
|
4
4
|
<html>
|
|
5
5
|
<head>
|
|
6
6
|
<meta charset="UTF-8" />
|
|
7
7
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
8
|
-
<meta http-equiv="Content-Security-Policy" content="${[...
|
|
8
|
+
<meta http-equiv="Content-Security-Policy" content="${[...Wi,...t?[`script-src 'unsafe-inline'`]:[]].join(`; `)}" />
|
|
9
9
|
<style>
|
|
10
10
|
*, *::before, *::after { box-sizing: border-box; }
|
|
11
11
|
html, body { min-height: 100%; margin: 0; }
|
|
@@ -14,8 +14,8 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.
|
|
|
14
14
|
</style>
|
|
15
15
|
</head>
|
|
16
16
|
<body>${e}</body>
|
|
17
|
-
</html>`,Ei=e=>typeof e==`function`?e():null,Di=e=>typeof e.props.editable==`function`?e.props.editable(e.state):e.editable,Oi=class{syncLanguageAttribute(e){let t=typeof e.attrs.language==`string`?e.attrs.language.trim():``;if(!t){this.contentDOM.removeAttribute(`data-language`);return}this.contentDOM.setAttribute(`data-language`,t)}constructor(e,t,n,r){this.previewFrame=null,this.isPreviewAvailable=!1,this.isPreviewMode=!1,this.renderedPreviewKey=null,this.copyFeedbackTimer=null,this.handlePreviewClick=e=>{e.preventDefault(),e.stopPropagation(),this.isPreviewAvailable&&(this.isPreviewMode=!this.isPreviewMode,this.syncPreviewState(),this.view.dispatch(this.view.state.tr.setMeta(vi,!0)))},this.handlePreviewKeyDown=e=>{if(e.defaultPrevented||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey||e.key!==`ArrowUp`&&e.key!==`ArrowDown`)return;let t=Ei(this.getPos);t!==null&<(this.view,t,this.node,e.key)&&e.preventDefault()},this.handleCopyClick=e=>{if(e.preventDefault(),e.stopPropagation(),!Di(this.view))return;let t=this.node.textContent;(typeof navigator<`u`&&navigator.clipboard?.writeText?navigator.clipboard.writeText(t):Promise.resolve()).then(()=>{this.copyButton.innerHTML=xi,this.copyButton.dataset.copied=`true`,this.copyFeedbackTimer!==null&&clearTimeout(this.copyFeedbackTimer),this.copyFeedbackTimer=setTimeout(()=>{this.copyButton.innerHTML=bi,delete this.copyButton.dataset.copied,this.copyFeedbackTimer=null},gi)}).catch(()=>{})},this.handleDeleteClick=e=>{e.preventDefault(),e.stopPropagation(),Di(this.view)&&this.deleteCurrentCodeBlock()},this.node=e,this.view=t,this.getPos=n,this.messages=r,this.dom=document.createElement(`div`),this.dom.className=`zt-md-code-block`,this.dom.dataset.type=hi,this.contentDOM=document.createElement(`pre`),this.previewContainer=document.createElement(`div`),this.previewContainer.className=`zt-md-code-block-preview`,this.previewContainer.contentEditable=`false`,this.previewContainer.hidden=!0,this.previewContainer.tabIndex=-1,this.previewContainer.setAttribute(`role`,`region`),this.previewContainer.setAttribute(`aria-label`,r.codeBlockPreviewAriaLabel),this.actionsContainer=document.createElement(`span`),this.actionsContainer.className=`zt-md-code-block-actions`,this.actionsContainer.contentEditable=`false`,this.previewButton=document.createElement(`button`),this.previewButton.type=`button`,this.previewButton.className=`zt-md-code-block-action-button`,this.previewButton.hidden=!0,this.previewButton.innerHTML=Ci,this.copyButton=document.createElement(`button`),this.copyButton.type=`button`,this.copyButton.className=`zt-md-code-block-action-button zt-md-code-block-editable-action`,this.copyButton.setAttribute(`aria-label`,r.codeBlockCopyAriaLabel),this.copyButton.innerHTML=bi,this.deleteButton=document.createElement(`button`),this.deleteButton.type=`button`,this.deleteButton.className=`zt-md-code-block-action-button zt-md-code-block-editable-action zt-md-code-block-action-button-danger`,this.deleteButton.setAttribute(`aria-label`,r.codeBlockDeleteAriaLabel),this.deleteButton.innerHTML=Si,this.actionsContainer.append(this.previewButton,this.copyButton,this.deleteButton),this.dom.append(this.contentDOM,this.previewContainer,this.actionsContainer),this.updateEditableState(),this.syncLanguageAttribute(e),this.syncPreviewAvailability(e),this.previewButton.addEventListener(`click`,this.handlePreviewClick),this.copyButton.addEventListener(`click`,this.handleCopyClick),this.deleteButton.addEventListener(`click`,this.handleDeleteClick),this.previewContainer.addEventListener(`keydown`,this.handlePreviewKeyDown),this.stopObservingMessages=W(r,()=>{this.previewContainer.setAttribute(`aria-label`,r.codeBlockPreviewAriaLabel),this.copyButton.setAttribute(`aria-label`,r.codeBlockCopyAriaLabel),this.deleteButton.setAttribute(`aria-label`,r.codeBlockDeleteAriaLabel);let e=this.isPreviewAvailable&&this.isPreviewMode?r.codeBlockSourceAriaLabel:r.codeBlockPreviewAriaLabel;this.previewButton.setAttribute(`aria-label`,e),this.previewButton.title=e,this.previewFrame&&(this.previewFrame.title=r.codeBlockPreviewAriaLabel)})}deleteCurrentCodeBlock(){let e=Ei(this.getPos);if(e===null)return;let t=this.view.state.tr.delete(e,e+this.node.nodeSize),n=Math.min(e,t.doc.content.size);t.setSelection(v.TextSelection.near(t.doc.resolve(n),-1)).scrollIntoView(),this.view.dispatch(t),requestAnimationFrame(()=>{this.view.focus()})}updateEditableState(){this.dom.dataset.editable=Di(this.view)?`true`:`false`}syncPreviewAvailability(e){let t=typeof e.attrs.language==`string`?e.attrs.language:``;this.isPreviewAvailable=mi(t),this.isPreviewAvailable||(this.isPreviewMode=!1),this.previewButton.hidden=!this.isPreviewAvailable,this.syncPreviewState(),this.syncActionsVisibility()}syncPreviewState(){let e=this.isPreviewAvailable&&this.isPreviewMode,t=e?this.messages.codeBlockSourceAriaLabel:this.messages.codeBlockPreviewAriaLabel;if(this.dom.dataset.viewMode=e?`preview`:`source`,this.previewContainer.hidden=!e,this.previewContainer.tabIndex=e?0:-1,this.previewButton.dataset.active=e?`true`:`false`,this.previewButton.setAttribute(`aria-pressed`,e?`true`:`false`),this.previewButton.setAttribute(`aria-label`,t),this.previewButton.title=t,this.previewButton.innerHTML=e?wi:Ci,e){this.contentDOM.setAttribute(`aria-hidden`,`true`),this.renderPreview();return}this.contentDOM.removeAttribute(`aria-hidden`),this.clearPreview()}syncActionsVisibility(){let e=Di(this.view)||this.isPreviewAvailable;this.actionsContainer.dataset.visible=e?`true`:`false`}renderPreview(){let e=this.node.textContent,t=J(String(this.node.attrs.language??``)),n=t===_i,r=`${t}\u0000${e}`;if(this.renderedPreviewKey===r)return;this.renderedPreviewKey=r;let i=document.createElement(`iframe`);i.className=`zt-md-code-block-preview-frame`,i.title=this.messages.codeBlockPreviewAriaLabel,i.tabIndex=-1,i.referrerPolicy=`no-referrer`,i.setAttribute(`sandbox`,n?`allow-scripts`:``),i.srcdoc=Ti(e,n),this.previewContainer.replaceChildren(i),this.previewFrame=i}clearPreview(){this.renderedPreviewKey=null,this.previewFrame?.remove(),this.previewFrame=null}update(e){return e.type.name===hi?(this.node=e,this.updateEditableState(),this.syncLanguageAttribute(e),this.syncPreviewAvailability(e),!0):!1}stopEvent(e){let t=e.target;return t instanceof Node?this.actionsContainer.contains(t)||this.previewContainer.contains(t):!1}ignoreMutation(e){return e.type===`selection`?!1:e.type===`attributes`&&(e.target===this.dom&&e.attributeName===`data-view-mode`||e.target===this.contentDOM&&e.attributeName===`aria-hidden`)?!0:this.actionsContainer.contains(e.target)||this.previewContainer.contains(e.target)}destroy(){this.stopObservingMessages(),this.previewButton.removeEventListener(`click`,this.handlePreviewClick),this.copyButton.removeEventListener(`click`,this.handleCopyClick),this.deleteButton.removeEventListener(`click`,this.handleDeleteClick),this.previewContainer.removeEventListener(`keydown`,this.handlePreviewKeyDown),this.copyFeedbackTimer!==null&&(clearTimeout(this.copyFeedbackTimer),this.copyFeedbackTimer=null),this.copyButton.innerHTML=bi,delete this.copyButton.dataset.copied,this.clearPreview()}},ki=(e=U())=>(t,n,r)=>new Oi(t,n,typeof r==`function`?()=>{let e=r();return typeof e==`number`?e:0}:!1,e),Ai=new Set,ji=!1,Mi=()=>typeof document<`u`,Ni=e=>{Array.from(Ai).forEach(t=>t(e))},Pi=()=>{ji||!Mi()||(document.addEventListener(`scroll`,Ni,{capture:!0,passive:!0}),ji=!0)},Fi=()=>{!ji||!Mi()||(document.removeEventListener(`scroll`,Ni,!0),ji=!1)},Ii=e=>{if(!Mi())return()=>void 0;let t=!0;return Ai.add(e),Pi(),()=>{t&&(t=!1,Ai.delete(e),Ai.size===0&&Fi())}},Li=e=>e?e.closest(`.zt-md-editor`)??e:null,Ri=(e,t,n)=>{let r=typeof window>`u`?e.bottom:window.innerHeight,i=n?.top??0,a=n?.bottom??r,o=e.top-i,s=a-e.bottom;return s<t&&o>s?`top`:`bottom`},zi=(e,t,n)=>{let r=n??t.getBoundingClientRect();return{anchorTopInContent:e.top-r.top+t.scrollTop,anchorBottomInContent:e.bottom-r.top+t.scrollTop,anchorLeftInContent:e.left-r.left+t.scrollLeft,anchorRightInContent:e.right-r.left+t.scrollLeft}},Bi=e=>{let{anchor:t,overlaySize:n,horizontalAlign:r=`start`}=e,i=t.anchorRightInContent??t.anchorLeftInContent;return r===`end`?i-n.width:r===`center`?t.anchorLeftInContent+(i-t.anchorLeftInContent-n.width)/2:t.anchorLeftInContent},Vi=(e,t)=>{let{wrapper:n,anchor:r,overlaySize:i,placement:a,offsetY:o,boundaryInset:s}=e,c=t??n.getBoundingClientRect(),l=n.scrollLeft+s,u=n.scrollLeft+n.clientWidth-i.width-s,d=Bi(e),f=Math.min(Math.max(d,l),Math.max(l,u)),p=a===`top`?r.anchorTopInContent-(i.height??0)-o:r.anchorBottomInContent+o;return{left:c.left+f-n.scrollLeft,top:c.top+p-n.scrollTop}},Hi=(e,t,n)=>{let r=Vi(e,n),i=t.getBoundingClientRect();return{left:r.left-i.left,top:r.top-i.top}},Ui=e=>{let t=0,n=null,r=null,i=()=>{typeof window>`u`||(t&&window.cancelAnimationFrame(t),t=window.requestAnimationFrame(()=>{t=0,e()}))},a=()=>{window.addEventListener(`resize`,i),r||=Ii(i)},o=()=>{window.removeEventListener(`resize`,i),r?.(),r=null},s=e=>{n!==e&&(n&&n.removeEventListener(`scroll`,i),n=e,n&&n.addEventListener(`scroll`,i,{passive:!0}))};return{schedule:i,bindGlobal:a,unbindGlobal:o,bindWrapper:s,destroy:()=>{typeof window<`u`&&t&&(window.cancelAnimationFrame(t),t=0),o(),s(null)}}},Wi=(e,t,n,r)=>{let i=t.top-r.top,a=r.bottom-t.bottom;return e===`top`?i<n&&a>i?`bottom`:`top`:a<n&&i>a?`top`:`bottom`},Gi=({open:e,portalContainer:t,editorWrapper:n,defaultPlacement:r=`bottom`,horizontalAlign:i=`start`,offsetY:a=8,boundaryInset:o=2,fallbackWidth:s,fallbackHeight:l,onOutside:u})=>{let d=(0,c.useRef)(null),f=(0,c.useRef)(null),p=(0,c.useRef)(e),m=(0,c.useRef)(u);m.current=u;let h=(0,c.useCallback)(()=>{let e=d.current,c=f.current;if(!p.current||!e||!c||!t||!n)return;let u=e.getBoundingClientRect(),m=n.getBoundingClientRect(),h=c.offsetWidth||s,g=c.offsetHeight||l,_=Wi(r,u,g,m),v=Hi({wrapper:n,anchor:zi(u,n,m),overlaySize:{width:h,height:g},placement:_,horizontalAlign:i,offsetY:a,boundaryInset:o},t,m);c.style.position=`absolute`,c.style.left=`${v.left}px`,c.style.top=`${v.top}px`,c.style.transform=``,c.style.visibility=`visible`},[o,r,n,l,s,i,a,t]),g=(0,c.useCallback)(e=>{f.current=e,e&&(e.style.visibility=`hidden`,h())},[h]);return(0,c.useLayoutEffect)(()=>{if(p.current=e,!e){f.current&&(f.current.style.visibility=`hidden`);return}h()},[e,h]),(0,c.useEffect)(()=>{if(!e)return;let t=Ui(h);return t.bindGlobal(),t.bindWrapper(n??null),t.schedule(),()=>{t.destroy()}},[n,e,h]),(0,c.useEffect)(()=>{if(!e)return;let t=e=>{let t=e.target;t instanceof Node&&(d.current?.contains(t)||f.current?.contains(t)||m.current())};return document.addEventListener(`mousedown`,t),()=>{document.removeEventListener(`mousedown`,t)}},[e]),{open:e,triggerRef:d,panelRef:g,updatePosition:h}},Ki=({panel:e,portalContainer:t,className:n,role:r,onMouseDown:i,children:a})=>!e.open||!t?null:(0,le.createPortal)((0,c.createElement)(`div`,{ref:e.panelRef,role:r,className:n,style:{position:`absolute`,visibility:`hidden`},onMouseDown:i},a),t),qi=`code_block`,Ji=`ZT_MD_CODE_BLOCK_LANGUAGE_PICKER`,Yi=8,Xi=96,Zi=26,Qi=224,$i=220,ea=[`javascript`,`typescript`,`tsx`,`jsx`,`html`,`css`,`json`,`bash`,`python`,`go`,`java`,`sql`,`yaml`,`markdown`,`rust`,`cpp`,`c`,`csharp`,`php`,`docker`],ta=e=>{let t=E.refractor.listLanguages(),n=new Set(t.map(e=>J(e)).filter(e=>e!==li)),r=[];for(let e of ea)n.delete(e)&&r.push({value:e,label:e});let i=[...n].sort((e,t)=>e.localeCompare(t));return[{value:li,label:e},...r,...i.map(e=>({value:e,label:e}))]},na=e=>{let t=e.state.selection.$from;for(let e=t.depth;e>=0;--e){let n=t.node(e);if(n.type.name===qi)return{position:e===0?0:t.before(e),node:n}}return null},ra=(e,t)=>{let n=e.nodeDOM(t);return n instanceof HTMLPreElement?n:n instanceof HTMLElement?n.querySelector(`pre`):null},ia=e=>typeof e.props.editable==`function`?e.props.editable(e.state):e.editable,aa=e=>{let[t,n]=(0,c.useState)(!1),[r,i]=(0,c.useState)(``),[a,o]=(0,c.useState)(0),s=(0,c.useRef)(null),l=(0,c.useRef)(null),u=J(e.currentLanguage),d=u===`text`?e.messages.codeBlockLanguagePlainText:u,p=(0,c.useMemo)(()=>ta(e.messages.codeBlockLanguagePlainText),[e.messages.codeBlockLanguagePlainText]),m=(0,c.useMemo)(()=>{let e=r.trim().toLowerCase();if(!e)return p;let t=[],n=[];for(let r of p){let i=r.label.toLowerCase(),a=r.value.toLowerCase();a.startsWith(e)||i.startsWith(e)?t.push(r):(a.includes(e)||i.includes(e))&&n.push(r)}return[...t,...n]},[r,p]),h=Gi({open:t,portalContainer:e.portalContainer,editorWrapper:e.collisionBoundary,horizontalAlign:`end`,offsetY:6,fallbackWidth:Qi,fallbackHeight:$i,onOutside:()=>n(!1)}),g=e=>e instanceof HTMLElement?e.closest(`input, textarea, [contenteditable]:not([contenteditable="false"])`)!==null:!1,_=e=>{g(e.target)||e.preventDefault()},v=()=>{if(t){n(!1);return}let e=m.findIndex(e=>e.value===u);o(e>=0?e:0),h.updatePosition(),n(!0)},y=t=>{e.onSelectLanguage(t),n(!1),i(``)},b=e=>{m.length!==0&&o(t=>(t+e+m.length)%m.length)},x=()=>{let e=m[a];e&&y(e.value)};return(0,c.useLayoutEffect)(()=>{e.onLayoutChange()},[d,e.onLayoutChange]),(0,c.useEffect)(()=>{n(!1),i(``),o(0)},[e.currentLanguage]),(0,c.useEffect)(()=>{t&&s.current?.focus()},[t]),(0,c.useEffect)(()=>{if(!t)return;let e=l.current,n=e?.querySelector(`[data-active="true"]`);if(!e||!n)return;let r=e.getBoundingClientRect(),i=n.getBoundingClientRect();i.top<r.top?e.scrollTop+=i.top-r.top:i.bottom>r.bottom&&(e.scrollTop+=i.bottom-r.bottom)},[a,m,t]),(0,c.createElement)(c.Fragment,null,(0,c.createElement)(`div`,{className:`zt-md-code-language-picker`,onMouseDown:_},(0,c.createElement)(`button`,{ref:h.triggerRef,type:`button`,className:`zt-md-code-language-picker-trigger`,"aria-expanded":t,"aria-label":d,onClick:v},(0,c.createElement)(`span`,{className:`zt-md-code-language-picker-trigger-label`},d),(0,c.createElement)(f.ChevronDown,{className:`zt-md-code-language-picker-trigger-icon`,size:14,strokeWidth:2,"aria-hidden":`true`}))),(0,c.createElement)(Ki,{panel:h,portalContainer:e.portalContainer,className:`zt-md-code-language-picker-panel`,onMouseDown:_},(0,c.createElement)(`label`,{className:`zt-md-code-language-picker-search`},(0,c.createElement)(f.Search,{className:`zt-md-code-language-picker-search-icon`,size:14,strokeWidth:2,"aria-hidden":`true`}),(0,c.createElement)(`input`,{ref:s,value:r,onChange:e=>{i(e.currentTarget.value),o(0)},onKeyDown:e=>{let t={ArrowDown:()=>b(1),ArrowUp:()=>b(-1),Enter:x}[e.key];t&&(e.preventDefault(),t())},placeholder:e.messages.codeBlockLanguageSearchPlaceholder,className:`zt-md-code-language-picker-search-input`})),(0,c.createElement)(`div`,{ref:l,className:`zt-md-code-language-picker-options`,role:`listbox`},m.length>0?m.map((e,t)=>(0,c.createElement)(`button`,{key:e.value||`__plain_text__`,type:`button`,role:`option`,"aria-selected":e.value===u?`true`:`false`,className:`zt-md-code-language-picker-option`,"data-active":t===a?`true`:`false`,"data-selected":e.value===u?`true`:`false`,onClick:()=>y(e.value)},(0,c.createElement)(`span`,null,e.label),e.value===u?(0,c.createElement)(f.Check,{className:`zt-md-code-language-picker-option-check`,size:14,strokeWidth:2,"aria-hidden":`true`}):null)):(0,c.createElement)(`div`,{className:`zt-md-code-language-picker-empty`},`-`))))},oa=class{constructor(e,t,n){this.isAttached=!1,this.currentCodeBlockPosition=null,this.currentPreElement=null,this.currentActionsContainer=null,this.currentRenderedLanguage=null,this.hasPositionContext=!1,this.repositionScheduler=Ui(()=>{this.hasPositionContext&&this.updateOverlayPosition()}),this.handlePickerLayoutChange=()=>{this.hasPositionContext&&this.updateOverlayPosition()},this.view=e,this.messages=t,this.portalContainer=n,this.editorWrapper=Li(e.dom),this.host=document.createElement(`span`),this.host.className=`zt-md-code-language-picker-host`,this.hostRoot=(0,ae.createRoot)(this.host),this.update(e),this.stopObservingMessages=W(t,()=>{let e=this.currentRenderedLanguage;this.currentRenderedLanguage=null,e!==null&&this.render(e)})}applyLanguage(e){if(this.currentCodeBlockPosition===null)return;let t=this.view.state.doc.nodeAt(this.currentCodeBlockPosition);if(!t||t.type.name!==qi)return;let n=J(e),r={...t.attrs,language:n};if(String(t.attrs.language??``)===n)return;let i=this.view.state.tr.setNodeMarkup(this.currentCodeBlockPosition,t.type,r,t.marks);this.view.dispatch(i),this.view.focus()}render(e){this.currentRenderedLanguage!==null&&this.currentRenderedLanguage===e||(this.hostRoot.render((0,c.createElement)(aa,{currentLanguage:e,messages:{...this.messages},portalContainer:this.portalContainer,collisionBoundary:this.editorWrapper,onSelectLanguage:e=>this.applyLanguage(e),onLayoutChange:this.handlePickerLayoutChange})),this.host.dataset.mounted=`true`,this.currentRenderedLanguage=e)}syncFocusedActionsContainer(e){this.currentActionsContainer!==e&&(delete this.currentActionsContainer?.dataset.focused,this.currentActionsContainer=e,this.currentActionsContainer&&(this.currentActionsContainer.dataset.focused=`true`))}detach(){this.isAttached&&(this.isAttached=!1,this.repositionScheduler.unbindGlobal(),this.repositionScheduler.bindWrapper(null),this.syncFocusedActionsContainer(null),this.hostRoot.render(null),delete this.host.dataset.mounted,this.host.remove(),this.currentCodeBlockPosition=null,this.currentPreElement=null,this.currentRenderedLanguage=null,this.hasPositionContext=!1)}updateOverlayPosition(){if(!this.editorWrapper||!this.currentPreElement||this.host.parentElement!==this.portalContainer)return;let e=this.editorWrapper.getBoundingClientRect(),t=this.currentPreElement.getBoundingClientRect(),n=zi(t,this.editorWrapper,e),r=n.anchorRightInContent??n.anchorLeftInContent+t.width,i=Math.max(0,Math.min(t.width,this.editorWrapper.clientWidth)-Yi*2);this.host.style.setProperty(`--zt-md-code-language-picker-max-width`,`${i}px`);let a=this.host.offsetWidth||Math.min(Xi,i),o=this.host.offsetHeight||Zi,s=Hi({wrapper:this.editorWrapper,anchor:{anchorLeftInContent:r-a-Yi,anchorTopInContent:n.anchorTopInContent+t.height-o-Yi,anchorBottomInContent:n.anchorTopInContent+t.height-o-Yi},overlaySize:{width:a},placement:`top`,offsetY:0,boundaryInset:2},this.portalContainer,e);this.host.style.left=`${s.left}px`,this.host.style.top=`${s.top}px`}update(e){if(this.view=e,e.composing)return;if(!ia(e)||!this.editorWrapper){this.detach();return}let t=na(e);if(!t){this.detach();return}let n=ra(e,t.position);if(!n){this.detach();return}let r=n.parentElement?.querySelector(`:scope > .zt-md-code-block-actions`)??null;this.syncFocusedActionsContainer(r);let i=this.isAttached;this.isAttached||(this.isAttached=!0,this.repositionScheduler.bindGlobal(),this.repositionScheduler.bindWrapper(this.editorWrapper)),this.host.parentElement!==this.portalContainer&&this.portalContainer.append(this.host);let a=J(String(t.node.attrs.language??``)),o=this.currentCodeBlockPosition===t.position&&this.currentPreElement===n&&this.currentRenderedLanguage!==null&&this.currentRenderedLanguage===a;this.currentCodeBlockPosition=t.position,this.currentPreElement=n,this.hasPositionContext=!0,o||this.render(a),i?this.repositionScheduler.schedule():this.updateOverlayPosition()}destroy(){this.stopObservingMessages(),this.detach(),this.repositionScheduler.destroy(),this.hostRoot.unmount()}},sa=(e,t)=>(0,L.$prose)(()=>new v.Plugin({key:new v.PluginKey(Ji),view:n=>new oa(n,e,t)})),ca=new Set([`code_block`,`frontmatter`]),la=`a`,ua=`zt-md-code-block-mod-a-select`,da=e=>e.key.toLowerCase()!==la||e.defaultPrevented||e.altKey||e.shiftKey||!e.ctrlKey&&!e.metaKey,fa=e=>{for(let t=e.depth;t>=0;--t){let n=e.node(t);if(!ca.has(n.type.name))continue;let r=t===0?0:e.before(t);return{codeBlockStart:r+1,codeBlockEnd:r+n.nodeSize-1}}return null},pa=(e,t)=>{let n=e.state.selection.$from,r=fa(n);if(!r)return!1;let i=e.state.tr.setSelection(v.TextSelection.create(e.state.doc,r.codeBlockStart,r.codeBlockEnd));return t.preventDefault(),e.dispatch(i),!0},ma=(0,L.$prose)(()=>new v.Plugin({key:new v.PluginKey(ua),props:{handleKeyDown:(e,t)=>da(t)?!1:pa(e,t)}})),ha=`frontmatter`,ga=[`yaml`,`toml`],_a=e=>e===`toml`?`toml`:`yaml`,va=[(0,L.$remark)(`remarkFrontmatter`,()=>ue.default,[...ga]),(0,L.$nodeSchema)(ha,()=>({content:`text*`,group:`block`,marks:``,code:!0,defining:!0,isolating:!0,attrs:{format:{default:`yaml`,validate:`string`}},parseDOM:[{tag:`pre[data-type="${ha}"]`,preserveWhitespace:`full`,getAttrs:e=>({format:_a(e.dataset.format)})}],toDOM:e=>[`pre`,{"data-type":ha,"data-format":_a(e.attrs.format)},[`code`,0]],parseMarkdown:{match:e=>e.type===`yaml`||e.type===`toml`,runner:(e,t,n)=>{let r=_a(t.type),i=typeof t.value==`string`?t.value:``;e.openNode(n,{format:r}),i&&e.addText(i),e.closeNode()}},toMarkdown:{match:e=>e.type.name===ha,runner:(e,t)=>{let n=_a(t.attrs.format);e.addNode(n,void 0,t.textContent)}}}))].flat(),ya=1200,ba={yaml:`frontmatterYamlLabel`,toml:`frontmatterTomlLabel`},xa=K(`ChevronDown`,{size:14,strokeWidth:2}),Sa=K(`Copy`,{size:14,strokeWidth:2}),Ca=K(`Check`,{size:14,strokeWidth:2}),wa=K(`Trash2`,{size:14,strokeWidth:2}),Ta=e=>typeof e==`function`?e():null,Ea=e=>typeof e.props.editable==`function`?e.props.editable(e.state):e.editable,Da=class{constructor(e,t,n,r){this.isCollapsed=!1,this.copyFeedbackTimer=null,this.handleToggleClick=e=>{e.preventDefault(),e.stopPropagation(),this.isCollapsed=!this.isCollapsed,this.syncCollapsedState(),this.syncLocalizedLabels()},this.handleCopyClick=e=>{e.preventDefault(),e.stopPropagation();let t=this.node.textContent;(typeof navigator<`u`&&navigator.clipboard?.writeText?navigator.clipboard.writeText(t):Promise.resolve()).then(()=>{this.copyButton.innerHTML=Ca,this.copyButton.dataset.copied=`true`,this.copyFeedbackTimer!==null&&clearTimeout(this.copyFeedbackTimer),this.copyFeedbackTimer=setTimeout(()=>{this.copyButton.innerHTML=Sa,delete this.copyButton.dataset.copied,this.copyFeedbackTimer=null},ya)}).catch(()=>{})},this.handleDeleteClick=e=>{if(e.preventDefault(),e.stopPropagation(),!Ea(this.view))return;let t=Ta(this.getPos);if(t===null)return;let n=t+this.node.nodeSize,r=t===0&&n===this.view.state.doc.content.size,i=this.view.state.schema.nodes.paragraph,a=r?i?.createAndFill():null;if(a){let e=this.view.state.tr.replaceWith(t,n,a);e.setSelection(v.TextSelection.near(e.doc.resolve(t+1),1)).scrollIntoView(),this.view.dispatch(e),this.view.focus();return}let o=this.view.state.tr.delete(t,n),s=Math.min(t,o.doc.content.size);o.setSelection(v.TextSelection.near(o.doc.resolve(s),1)).scrollIntoView(),this.view.dispatch(o),this.view.focus()},this.node=e,this.view=t,this.getPos=n,this.messages=r,this.dom=document.createElement(`div`),this.dom.className=`zt-md-frontmatter`,this.dom.dataset.type=ha,this.headerContainer=document.createElement(`div`),this.headerContainer.className=`zt-md-frontmatter-header`,this.headerContainer.contentEditable=`false`,this.toggleButton=document.createElement(`button`),this.toggleButton.type=`button`,this.toggleButton.className=`zt-md-frontmatter-toggle`,this.chevronIcon=document.createElement(`span`),this.chevronIcon.className=`zt-md-frontmatter-chevron`,this.chevronIcon.innerHTML=xa,this.titleSpan=document.createElement(`span`),this.titleSpan.className=`zt-md-frontmatter-title`,this.toggleButton.append(this.chevronIcon,this.titleSpan),this.actionsContainer=document.createElement(`span`),this.actionsContainer.className=`zt-md-frontmatter-actions`,this.copyButton=document.createElement(`button`),this.copyButton.type=`button`,this.copyButton.className=`zt-md-frontmatter-action-button`,this.copyButton.innerHTML=Sa,this.deleteButton=document.createElement(`button`),this.deleteButton.type=`button`,this.deleteButton.className=`zt-md-frontmatter-action-button zt-md-frontmatter-editable-action zt-md-frontmatter-action-button-danger`,this.deleteButton.innerHTML=wa,this.actionsContainer.append(this.copyButton,this.deleteButton),this.headerContainer.append(this.toggleButton,this.actionsContainer),this.contentDOM=document.createElement(`pre`),this.contentDOM.className=`zt-md-frontmatter-body`,this.dom.append(this.headerContainer,this.contentDOM),this.syncFormatState(e),this.syncEditableState(),this.syncCollapsedState(),this.syncLocalizedLabels(),this.toggleButton.addEventListener(`click`,this.handleToggleClick),this.copyButton.addEventListener(`click`,this.handleCopyClick),this.deleteButton.addEventListener(`click`,this.handleDeleteClick),this.stopObservingMessages=W(r,()=>{this.syncLocalizedLabels()})}syncFormatState(e){let t=_a(e.attrs.format);this.dom.dataset.format=t,this.titleSpan.textContent=this.messages[ba[t]]}syncEditableState(){this.dom.dataset.editable=Ea(this.view)?`true`:`false`}syncCollapsedState(){this.dom.dataset.collapsed=this.isCollapsed?`true`:`false`,this.toggleButton.setAttribute(`aria-expanded`,String(!this.isCollapsed)),this.contentDOM.hidden=this.isCollapsed,this.contentDOM.setAttribute(`aria-hidden`,String(this.isCollapsed))}syncLocalizedLabels(){let e=_a(this.node.attrs.format);this.titleSpan.textContent=this.messages[ba[e]];let t=this.isCollapsed?this.messages.frontmatterExpandAriaLabel:this.messages.frontmatterCollapseAriaLabel;this.toggleButton.setAttribute(`aria-label`,t),this.toggleButton.title=t,this.copyButton.setAttribute(`aria-label`,this.messages.frontmatterCopyAriaLabel),this.copyButton.title=this.messages.frontmatterCopyAriaLabel,this.deleteButton.setAttribute(`aria-label`,this.messages.frontmatterDeleteAriaLabel),this.deleteButton.title=this.messages.frontmatterDeleteAriaLabel}update(e){return e.type.name===`frontmatter`?(this.node=e,this.syncFormatState(e),this.syncEditableState(),!0):!1}stopEvent(e){let t=e.target;return t instanceof Node?this.headerContainer.contains(t):!1}ignoreMutation(e){return e.type===`selection`?!1:!!(this.headerContainer.contains(e.target)||e.type===`attributes`&&(e.target===this.dom&&(e.attributeName===`data-collapsed`||e.attributeName===`data-editable`||e.attributeName===`data-format`)||e.target===this.contentDOM&&(e.attributeName===`hidden`||e.attributeName===`aria-hidden`)))}destroy(){this.stopObservingMessages(),this.toggleButton.removeEventListener(`click`,this.handleToggleClick),this.copyButton.removeEventListener(`click`,this.handleCopyClick),this.deleteButton.removeEventListener(`click`,this.handleDeleteClick),this.copyFeedbackTimer!==null&&(clearTimeout(this.copyFeedbackTimer),this.copyFeedbackTimer=null)}},Oa=(e=U())=>(t,n,r)=>new Da(t,n,typeof r==`function`?()=>{let e=r();return typeof e==`number`?e:0}:!1,e),ka=(e,t)=>e(t.state,t.dispatch,t),Aa=(e,t)=>{let n=e?.state?.selection?.$from;if(!n||!e?.dispatch)return!1;for(let r=n.depth;r>0;--r){let i=n.node(r);if(i?.type?.name!==`list_item`)continue;if(!i.type?.spec?.attrs?.checked)return!1;let a=n.before(r);return e.dispatch(e.state.tr.setNodeMarkup(a,void 0,{...i.attrs,checked:t})),!0}return!1},ja={heading1:1,heading2:2,heading3:3,heading4:4,heading5:5,heading6:6},Ma={bulletList:`bullet_list`,orderedList:`ordered_list`},Na=[`codeBlock`,`heading1`,`heading2`,`heading3`,`heading4`,`heading5`,`heading6`,`taskList`,`orderedList`,`bulletList`,`blockquote`,`paragraph`],Pa=(e,t)=>{if(!e?.state||!e?.dispatch)return!1;let n=e.state.schema.nodes;if(t===`paragraph`){let t=n.paragraph;return t?ka((0,B.setBlockType)(t),e):!1}if(t in ja){let r=n.heading,i=ja[t];return!r||typeof i!=`number`?!1:ka((0,B.setBlockType)(r,{level:i}),e)}if(t===`blockquote`){let t=n.blockquote;return t?ka((0,B.wrapIn)(t),e):!1}if(t===`taskList`){let t=n.bullet_list;return!t||!ka((0,fe.wrapInList)(t),e)?!1:Aa(e,!1)}if(t===`codeBlock`){let t=n.code_block;return t?ka((0,B.setBlockType)(t,{language:`text`}),e):!1}if(t in Ma){let r=n[Ma[t]];return r?ka((0,fe.wrapInList)(r),e):!1}return!1},Fa=e=>{let t=e.state.selection.$from,n=new Set;for(let e=t.depth;e>0;--e){let r=t.node(e),i=r.type.name;if(i===`code_block`){n.add(`codeBlock`);continue}if(i===`blockquote`){n.add(`blockquote`);continue}if(i===`heading`){let e={1:`heading1`,2:`heading2`,3:`heading3`,4:`heading4`,5:`heading5`,6:`heading6`}[Number(r.attrs?.level??0)];e&&n.add(e);continue}if(i===`list_item`){typeof r.attrs?.checked==`boolean`&&n.add(`taskList`);continue}if(i===`ordered_list`){n.add(`orderedList`);continue}if(i===`bullet_list`){n.add(`bulletList`);continue}i===`paragraph`&&n.add(`paragraph`)}return n.has(`taskList`)&&n.delete(`bulletList`),n.size===0&&n.add(`paragraph`),n},Ia=e=>{let t=Fa(e);return Na.find(e=>t.has(e))||`paragraph`},La=/Mac|iPhone|iPad|iPod/,Ra={paragraph:{key:`p`,code:`KeyP`,modeOverrides:{modAlt:{key:`0`,code:`Digit0`}}},heading1:{key:`1`,code:`Digit1`},heading2:{key:`2`,code:`Digit2`},heading3:{key:`3`,code:`Digit3`},heading4:{key:`4`,code:`Digit4`},heading5:{key:`5`,code:`Digit5`},heading6:{key:`6`,code:`Digit6`},bulletList:{key:`u`,code:`KeyU`},orderedList:{key:`o`,code:`KeyO`},taskList:{key:`9`,code:`Digit9`},blockquote:{key:`q`,code:`KeyQ`},inlineCode:{key:`e`,code:`KeyE`},codeBlock:{key:`c`,code:`KeyC`},table:{key:`t`,code:`KeyT`},inlineMath:{key:`f`,code:`KeyF`},mathBlock:{key:`b`,code:`KeyB`},image:{key:`i`,code:`KeyI`}},za=e=>Object.fromEntries(Object.entries(Ra).map(([t,n])=>[t,n.modeOverrides?.[e]??n])),Ba={Mod:`Ctrl`,Alt:`Alt`,Shift:`Shift`},Va={Mod:`⌘`,Alt:`⌥`,Shift:`⇧`},Ha=()=>typeof navigator<`u`&&La.test(navigator.platform),Ua=e=>{let t=e===`modAlt`?`Mod-Alt`:`Mod-Shift`,n=za(e);return Object.fromEntries(Object.entries(n).map(([e,n])=>[e,`${t}-${n.key}`]))},Wa=e=>{let t=Ha(),n=t?Va:Ba;return e.split(`-`).map(e=>n[e]??e.toUpperCase()).join(t?``:`+`)},Ga=e=>{let t=Ua(e);return Object.fromEntries(Object.entries(t).map(([e,t])=>[e,Wa(t)]))},Ka=e=>{let t=Ga(e);return{paragraph:t.paragraph,heading1:t.heading1,heading2:t.heading2,heading3:t.heading3,heading4:t.heading4,heading5:t.heading5,heading6:t.heading6,bulletList:t.bulletList,orderedList:t.orderedList,taskList:t.taskList,blockquote:t.blockquote,codeBlock:t.codeBlock}},qa=(e,t)=>{let n=Ua(t);e.update(C.paragraphKeymap.key,e=>({...e,TurnIntoText:{...e.TurnIntoText,shortcuts:n.paragraph}})),e.update(C.headingKeymap.key,e=>({...e,TurnIntoH1:{...e.TurnIntoH1,shortcuts:n.heading1},TurnIntoH2:{...e.TurnIntoH2,shortcuts:n.heading2},TurnIntoH3:{...e.TurnIntoH3,shortcuts:n.heading3},TurnIntoH4:{...e.TurnIntoH4,shortcuts:n.heading4},TurnIntoH5:{...e.TurnIntoH5,shortcuts:n.heading5},TurnIntoH6:{...e.TurnIntoH6,shortcuts:n.heading6}})),e.update(C.bulletListKeymap.key,e=>({...e,WrapInBulletList:{...e.WrapInBulletList,shortcuts:n.bulletList}})),e.update(C.orderedListKeymap.key,e=>({...e,WrapInOrderedList:{...e.WrapInOrderedList,shortcuts:n.orderedList}})),e.update(C.blockquoteKeymap.key,e=>({...e,WrapInBlockquote:{...e.WrapInBlockquote,shortcuts:n.blockquote}})),e.update(C.codeBlockKeymap.key,e=>({...e,CreateCodeBlock:{...e.CreateCodeBlock,shortcuts:n.codeBlock}})),e.update(C.inlineCodeKeymap.key,e=>({...e,ToggleInlineCode:{...e.ToggleInlineCode,shortcuts:n.inlineCode}}))},Ja=e=>{let t=Ua(e).taskList;return(0,L.$useKeymap)(`taskListTransform`,{WrapInTaskList:{shortcuts:t,command:()=>(e,t,n)=>n?Pa(n,`taskList`):!1}})},Ya=`zt-md-selection-tooltip`,Xa=e=>[{command:`strong`,iconName:`Bold`,title:e.selectionTooltipStrongTitle,markNames:[`strong`]},{command:`em`,iconName:`Italic`,title:e.selectionTooltipEmTitle,markNames:[`em`,`emphasis`]},{command:`strike`,iconName:`Strikethrough`,title:e.selectionTooltipStrikeTitle,markNames:[`strike_through`,`strikeThrough`]},{command:`inlineCode`,iconName:`Code2`,title:e.selectionTooltipInlineCodeTitle,markNames:[`inlineCode`,`code_inline`]},{command:`link`,iconName:`Code2`,title:e.selectionTooltipLinkTitle,markNames:[`link`]}],Y={paragraph:f.Type,heading1:f.Heading1,heading2:f.Heading2,heading3:f.Heading3,heading4:f.Heading4,heading5:f.Heading5,heading6:f.Heading6,bulletList:f.List,orderedList:f.ListOrdered,taskList:f.ListChecks,blockquote:f.TextQuote,codeBlock:f.Code2},Za=(e,t)=>{let n=Ka(t);return[{command:`paragraph`,icon:Y.paragraph,label:e.selectionTooltipTransformParagraphLabel,shortcut:n.paragraph},{command:`heading1`,icon:Y.heading1,label:e.selectionTooltipTransformHeading1Label,shortcut:n.heading1},{command:`heading2`,icon:Y.heading2,label:e.selectionTooltipTransformHeading2Label,shortcut:n.heading2},{command:`heading3`,icon:Y.heading3,label:e.selectionTooltipTransformHeading3Label,shortcut:n.heading3},{command:`heading4`,icon:Y.heading4,label:e.selectionTooltipTransformHeading4Label,shortcut:n.heading4},{command:`heading5`,icon:Y.heading5,label:e.selectionTooltipTransformHeading5Label,shortcut:n.heading5},{command:`heading6`,icon:Y.heading6,label:e.selectionTooltipTransformHeading6Label,shortcut:n.heading6},{command:`bulletList`,icon:Y.bulletList,label:e.selectionTooltipTransformBulletListLabel,shortcut:n.bulletList},{command:`orderedList`,icon:Y.orderedList,label:e.selectionTooltipTransformOrderedListLabel,shortcut:n.orderedList},{command:`taskList`,icon:Y.taskList,label:e.selectionTooltipTransformTaskListLabel,shortcut:n.taskList},{command:`blockquote`,icon:Y.blockquote,label:e.selectionTooltipTransformBlockquoteLabel,shortcut:n.blockquote},{command:`codeBlock`,icon:Y.codeBlock,label:e.selectionTooltipTransformCodeBlockLabel,shortcut:n.codeBlock}]},Qa=e=>typeof e.props.editable==`function`?e.props.editable(e.state):e.editable,X=(e,t)=>{let n=e.state.schema.marks,r=t.find(e=>n[e]);return r?n[r]??null:null},$a=(e,t)=>{let{from:n,to:r}=e.selection;return e.doc.rangeHasMark(n,r,t)},eo=(e,t)=>{let{from:n,to:r}=e.selection,i=``;return e.doc.nodesBetween(n,r,e=>{let n=e.marks.find(e=>e.type===t);return n?(i=typeof n.attrs.href==`string`?n.attrs.href:``,!1):!0}),i},to=e=>{(0,B.toggleMark)(e.markType)(e.view.state,e.view.dispatch,e.view),e.view.focus()},no=e=>{e.toggleLinkPopover(e.view)},ro=(e,t)=>{({strong:to,em:to,strike:to,inlineCode:to,link:no})[e](t)},io=(e,t,n,r)=>{let i=document.createElement(`button`);i.type=`button`,i.className=`zt-md-selection-tooltip-button`,i.dataset.command=e.command,i.title=e.title,i.setAttribute(`aria-label`,e.title);let a=document.createElement(`span`);return a.className=`zt-md-selection-tooltip-button-icon`,a.innerHTML=K(e.iconName,{size:14,strokeWidth:2}),i.append(a),i.addEventListener(`mousedown`,e=>{e.preventDefault()}),i.addEventListener(`click`,i=>{i.preventDefault();let a=n();!a||a.state.selection.empty||ro(e.command,{view:a,markType:t,toggleLinkPopover:r})}),i},ao=(e,t,n,r,i)=>{let a=document.createElement(`div`);return a.className=`zt-md-selection-tooltip`,a.append(i),t.forEach(t=>{let i=X(e,t.markNames);i&&t.command!==`link`&&a.append(io(t,i,n,r))}),a},oo=e=>{let t=Gi({open:e.open,portalContainer:e.portalContainer,editorWrapper:e.collisionBoundary,offsetY:8,fallbackWidth:224,fallbackHeight:360,onOutside:()=>e.onOpenChange(!1)}),n=e=>{e.preventDefault()},r=t=>{let n=e.getCurrentView();if(!n||n.state.selection.empty){e.onOpenChange(!1);return}Pa(n,t),e.onOpenChange(!1),n.focus()};return(0,c.createElement)(c.Fragment,null,(0,c.createElement)(`button`,{ref:t.triggerRef,type:`button`,className:`zt-md-selection-transform-trigger`,"aria-label":e.menuTitle,"aria-expanded":e.open,title:e.menuTitle,onMouseDown:n,onClick:()=>{if(e.open){e.onOpenChange(!1);return}t.updatePosition(),e.onOpenChange(!0)}},(0,c.createElement)(`span`,{className:`zt-md-selection-transform-trigger-label`},e.activeLabel),(0,c.createElement)(f.ChevronDown,{size:e.iconSize,strokeWidth:e.iconStrokeWidth,"aria-hidden":`true`})),(0,c.createElement)(Ki,{panel:t,portalContainer:e.portalContainer,className:`zt-md-selection-transform-popover !w-[224px] p-1`,onMouseDown:n},(0,c.createElement)(`p`,{className:`zt-md-selection-transform-popover-title`},e.menuTitle),(0,c.createElement)(`div`,{className:`zt-md-selection-transform-popover-list`},...e.items.map(t=>{let i=e.activeCommands.has(t.command);return(0,c.createElement)(`button`,{key:t.command,type:`button`,className:`zt-md-selection-transform-item`,"data-active":i?`true`:`false`,onMouseDown:n,onClick:()=>r(t.command)},(0,c.createElement)(t.icon,{size:e.iconSize,strokeWidth:e.iconStrokeWidth,className:`zt-md-selection-transform-item-icon`,"aria-hidden":`true`}),(0,c.createElement)(`span`,{className:`zt-md-selection-transform-item-label`},t.label),(0,c.createElement)(`kbd`,{className:`zt-md-selection-transform-item-shortcut`},t.shortcut))}))))},so=e=>{let[t,n]=(0,c.useState)(``),r=(0,c.useRef)(null),i=e=>{e.preventDefault()},a=t=>{let n=e.getCurrentView();if(!n||n.state.selection.empty){e.onOpenChange(!1);return}let r=X(n,[`link`]);if(!r){e.onOpenChange(!1);return}let i=St(t),{from:a,to:o}=n.state.selection,s=n.state.tr.removeMark(a,o,r);i&&s.addMark(a,o,r.create({href:i})),n.dispatch(s.scrollIntoView()),e.onOpenChange(!1),n.focus()},o=t=>{if(!t){e.onOpenChange(!1);return}let r=e.getCurrentView(),i=r?X(r,[`link`]):null;if(!r||!i||r.state.selection.empty){e.onOpenChange(!1);return}n(St(eo(r.state,i))),e.onOpenChange(!0)},s=Gi({open:e.open,portalContainer:e.portalContainer,editorWrapper:e.collisionBoundary,horizontalAlign:`center`,offsetY:8,fallbackWidth:266,fallbackHeight:48,onOutside:()=>o(!1)});return(0,c.useEffect)(()=>{if(!e.open)return;let t=e.getCurrentView(),n=t?X(t,[`link`]):null;(!t||!n||t.state.selection.empty)&&e.onOpenChange(!1)},[e.open,e.getCurrentView,e.onOpenChange]),(0,c.useEffect)(()=>{e.open&&r.current?.focus()},[e.open]),(0,c.createElement)(c.Fragment,null,(0,c.createElement)(`button`,{ref:t=>{s.triggerRef.current=t,e.triggerRef(t)},type:`button`,className:`zt-md-selection-tooltip-button`,"data-command":`link`,title:e.messages.selectionTooltipLinkTitle,"aria-label":e.messages.selectionTooltipLinkTitle,"aria-expanded":e.open,onMouseDown:i,onClick:()=>{if(e.open){o(!1);return}s.updatePosition(),o(!0)}},(0,c.createElement)(`span`,{className:`zt-md-selection-tooltip-button-icon`},(0,c.createElement)(f.Link2,{size:e.iconSize,strokeWidth:e.iconStrokeWidth}))),(0,c.createElement)(Ki,{panel:s,portalContainer:e.portalContainer,className:`zt-md-selection-link-popover w-fit min-w-0 gap-0 p-2`},(0,c.createElement)(`div`,{className:`zt-md-selection-link-popover-row`},(0,c.createElement)(`input`,{ref:r,type:`text`,value:t,placeholder:e.messages.selectionLinkInputPlaceholder,className:`zt-md-selection-link-popover-input`,onChange:e=>n(e.currentTarget.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),a(t.trim()))}}),(0,c.createElement)(`button`,{type:`button`,className:`zt-md-selection-link-popover-action`,onMouseDown:i,onClick:()=>a(t.trim()),"aria-label":e.messages.selectionLinkSaveAriaLabel},(0,c.createElement)(f.Check,{size:e.iconSize,strokeWidth:e.iconStrokeWidth})),(0,c.createElement)(`button`,{type:`button`,className:`zt-md-selection-link-popover-action zt-md-selection-link-popover-action-danger`,onMouseDown:i,onClick:()=>a(``),"aria-label":e.messages.selectionLinkRemoveAriaLabel},(0,c.createElement)(f.Trash2,{size:e.iconSize,strokeWidth:e.iconStrokeWidth})))))},co=(e,t,n)=>{n.forEach(n=>{let r=X(t,n.markNames);if(!r)return;let i=e.querySelector(`[data-command="${n.command}"]`);i instanceof HTMLButtonElement&&(i.dataset.active=$a(t.state,r)?`true`:`false`)})},lo=e=>{let{from:t,to:n}=e.state.selection,r=!1;return e.state.doc.nodesBetween(t,n,e=>e.type.name===`code_block`?(r=!0,!1):!0),r},uo=(e,t,n)=>r=>{let{selection:i,doc:a}=r.state,o=e.contains(document.activeElement);return!Qa(r)||i.empty||!(i instanceof v.TextSelection)||!r.hasFocus()&&!o&&!t()&&!n()||lo(r)?!1:e.childElementCount>0&&a.textBetween(i.from,i.to).trim().length>0},fo=e=>{let{$from:t}=e.state.selection;for(let e=t.depth;e>0;--e){let n=t.node(e).type.name;if(n===`table`||n===`table_cell`||n===`table_header`)return!0}return!1},po=(e,t,n,r)=>{let i=Xa(n),a=Za(n,r),o=e,s=!1,l=!1,u=!1,d=0,f=``,p=document.createElement(`span`),m=(0,ae.createRoot)(p),h=document.createElement(`span`),g=null,_=(0,ae.createRoot)(h),v=t.closest(`.zt-md-editor`),y=e=>{s!==e&&(s=e,C())},b=e=>{l!==e&&(l=e,S())},x=e=>{e.state.selection.empty||y(!s)},S=()=>{let e=o?Fa(o):new Set([`paragraph`]),r=o?Ia(o):`paragraph`,i=`${d}:${r}:${l}:${Array.from(e).sort().join(`,`)}`;if(f===i)return;f=i;let s=a.find(e=>e.command===r)??a[0];m.render((0,c.createElement)(oo,{getCurrentView:()=>o,portalContainer:t,collisionBoundary:v,iconSize:14,iconStrokeWidth:2,menuTitle:n.selectionTooltipTransformLabel,items:a,activeLabel:s?.label??n.selectionTooltipTransformParagraphLabel,open:l,onOpenChange:b,activeCommands:e}))},C=()=>{_.render((0,c.createElement)(so,{getCurrentView:()=>o,portalContainer:t,collisionBoundary:v,iconSize:14,iconStrokeWidth:2,triggerRef:e=>{g=e},open:s,onOpenChange:y,messages:n}))},w=ao(e,i,()=>o,x,p);S(),X(e,[`link`])&&(w.append(h),C());let T=uo(w,()=>s,()=>l),E=new de.TooltipProvider({content:w,debounce:80,offset:8,root:t,shouldShow:T,floatingUIOptions:{placement:`top`}}),D=()=>{w.parentElement||t.appendChild(w)},O=()=>{w.remove()};E.onHide=O;let k=()=>{y(!1),b(!1),E.hide(),O()},A=e=>e instanceof Node?!!o?.dom.contains(e)||w.contains(e)||t.contains(e):!1,j=()=>{requestAnimationFrame(()=>{u||A(document.activeElement)||k()})},M=e=>{A(e.target)||k()};e.dom.addEventListener(`blur`,j),document.addEventListener(`mousedown`,M,!0);let N=W(n,()=>{d+=1,i=Xa(n),a=Za(n,r),i.forEach(e=>{let t=w.querySelector(`[data-command="${e.command}"]`);t&&(t.title=e.title,t.setAttribute(`aria-label`,e.title))}),S(),X(e,[`link`])&&C()});return{update:(e,t)=>{if(o=e,o.composing){w.parentElement&&k();return}if(o.state.selection.empty&&(y(!1),b(!1)),!T(o)){E.hide(),O();return}let n=fo(o);if(p.hidden=n,n?b(!1):S(),co(w,o,i),g){let e=X(o,[`link`]);g.dataset.active=e&&$a(o.state,e)?`true`:`false`}D(),E.update(o,t)},destroy:()=>{N(),u=!0,o=null,e.dom.removeEventListener(`blur`,j),document.removeEventListener(`mousedown`,M,!0),m.unmount(),_.unmount(),E.destroy(),w.remove()}}},mo=(e,t,n)=>(0,L.$prose)(()=>new v.Plugin({key:new v.PluginKey(Ya),view:r=>po(r,e,t,n)})),ho=(e,t)=>e(t.state,t.dispatch,t),go=e=>{let t=e?.state?.selection?.$from;if(!t)return!1;for(let e=t.depth;e>0;--e)if(t.node(e)?.type?.name===`table`)return!0;return!1},_o=(e,t)=>{let n=e?.state?.doc;if(!n||typeof t!=`number`)return-1;let r=Math.min(Math.max(t,0),n.content.size),i=n.resolve(r);for(let e=i.depth;e>0;--e)if(i.node(e)?.type?.name===`table`)return i.before(e);return-1},vo=(e,t,n,r)=>{let i=e?.state?.schema?.nodes;if(!i)return null;let a=i.table,o=i.table_header_row,s=i.table_row,c=i.table_header,l=i.table_cell;if(!a||!o||!s||!c||!l)return null;let u=Math.max(1,t),d=Math.max(1,n),f=Array.from({length:u},(e,t)=>{let n=r&&t===0,i=n?o:s,a=n?c:l,u=Array.from({length:d},()=>a.createAndFill()).filter(Boolean);return i.create(null,u)});return a.create(null,f)},yo=e=>{if(!e?.state||!e?.dispatch||go(e))return!1;let t=e.state.selection.from,n=vo(e,3,3,!0);if(!n)return!1;e.dispatch(e.state.tr.replaceSelectionWith(n).scrollIntoView());let r=_o(e,t);if(r<0&&t>0&&(r=_o(e,t-1)),r<0)return!0;let i=r+2;if(i>e.state.doc.content.size)return!0;let a=v.TextSelection.near(e.state.doc.resolve(i),1);return e.dispatch(e.state.tr.setSelection(a).scrollIntoView()),e.focus(),!0},bo=(e,t)=>{let n=e?.state?.schema?.marks??{},r=t.find(e=>n[e]);return r?n[r]??null:null},xo=new Set([`paragraph`,`heading1`,`heading2`,`heading3`,`heading4`,`heading5`,`heading6`,`bulletList`,`orderedList`,`taskList`,`blockquote`,`codeBlock`]),So=e=>xo.has(e),Co={inlineCode:e=>{let t=bo(e,[`inlineCode`,`code_inline`]);return t?ho((0,B.toggleMark)(t),e):!1},inlineMath:e=>{let t=e?.state?.schema?.nodes?.math_inline;if(!t||!e?.dispatch)return!1;let n=e.state.selection.from,r=t.create({value:``});return e.dispatch(e.state.tr.replaceSelectionWith(r).setMeta(q,{type:`open`,position:n}).scrollIntoView()),!0},mathBlock:e=>{let t=e.state.schema.nodes?.math_block;if(!t||!ho((0,B.setBlockType)(t),e))return!1;let n=e.state.selection?.$from;if(!n)return!0;let r=null;for(let e=n.depth;e>0;--e)if(n.node(e)?.type?.name===`math_block`){r=n.before(e);break}if(r===null)return!0;let i=v.NodeSelection.create(e.state.doc,r);return e.dispatch(e.state.tr.setSelection(i).scrollIntoView()),!0},table:yo},wo=(e,t)=>!e?.state||!e?.dispatch?!1:So(t)?Pa(e,t):t===`image`?!1:Co[t](e),To=e=>typeof e?.props?.editable==`function`?e.props.editable(e.state):!!e?.editable,Eo=[{id:`paragraph`,label:`普通文本`,group:`标题`,icon:`Type`,command:`paragraph`},{id:`heading-1`,label:`标题 1`,group:`标题`,icon:`Heading1`,command:`heading1`},{id:`heading-2`,label:`标题 2`,group:`标题`,icon:`Heading2`,command:`heading2`},{id:`heading-3`,label:`标题 3`,group:`标题`,icon:`Heading3`,command:`heading3`},{id:`heading-4`,label:`标题 4`,group:`标题`,icon:`Heading4`,command:`heading4`},{id:`heading-5`,label:`标题 5`,group:`标题`,icon:`Heading5`,command:`heading5`},{id:`heading-6`,label:`标题 6`,group:`标题`,icon:`Heading6`,command:`heading6`},{id:`bullet-list`,label:`无序列表`,group:`列表`,icon:`List`,command:`bulletList`},{id:`ordered-list`,label:`有序列表`,group:`列表`,icon:`ListOrdered`,command:`orderedList`},{id:`task-list`,label:`任务列表`,group:`列表`,icon:`ListTodo`,command:`taskList`},{id:`blockquote`,label:`引用块`,group:`插入`,icon:`TextQuote`,command:`blockquote`},{id:`inline-code`,label:`行内代码`,group:`插入`,icon:`Code`,command:`inlineCode`},{id:`code-block`,label:`代码块`,group:`插入`,icon:`SquareCode`,command:`codeBlock`},{id:`table`,label:`表格`,group:`插入`,icon:`Table`,command:`table`},{id:`inline-math`,label:`行内公式`,group:`公式`,icon:`Sigma`,command:`inlineMath`},{id:`math-block`,label:`公式块`,group:`公式`,icon:`SquareFunction`,command:`mathBlock`},{id:`image`,label:`图片`,group:`媒体`,icon:`Image`,command:`image`}],Do=[{id:`paragraph`,label:`Paragraph`,group:`Headings`,icon:`Type`,command:`paragraph`},{id:`heading-1`,label:`Heading 1`,group:`Headings`,icon:`Heading1`,command:`heading1`},{id:`heading-2`,label:`Heading 2`,group:`Headings`,icon:`Heading2`,command:`heading2`},{id:`heading-3`,label:`Heading 3`,group:`Headings`,icon:`Heading3`,command:`heading3`},{id:`heading-4`,label:`Heading 4`,group:`Headings`,icon:`Heading4`,command:`heading4`},{id:`heading-5`,label:`Heading 5`,group:`Headings`,icon:`Heading5`,command:`heading5`},{id:`heading-6`,label:`Heading 6`,group:`Headings`,icon:`Heading6`,command:`heading6`},{id:`bullet-list`,label:`Bullet list`,group:`Lists`,icon:`List`,command:`bulletList`},{id:`ordered-list`,label:`Ordered list`,group:`Lists`,icon:`ListOrdered`,command:`orderedList`},{id:`task-list`,label:`Task list`,group:`Lists`,icon:`ListTodo`,command:`taskList`},{id:`blockquote`,label:`Blockquote`,group:`Insert`,icon:`TextQuote`,command:`blockquote`},{id:`inline-code`,label:`Inline code`,group:`Insert`,icon:`Code`,command:`inlineCode`},{id:`code-block`,label:`Code block`,group:`Insert`,icon:`SquareCode`,command:`codeBlock`},{id:`table`,label:`Table`,group:`Insert`,icon:`Table`,command:`table`},{id:`inline-math`,label:`Inline math`,group:`Math`,icon:`Sigma`,command:`inlineMath`},{id:`math-block`,label:`Math block`,group:`Math`,icon:`SquareFunction`,command:`mathBlock`},{id:`image`,label:`Image`,group:`Media`,icon:`Image`,command:`image`}],Oo=(e,t=`zh-CN`)=>e?.items&&e.items.length>0?e.items:t===`en-US`?Do:Eo,ko=e=>{let t=e?.state?.selection?.$from;if(!t)return!1;let n=String(t.parent?.type?.name??``);if(n.includes(`code`)||n===`math_block`)return!0;for(let e=t.depth;e>0;--e){let n=String(t.node(e)?.type?.name??``);if(n===`table`||n===`table_cell`||n===`table_header`)return!0}return!1},Ao=e=>{let t=e?.state,n=t?.selection?.$from;if(!t||!n)return``;let r=n.start(),i=n.pos;return t.doc.textBetween(r,i,`
|
|
17
|
+
</html>`,Zi=e=>typeof e==`function`?e():null,Qi=e=>typeof e.props.editable==`function`?e.props.editable(e.state):e.editable,$i=class{syncLanguageAttribute(e){let t=typeof e.attrs.language==`string`?e.attrs.language.trim():``;if(!t){this.contentDOM.removeAttribute(`data-language`);return}this.contentDOM.setAttribute(`data-language`,t)}constructor(e,t,n,r){this.previewFrame=null,this.isPreviewAvailable=!1,this.isPreviewMode=!1,this.renderedPreviewKey=null,this.copyFeedbackTimer=null,this.handlePreviewClick=e=>{e.preventDefault(),e.stopPropagation(),this.isPreviewAvailable&&(this.isPreviewMode=!this.isPreviewMode,this.syncPreviewState(),this.view.dispatch(this.view.state.tr.setMeta(Ui,!0)))},this.handlePreviewKeyDown=e=>{if(e.defaultPrevented||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey||e.key!==`ArrowUp`&&e.key!==`ArrowDown`)return;let t=Zi(this.getPos);t!==null&&kt(this.view,t,this.node,e.key)&&e.preventDefault()},this.handleCopyClick=e=>{if(e.preventDefault(),e.stopPropagation(),!Qi(this.view))return;let t=this.node.textContent;(typeof navigator<`u`&&navigator.clipboard?.writeText?navigator.clipboard.writeText(t):Promise.resolve()).then(()=>{this.copyButton.innerHTML=Ki,this.copyButton.dataset.copied=`true`,this.copyFeedbackTimer!==null&&clearTimeout(this.copyFeedbackTimer),this.copyFeedbackTimer=setTimeout(()=>{this.copyButton.innerHTML=Gi,delete this.copyButton.dataset.copied,this.copyFeedbackTimer=null},Vi)}).catch(()=>{})},this.handleDeleteClick=e=>{e.preventDefault(),e.stopPropagation(),Qi(this.view)&&this.deleteCurrentCodeBlock()},this.node=e,this.view=t,this.getPos=n,this.messages=r,this.dom=document.createElement(`div`),this.dom.className=`zt-md-code-block`,this.dom.dataset.type=Bi,this.contentDOM=document.createElement(`pre`),this.previewContainer=document.createElement(`div`),this.previewContainer.className=`zt-md-code-block-preview`,this.previewContainer.contentEditable=`false`,this.previewContainer.hidden=!0,this.previewContainer.tabIndex=-1,this.previewContainer.setAttribute(`role`,`region`),this.previewContainer.setAttribute(`aria-label`,r.codeBlockPreviewAriaLabel),this.actionsContainer=document.createElement(`span`),this.actionsContainer.className=`zt-md-code-block-actions`,this.actionsContainer.contentEditable=`false`,this.previewButton=document.createElement(`button`),this.previewButton.type=`button`,this.previewButton.className=`zt-md-code-block-action-button`,this.previewButton.hidden=!0,this.previewButton.innerHTML=Ji,this.copyButton=document.createElement(`button`),this.copyButton.type=`button`,this.copyButton.className=`zt-md-code-block-action-button zt-md-code-block-editable-action`,this.copyButton.setAttribute(`aria-label`,r.codeBlockCopyAriaLabel),this.copyButton.innerHTML=Gi,this.deleteButton=document.createElement(`button`),this.deleteButton.type=`button`,this.deleteButton.className=`zt-md-code-block-action-button zt-md-code-block-editable-action zt-md-code-block-action-button-danger`,this.deleteButton.setAttribute(`aria-label`,r.codeBlockDeleteAriaLabel),this.deleteButton.innerHTML=qi,this.actionsContainer.append(this.previewButton,this.copyButton,this.deleteButton),this.dom.append(this.contentDOM,this.previewContainer,this.actionsContainer),this.updateEditableState(),this.syncLanguageAttribute(e),this.syncPreviewAvailability(e),this.previewButton.addEventListener(`click`,this.handlePreviewClick),this.copyButton.addEventListener(`click`,this.handleCopyClick),this.deleteButton.addEventListener(`click`,this.handleDeleteClick),this.previewContainer.addEventListener(`keydown`,this.handlePreviewKeyDown),this.stopObservingMessages=W(r,()=>{this.previewContainer.setAttribute(`aria-label`,r.codeBlockPreviewAriaLabel),this.copyButton.setAttribute(`aria-label`,r.codeBlockCopyAriaLabel),this.deleteButton.setAttribute(`aria-label`,r.codeBlockDeleteAriaLabel);let e=this.isPreviewAvailable&&this.isPreviewMode?r.codeBlockSourceAriaLabel:r.codeBlockPreviewAriaLabel;this.previewButton.setAttribute(`aria-label`,e),this.previewButton.title=e,this.previewFrame&&(this.previewFrame.title=r.codeBlockPreviewAriaLabel)})}deleteCurrentCodeBlock(){let e=Zi(this.getPos);if(e===null)return;let t=this.view.state.tr.delete(e,e+this.node.nodeSize),n=Math.min(e,t.doc.content.size);t.setSelection(v.TextSelection.near(t.doc.resolve(n),-1)).scrollIntoView(),this.view.dispatch(t),requestAnimationFrame(()=>{this.view.focus()})}updateEditableState(){this.dom.dataset.editable=Qi(this.view)?`true`:`false`}syncPreviewAvailability(e){let t=typeof e.attrs.language==`string`?e.attrs.language:``;this.isPreviewAvailable=zi(t),this.isPreviewAvailable||(this.isPreviewMode=!1),this.previewButton.hidden=!this.isPreviewAvailable,this.syncPreviewState(),this.syncActionsVisibility()}syncPreviewState(){let e=this.isPreviewAvailable&&this.isPreviewMode,t=e?this.messages.codeBlockSourceAriaLabel:this.messages.codeBlockPreviewAriaLabel;if(this.dom.dataset.viewMode=e?`preview`:`source`,this.previewContainer.hidden=!e,this.previewContainer.tabIndex=e?0:-1,this.previewButton.dataset.active=e?`true`:`false`,this.previewButton.setAttribute(`aria-pressed`,e?`true`:`false`),this.previewButton.setAttribute(`aria-label`,t),this.previewButton.title=t,this.previewButton.innerHTML=e?Yi:Ji,e){this.contentDOM.setAttribute(`aria-hidden`,`true`),this.renderPreview();return}this.contentDOM.removeAttribute(`aria-hidden`),this.clearPreview()}syncActionsVisibility(){let e=Qi(this.view)||this.isPreviewAvailable;this.actionsContainer.dataset.visible=e?`true`:`false`}renderPreview(){let e=this.node.textContent,t=Y(String(this.node.attrs.language??``)),n=t===Hi,r=`${t}\u0000${e}`;if(this.renderedPreviewKey===r)return;this.renderedPreviewKey=r;let i=document.createElement(`iframe`);i.className=`zt-md-code-block-preview-frame`,i.title=this.messages.codeBlockPreviewAriaLabel,i.tabIndex=-1,i.referrerPolicy=`no-referrer`,i.setAttribute(`sandbox`,n?`allow-scripts`:``),i.srcdoc=Xi(e,n),this.previewContainer.replaceChildren(i),this.previewFrame=i}clearPreview(){this.renderedPreviewKey=null,this.previewFrame?.remove(),this.previewFrame=null}update(e){return e.type.name===Bi?(this.node=e,this.updateEditableState(),this.syncLanguageAttribute(e),this.syncPreviewAvailability(e),!0):!1}stopEvent(e){let t=e.target;return t instanceof Node?this.actionsContainer.contains(t)||this.previewContainer.contains(t):!1}ignoreMutation(e){return e.type===`selection`?!1:e.type===`attributes`&&(e.target===this.dom&&e.attributeName===`data-view-mode`||e.target===this.contentDOM&&e.attributeName===`aria-hidden`)?!0:this.actionsContainer.contains(e.target)||this.previewContainer.contains(e.target)}destroy(){this.stopObservingMessages(),this.previewButton.removeEventListener(`click`,this.handlePreviewClick),this.copyButton.removeEventListener(`click`,this.handleCopyClick),this.deleteButton.removeEventListener(`click`,this.handleDeleteClick),this.previewContainer.removeEventListener(`keydown`,this.handlePreviewKeyDown),this.copyFeedbackTimer!==null&&(clearTimeout(this.copyFeedbackTimer),this.copyFeedbackTimer=null),this.copyButton.innerHTML=Gi,delete this.copyButton.dataset.copied,this.clearPreview()}},ea=(e=U())=>(t,n,r)=>new $i(t,n,typeof r==`function`?()=>{let e=r();return typeof e==`number`?e:0}:!1,e),ta=new Set,na=!1,ra=()=>typeof document<`u`,ia=e=>{Array.from(ta).forEach(t=>t(e))},aa=()=>{na||!ra()||(document.addEventListener(`scroll`,ia,{capture:!0,passive:!0}),na=!0)},oa=()=>{!na||!ra()||(document.removeEventListener(`scroll`,ia,!0),na=!1)},sa=e=>{if(!ra())return()=>void 0;let t=!0;return ta.add(e),aa(),()=>{t&&(t=!1,ta.delete(e),ta.size===0&&oa())}},ca=e=>e?e.closest(`.zt-md-editor`)??e:null,la=(e,t,n)=>{let r=typeof window>`u`?e.bottom:window.innerHeight,i=n?.top??0,a=n?.bottom??r,o=e.top-i,s=a-e.bottom;return s<t&&o>s?`top`:`bottom`},ua=(e,t,n)=>{let r=n??t.getBoundingClientRect();return{anchorTopInContent:e.top-r.top+t.scrollTop,anchorBottomInContent:e.bottom-r.top+t.scrollTop,anchorLeftInContent:e.left-r.left+t.scrollLeft,anchorRightInContent:e.right-r.left+t.scrollLeft}},da=e=>{let{anchor:t,overlaySize:n,horizontalAlign:r=`start`}=e,i=t.anchorRightInContent??t.anchorLeftInContent;return r===`end`?i-n.width:r===`center`?t.anchorLeftInContent+(i-t.anchorLeftInContent-n.width)/2:t.anchorLeftInContent},fa=(e,t)=>{let{wrapper:n,anchor:r,overlaySize:i,placement:a,offsetY:o,boundaryInset:s}=e,c=t??n.getBoundingClientRect(),l=n.scrollLeft+s,u=n.scrollLeft+n.clientWidth-i.width-s,d=da(e),f=Math.min(Math.max(d,l),Math.max(l,u)),p=a===`top`?r.anchorTopInContent-(i.height??0)-o:r.anchorBottomInContent+o;return{left:c.left+f-n.scrollLeft,top:c.top+p-n.scrollTop}},pa=(e,t,n)=>{let r=fa(e,n),i=t.getBoundingClientRect();return{left:r.left-i.left,top:r.top-i.top}},ma=e=>{let t=0,n=null,r=null,i=()=>{typeof window>`u`||(t&&window.cancelAnimationFrame(t),t=window.requestAnimationFrame(()=>{t=0,e()}))},a=()=>{window.addEventListener(`resize`,i),r||=sa(i)},o=()=>{window.removeEventListener(`resize`,i),r?.(),r=null},s=e=>{n!==e&&(n&&n.removeEventListener(`scroll`,i),n=e,n&&n.addEventListener(`scroll`,i,{passive:!0}))};return{schedule:i,bindGlobal:a,unbindGlobal:o,bindWrapper:s,destroy:()=>{typeof window<`u`&&t&&(window.cancelAnimationFrame(t),t=0),o(),s(null)}}},ha=(e,t,n,r)=>{let i=t.top-r.top,a=r.bottom-t.bottom;return e===`top`?i<n&&a>i?`bottom`:`top`:a<n&&i>a?`top`:`bottom`},ga=({open:e,portalContainer:t,editorWrapper:n,defaultPlacement:r=`bottom`,horizontalAlign:i=`start`,offsetY:a=8,boundaryInset:o=2,fallbackWidth:s,fallbackHeight:l,onOutside:u})=>{let d=(0,c.useRef)(null),f=(0,c.useRef)(null),p=(0,c.useRef)(e),m=(0,c.useRef)(u);m.current=u;let h=(0,c.useCallback)(()=>{let e=d.current,c=f.current;if(!p.current||!e||!c||!t||!n)return;let u=e.getBoundingClientRect(),m=n.getBoundingClientRect(),h=c.offsetWidth||s,g=c.offsetHeight||l,_=ha(r,u,g,m),v=pa({wrapper:n,anchor:ua(u,n,m),overlaySize:{width:h,height:g},placement:_,horizontalAlign:i,offsetY:a,boundaryInset:o},t,m);c.style.position=`absolute`,c.style.left=`${v.left}px`,c.style.top=`${v.top}px`,c.style.transform=``,c.style.visibility=`visible`},[o,r,n,l,s,i,a,t]),g=(0,c.useCallback)(e=>{f.current=e,e&&(e.style.visibility=`hidden`,h())},[h]);return(0,c.useLayoutEffect)(()=>{if(p.current=e,!e){f.current&&(f.current.style.visibility=`hidden`);return}h()},[e,h]),(0,c.useEffect)(()=>{if(!e)return;let t=ma(h);return t.bindGlobal(),t.bindWrapper(n??null),t.schedule(),()=>{t.destroy()}},[n,e,h]),(0,c.useEffect)(()=>{if(!e)return;let t=e=>{let t=e.target;t instanceof Node&&(d.current?.contains(t)||f.current?.contains(t)||m.current())};return document.addEventListener(`mousedown`,t),()=>{document.removeEventListener(`mousedown`,t)}},[e]),{open:e,triggerRef:d,panelRef:g,updatePosition:h}},_a=({panel:e,portalContainer:t,className:n,role:r,onMouseDown:i,children:a})=>!e.open||!t?null:(0,ue.createPortal)((0,c.createElement)(`div`,{ref:e.panelRef,role:r,className:n,style:{position:`absolute`,visibility:`hidden`},onMouseDown:i},a),t),va=`code_block`,ya=`ZT_MD_CODE_BLOCK_LANGUAGE_PICKER`,ba=8,xa=96,Sa=26,Ca=224,wa=220,Ta=[`javascript`,`typescript`,`tsx`,`jsx`,`html`,`css`,`json`,`bash`,`python`,`go`,`java`,`sql`,`yaml`,`markdown`,`rust`,`cpp`,`c`,`csharp`,`php`,`docker`],Ea=e=>{let t=E.refractor.listLanguages(),n=new Set(t.map(e=>Y(e)).filter(e=>e!==Pi)),r=[];for(let e of Ta)n.delete(e)&&r.push({value:e,label:e});let i=[...n].sort((e,t)=>e.localeCompare(t));return[{value:Pi,label:e},...r,...i.map(e=>({value:e,label:e}))]},Da=e=>{let t=e.state.selection.$from;for(let e=t.depth;e>=0;--e){let n=t.node(e);if(n.type.name===va)return{position:e===0?0:t.before(e),node:n}}return null},Oa=(e,t)=>{let n=e.nodeDOM(t);return n instanceof HTMLPreElement?n:n instanceof HTMLElement?n.querySelector(`pre`):null},ka=e=>typeof e.props.editable==`function`?e.props.editable(e.state):e.editable,Aa=e=>{let[t,n]=(0,c.useState)(!1),[r,i]=(0,c.useState)(``),[a,o]=(0,c.useState)(0),s=(0,c.useRef)(null),l=(0,c.useRef)(null),u=Y(e.currentLanguage),d=u===`text`?e.messages.codeBlockLanguagePlainText:u,p=(0,c.useMemo)(()=>Ea(e.messages.codeBlockLanguagePlainText),[e.messages.codeBlockLanguagePlainText]),m=(0,c.useMemo)(()=>{let e=r.trim().toLowerCase();if(!e)return p;let t=[],n=[];for(let r of p){let i=r.label.toLowerCase(),a=r.value.toLowerCase();a.startsWith(e)||i.startsWith(e)?t.push(r):(a.includes(e)||i.includes(e))&&n.push(r)}return[...t,...n]},[r,p]),h=ga({open:t,portalContainer:e.portalContainer,editorWrapper:e.collisionBoundary,horizontalAlign:`end`,offsetY:6,fallbackWidth:Ca,fallbackHeight:wa,onOutside:()=>n(!1)}),g=e=>e instanceof HTMLElement?e.closest(`input, textarea, [contenteditable]:not([contenteditable="false"])`)!==null:!1,_=e=>{g(e.target)||e.preventDefault()},v=()=>{if(t){n(!1);return}let e=m.findIndex(e=>e.value===u);o(e>=0?e:0),h.updatePosition(),n(!0)},y=t=>{e.onSelectLanguage(t),n(!1),i(``)},b=e=>{m.length!==0&&o(t=>(t+e+m.length)%m.length)},x=()=>{let e=m[a];e&&y(e.value)};return(0,c.useLayoutEffect)(()=>{e.onLayoutChange()},[d,e.onLayoutChange]),(0,c.useEffect)(()=>{n(!1),i(``),o(0)},[e.currentLanguage]),(0,c.useEffect)(()=>{t&&s.current?.focus()},[t]),(0,c.useEffect)(()=>{if(!t)return;let e=l.current,n=e?.querySelector(`[data-active="true"]`);if(!e||!n)return;let r=e.getBoundingClientRect(),i=n.getBoundingClientRect();i.top<r.top?e.scrollTop+=i.top-r.top:i.bottom>r.bottom&&(e.scrollTop+=i.bottom-r.bottom)},[a,m,t]),(0,c.createElement)(c.Fragment,null,(0,c.createElement)(`div`,{className:`zt-md-code-language-picker`,onMouseDown:_},(0,c.createElement)(`button`,{ref:h.triggerRef,type:`button`,className:`zt-md-code-language-picker-trigger`,"aria-expanded":t,"aria-label":d,onClick:v},(0,c.createElement)(`span`,{className:`zt-md-code-language-picker-trigger-label`},d),(0,c.createElement)(f.ChevronDown,{className:`zt-md-code-language-picker-trigger-icon`,size:14,strokeWidth:2,"aria-hidden":`true`}))),(0,c.createElement)(_a,{panel:h,portalContainer:e.portalContainer,className:`zt-md-code-language-picker-panel`,onMouseDown:_},(0,c.createElement)(`label`,{className:`zt-md-code-language-picker-search`},(0,c.createElement)(f.Search,{className:`zt-md-code-language-picker-search-icon`,size:14,strokeWidth:2,"aria-hidden":`true`}),(0,c.createElement)(`input`,{ref:s,value:r,onChange:e=>{i(e.currentTarget.value),o(0)},onKeyDown:e=>{let t={ArrowDown:()=>b(1),ArrowUp:()=>b(-1),Enter:x}[e.key];t&&(e.preventDefault(),t())},placeholder:e.messages.codeBlockLanguageSearchPlaceholder,className:`zt-md-code-language-picker-search-input`})),(0,c.createElement)(`div`,{ref:l,className:`zt-md-code-language-picker-options`,role:`listbox`},m.length>0?m.map((e,t)=>(0,c.createElement)(`button`,{key:e.value||`__plain_text__`,type:`button`,role:`option`,"aria-selected":e.value===u?`true`:`false`,className:`zt-md-code-language-picker-option`,"data-active":t===a?`true`:`false`,"data-selected":e.value===u?`true`:`false`,onClick:()=>y(e.value)},(0,c.createElement)(`span`,null,e.label),e.value===u?(0,c.createElement)(f.Check,{className:`zt-md-code-language-picker-option-check`,size:14,strokeWidth:2,"aria-hidden":`true`}):null)):(0,c.createElement)(`div`,{className:`zt-md-code-language-picker-empty`},`-`))))},ja=class{constructor(e,t,n){this.isAttached=!1,this.currentCodeBlockPosition=null,this.currentPreElement=null,this.currentActionsContainer=null,this.currentRenderedLanguage=null,this.hasPositionContext=!1,this.repositionScheduler=ma(()=>{this.hasPositionContext&&this.updateOverlayPosition()}),this.handlePickerLayoutChange=()=>{this.hasPositionContext&&this.updateOverlayPosition()},this.view=e,this.messages=t,this.portalContainer=n,this.editorWrapper=ca(e.dom),this.host=document.createElement(`span`),this.host.className=`zt-md-code-language-picker-host`,this.hostRoot=(0,oe.createRoot)(this.host),this.update(e),this.stopObservingMessages=W(t,()=>{let e=this.currentRenderedLanguage;this.currentRenderedLanguage=null,e!==null&&this.render(e)})}applyLanguage(e){if(this.currentCodeBlockPosition===null)return;let t=this.view.state.doc.nodeAt(this.currentCodeBlockPosition);if(!t||t.type.name!==va)return;let n=Y(e),r={...t.attrs,language:n};if(String(t.attrs.language??``)===n)return;let i=this.view.state.tr.setNodeMarkup(this.currentCodeBlockPosition,t.type,r,t.marks);this.view.dispatch(i),this.view.focus()}render(e){this.currentRenderedLanguage!==null&&this.currentRenderedLanguage===e||(this.hostRoot.render((0,c.createElement)(Aa,{currentLanguage:e,messages:{...this.messages},portalContainer:this.portalContainer,collisionBoundary:this.editorWrapper,onSelectLanguage:e=>this.applyLanguage(e),onLayoutChange:this.handlePickerLayoutChange})),this.host.dataset.mounted=`true`,this.currentRenderedLanguage=e)}syncFocusedActionsContainer(e){this.currentActionsContainer!==e&&(delete this.currentActionsContainer?.dataset.focused,this.currentActionsContainer=e,this.currentActionsContainer&&(this.currentActionsContainer.dataset.focused=`true`))}detach(){this.isAttached&&(this.isAttached=!1,this.repositionScheduler.unbindGlobal(),this.repositionScheduler.bindWrapper(null),this.syncFocusedActionsContainer(null),this.hostRoot.render(null),delete this.host.dataset.mounted,this.host.remove(),this.currentCodeBlockPosition=null,this.currentPreElement=null,this.currentRenderedLanguage=null,this.hasPositionContext=!1)}updateOverlayPosition(){if(!this.editorWrapper||!this.currentPreElement||this.host.parentElement!==this.portalContainer)return;let e=this.editorWrapper.getBoundingClientRect(),t=this.currentPreElement.getBoundingClientRect(),n=ua(t,this.editorWrapper,e),r=n.anchorRightInContent??n.anchorLeftInContent+t.width,i=Math.max(0,Math.min(t.width,this.editorWrapper.clientWidth)-ba*2);this.host.style.setProperty(`--zt-md-code-language-picker-max-width`,`${i}px`);let a=this.host.offsetWidth||Math.min(xa,i),o=this.host.offsetHeight||Sa,s=pa({wrapper:this.editorWrapper,anchor:{anchorLeftInContent:r-a-ba,anchorTopInContent:n.anchorTopInContent+t.height-o-ba,anchorBottomInContent:n.anchorTopInContent+t.height-o-ba},overlaySize:{width:a},placement:`top`,offsetY:0,boundaryInset:2},this.portalContainer,e);this.host.style.left=`${s.left}px`,this.host.style.top=`${s.top}px`}update(e){if(this.view=e,e.composing)return;if(!ka(e)||!this.editorWrapper){this.detach();return}let t=Da(e);if(!t){this.detach();return}let n=Oa(e,t.position);if(!n){this.detach();return}let r=n.parentElement?.querySelector(`:scope > .zt-md-code-block-actions`)??null;this.syncFocusedActionsContainer(r);let i=this.isAttached;this.isAttached||(this.isAttached=!0,this.repositionScheduler.bindGlobal(),this.repositionScheduler.bindWrapper(this.editorWrapper)),this.host.parentElement!==this.portalContainer&&this.portalContainer.append(this.host);let a=Y(String(t.node.attrs.language??``)),o=this.currentCodeBlockPosition===t.position&&this.currentPreElement===n&&this.currentRenderedLanguage!==null&&this.currentRenderedLanguage===a;this.currentCodeBlockPosition=t.position,this.currentPreElement=n,this.hasPositionContext=!0,o||this.render(a),i?this.repositionScheduler.schedule():this.updateOverlayPosition()}destroy(){this.stopObservingMessages(),this.detach(),this.repositionScheduler.destroy(),this.hostRoot.unmount()}},Ma=(e,t)=>(0,I.$prose)(()=>new v.Plugin({key:new v.PluginKey(ya),view:n=>new ja(n,e,t)})),Na=new Set([`code_block`,`frontmatter`]),Pa=`a`,Fa=`zt-md-code-block-mod-a-select`,Ia=e=>e.key.toLowerCase()!==Pa||e.defaultPrevented||e.altKey||e.shiftKey||!e.ctrlKey&&!e.metaKey,La=e=>{for(let t=e.depth;t>=0;--t){let n=e.node(t);if(!Na.has(n.type.name))continue;let r=t===0?0:e.before(t);return{codeBlockStart:r+1,codeBlockEnd:r+n.nodeSize-1}}return null},Ra=(e,t)=>{let n=e.state.selection.$from,r=La(n);if(!r)return!1;let i=e.state.tr.setSelection(v.TextSelection.create(e.state.doc,r.codeBlockStart,r.codeBlockEnd));return t.preventDefault(),e.dispatch(i),!0},za=(0,I.$prose)(()=>new v.Plugin({key:new v.PluginKey(Fa),props:{handleKeyDown:(e,t)=>Ia(t)?!1:Ra(e,t)}})),Ba=`frontmatter`,Va=[`yaml`,`toml`],Ha=e=>e===`toml`?`toml`:`yaml`,Ua=[(0,I.$remark)(`remarkFrontmatter`,()=>de.default,[...Va]),(0,I.$nodeSchema)(Ba,()=>({content:`text*`,group:`block`,marks:``,code:!0,defining:!0,isolating:!0,attrs:{format:{default:`yaml`,validate:`string`}},parseDOM:[{tag:`pre[data-type="${Ba}"]`,preserveWhitespace:`full`,getAttrs:e=>({format:Ha(e.dataset.format)})}],toDOM:e=>[`pre`,{"data-type":Ba,"data-format":Ha(e.attrs.format)},[`code`,0]],parseMarkdown:{match:e=>e.type===`yaml`||e.type===`toml`,runner:(e,t,n)=>{let r=Ha(t.type),i=typeof t.value==`string`?t.value:``;e.openNode(n,{format:r}),i&&e.addText(i),e.closeNode()}},toMarkdown:{match:e=>e.type.name===Ba,runner:(e,t)=>{let n=Ha(t.attrs.format);e.addNode(n,void 0,t.textContent)}}}))].flat(),Wa=1200,Ga={yaml:`frontmatterYamlLabel`,toml:`frontmatterTomlLabel`},Ka=q(`ChevronDown`,{size:14,strokeWidth:2}),qa=q(`Copy`,{size:14,strokeWidth:2}),Ja=q(`Check`,{size:14,strokeWidth:2}),Ya=q(`Trash2`,{size:14,strokeWidth:2}),Xa=e=>typeof e==`function`?e():null,Za=e=>typeof e.props.editable==`function`?e.props.editable(e.state):e.editable,Qa=class{constructor(e,t,n,r){this.isCollapsed=!1,this.copyFeedbackTimer=null,this.handleToggleClick=e=>{e.preventDefault(),e.stopPropagation(),this.isCollapsed=!this.isCollapsed,this.syncCollapsedState(),this.syncLocalizedLabels()},this.handleCopyClick=e=>{e.preventDefault(),e.stopPropagation();let t=this.node.textContent;(typeof navigator<`u`&&navigator.clipboard?.writeText?navigator.clipboard.writeText(t):Promise.resolve()).then(()=>{this.copyButton.innerHTML=Ja,this.copyButton.dataset.copied=`true`,this.copyFeedbackTimer!==null&&clearTimeout(this.copyFeedbackTimer),this.copyFeedbackTimer=setTimeout(()=>{this.copyButton.innerHTML=qa,delete this.copyButton.dataset.copied,this.copyFeedbackTimer=null},Wa)}).catch(()=>{})},this.handleDeleteClick=e=>{if(e.preventDefault(),e.stopPropagation(),!Za(this.view))return;let t=Xa(this.getPos);if(t===null)return;let n=t+this.node.nodeSize,r=t===0&&n===this.view.state.doc.content.size,i=this.view.state.schema.nodes.paragraph,a=r?i?.createAndFill():null;if(a){let e=this.view.state.tr.replaceWith(t,n,a);e.setSelection(v.TextSelection.near(e.doc.resolve(t+1),1)).scrollIntoView(),this.view.dispatch(e),this.view.focus();return}let o=this.view.state.tr.delete(t,n),s=Math.min(t,o.doc.content.size);o.setSelection(v.TextSelection.near(o.doc.resolve(s),1)).scrollIntoView(),this.view.dispatch(o),this.view.focus()},this.node=e,this.view=t,this.getPos=n,this.messages=r,this.dom=document.createElement(`div`),this.dom.className=`zt-md-frontmatter`,this.dom.dataset.type=Ba,this.headerContainer=document.createElement(`div`),this.headerContainer.className=`zt-md-frontmatter-header`,this.headerContainer.contentEditable=`false`,this.toggleButton=document.createElement(`button`),this.toggleButton.type=`button`,this.toggleButton.className=`zt-md-frontmatter-toggle`,this.chevronIcon=document.createElement(`span`),this.chevronIcon.className=`zt-md-frontmatter-chevron`,this.chevronIcon.innerHTML=Ka,this.titleSpan=document.createElement(`span`),this.titleSpan.className=`zt-md-frontmatter-title`,this.toggleButton.append(this.chevronIcon,this.titleSpan),this.actionsContainer=document.createElement(`span`),this.actionsContainer.className=`zt-md-frontmatter-actions`,this.copyButton=document.createElement(`button`),this.copyButton.type=`button`,this.copyButton.className=`zt-md-frontmatter-action-button`,this.copyButton.innerHTML=qa,this.deleteButton=document.createElement(`button`),this.deleteButton.type=`button`,this.deleteButton.className=`zt-md-frontmatter-action-button zt-md-frontmatter-editable-action zt-md-frontmatter-action-button-danger`,this.deleteButton.innerHTML=Ya,this.actionsContainer.append(this.copyButton,this.deleteButton),this.headerContainer.append(this.toggleButton,this.actionsContainer),this.contentDOM=document.createElement(`pre`),this.contentDOM.className=`zt-md-frontmatter-body`,this.dom.append(this.headerContainer,this.contentDOM),this.syncFormatState(e),this.syncEditableState(),this.syncCollapsedState(),this.syncLocalizedLabels(),this.toggleButton.addEventListener(`click`,this.handleToggleClick),this.copyButton.addEventListener(`click`,this.handleCopyClick),this.deleteButton.addEventListener(`click`,this.handleDeleteClick),this.stopObservingMessages=W(r,()=>{this.syncLocalizedLabels()})}syncFormatState(e){let t=Ha(e.attrs.format);this.dom.dataset.format=t,this.titleSpan.textContent=this.messages[Ga[t]]}syncEditableState(){this.dom.dataset.editable=Za(this.view)?`true`:`false`}syncCollapsedState(){this.dom.dataset.collapsed=this.isCollapsed?`true`:`false`,this.toggleButton.setAttribute(`aria-expanded`,String(!this.isCollapsed)),this.contentDOM.hidden=this.isCollapsed,this.contentDOM.setAttribute(`aria-hidden`,String(this.isCollapsed))}syncLocalizedLabels(){let e=Ha(this.node.attrs.format);this.titleSpan.textContent=this.messages[Ga[e]];let t=this.isCollapsed?this.messages.frontmatterExpandAriaLabel:this.messages.frontmatterCollapseAriaLabel;this.toggleButton.setAttribute(`aria-label`,t),this.toggleButton.title=t,this.copyButton.setAttribute(`aria-label`,this.messages.frontmatterCopyAriaLabel),this.copyButton.title=this.messages.frontmatterCopyAriaLabel,this.deleteButton.setAttribute(`aria-label`,this.messages.frontmatterDeleteAriaLabel),this.deleteButton.title=this.messages.frontmatterDeleteAriaLabel}update(e){return e.type.name===`frontmatter`?(this.node=e,this.syncFormatState(e),this.syncEditableState(),!0):!1}stopEvent(e){let t=e.target;return t instanceof Node?this.headerContainer.contains(t):!1}ignoreMutation(e){return e.type===`selection`?!1:!!(this.headerContainer.contains(e.target)||e.type===`attributes`&&(e.target===this.dom&&(e.attributeName===`data-collapsed`||e.attributeName===`data-editable`||e.attributeName===`data-format`)||e.target===this.contentDOM&&(e.attributeName===`hidden`||e.attributeName===`aria-hidden`)))}destroy(){this.stopObservingMessages(),this.toggleButton.removeEventListener(`click`,this.handleToggleClick),this.copyButton.removeEventListener(`click`,this.handleCopyClick),this.deleteButton.removeEventListener(`click`,this.handleDeleteClick),this.copyFeedbackTimer!==null&&(clearTimeout(this.copyFeedbackTimer),this.copyFeedbackTimer=null)}},$a=(e=U())=>(t,n,r)=>new Qa(t,n,typeof r==`function`?()=>{let e=r();return typeof e==`number`?e:0}:!1,e),eo=(e,t)=>e(t.state,t.dispatch,t),to=(e,t)=>{let n=e?.state?.selection?.$from;if(!n||!e?.dispatch)return!1;for(let r=n.depth;r>0;--r){let i=n.node(r);if(i?.type?.name!==`list_item`)continue;if(!i.type?.spec?.attrs?.checked)return!1;let a=n.before(r);return e.dispatch(e.state.tr.setNodeMarkup(a,void 0,{...i.attrs,checked:t})),!0}return!1},no={heading1:1,heading2:2,heading3:3,heading4:4,heading5:5,heading6:6},ro={bulletList:`bullet_list`,orderedList:`ordered_list`},io=[`codeBlock`,`heading1`,`heading2`,`heading3`,`heading4`,`heading5`,`heading6`,`taskList`,`orderedList`,`bulletList`,`blockquote`,`paragraph`],ao=(e,t)=>{if(!e?.state||!e?.dispatch)return!1;let n=e.state.schema.nodes;if(t===`paragraph`){let t=n.paragraph;return t?eo((0,z.setBlockType)(t),e):!1}if(t in no){let r=n.heading,i=no[t];return!r||typeof i!=`number`?!1:eo((0,z.setBlockType)(r,{level:i}),e)}if(t===`blockquote`){let t=n.blockquote;return t?eo((0,z.wrapIn)(t),e):!1}if(t===`taskList`){let t=n.bullet_list;return!t||!eo((0,pe.wrapInList)(t),e)?!1:to(e,!1)}if(t===`codeBlock`){let t=n.code_block;return t?eo((0,z.setBlockType)(t,{language:`text`}),e):!1}if(t in ro){let r=n[ro[t]];return r?eo((0,pe.wrapInList)(r),e):!1}return!1},oo=e=>{let t=e.state.selection.$from,n=new Set;for(let e=t.depth;e>0;--e){let r=t.node(e),i=r.type.name;if(i===`code_block`){n.add(`codeBlock`);continue}if(i===`blockquote`){n.add(`blockquote`);continue}if(i===`heading`){let e={1:`heading1`,2:`heading2`,3:`heading3`,4:`heading4`,5:`heading5`,6:`heading6`}[Number(r.attrs?.level??0)];e&&n.add(e);continue}if(i===`list_item`){typeof r.attrs?.checked==`boolean`&&n.add(`taskList`);continue}if(i===`ordered_list`){n.add(`orderedList`);continue}if(i===`bullet_list`){n.add(`bulletList`);continue}i===`paragraph`&&n.add(`paragraph`)}return n.has(`taskList`)&&n.delete(`bulletList`),n.size===0&&n.add(`paragraph`),n},so=e=>{let t=oo(e);return io.find(e=>t.has(e))||`paragraph`},co=/Mac|iPhone|iPad|iPod/,lo={paragraph:{key:`p`,code:`KeyP`,modeOverrides:{modAlt:{key:`0`,code:`Digit0`}}},heading1:{key:`1`,code:`Digit1`},heading2:{key:`2`,code:`Digit2`},heading3:{key:`3`,code:`Digit3`},heading4:{key:`4`,code:`Digit4`},heading5:{key:`5`,code:`Digit5`},heading6:{key:`6`,code:`Digit6`},bulletList:{key:`u`,code:`KeyU`},orderedList:{key:`o`,code:`KeyO`},taskList:{key:`9`,code:`Digit9`},blockquote:{key:`q`,code:`KeyQ`},inlineCode:{key:`e`,code:`KeyE`},codeBlock:{key:`c`,code:`KeyC`},table:{key:`t`,code:`KeyT`},inlineMath:{key:`f`,code:`KeyF`},mathBlock:{key:`b`,code:`KeyB`},image:{key:`i`,code:`KeyI`}},uo=e=>Object.fromEntries(Object.entries(lo).map(([t,n])=>[t,n.modeOverrides?.[e]??n])),fo={Mod:`Ctrl`,Alt:`Alt`,Shift:`Shift`},po={Mod:`⌘`,Alt:`⌥`,Shift:`⇧`},mo=()=>typeof navigator<`u`&&co.test(navigator.platform),ho=e=>{let t=e===`modAlt`?`Mod-Alt`:`Mod-Shift`,n=uo(e);return Object.fromEntries(Object.entries(n).map(([e,n])=>[e,`${t}-${n.key}`]))},go=e=>{let t=mo(),n=t?po:fo;return e.split(`-`).map(e=>n[e]??e.toUpperCase()).join(t?``:`+`)},_o=e=>{let t=ho(e);return Object.fromEntries(Object.entries(t).map(([e,t])=>[e,go(t)]))},vo=e=>{let t=_o(e);return{paragraph:t.paragraph,heading1:t.heading1,heading2:t.heading2,heading3:t.heading3,heading4:t.heading4,heading5:t.heading5,heading6:t.heading6,bulletList:t.bulletList,orderedList:t.orderedList,taskList:t.taskList,blockquote:t.blockquote,codeBlock:t.codeBlock}},yo=(e,t)=>{let n=ho(t);e.update(C.paragraphKeymap.key,e=>({...e,TurnIntoText:{...e.TurnIntoText,shortcuts:n.paragraph}})),e.update(C.headingKeymap.key,e=>({...e,TurnIntoH1:{...e.TurnIntoH1,shortcuts:n.heading1},TurnIntoH2:{...e.TurnIntoH2,shortcuts:n.heading2},TurnIntoH3:{...e.TurnIntoH3,shortcuts:n.heading3},TurnIntoH4:{...e.TurnIntoH4,shortcuts:n.heading4},TurnIntoH5:{...e.TurnIntoH5,shortcuts:n.heading5},TurnIntoH6:{...e.TurnIntoH6,shortcuts:n.heading6}})),e.update(C.bulletListKeymap.key,e=>({...e,WrapInBulletList:{...e.WrapInBulletList,shortcuts:n.bulletList}})),e.update(C.orderedListKeymap.key,e=>({...e,WrapInOrderedList:{...e.WrapInOrderedList,shortcuts:n.orderedList}})),e.update(C.blockquoteKeymap.key,e=>({...e,WrapInBlockquote:{...e.WrapInBlockquote,shortcuts:n.blockquote}})),e.update(C.codeBlockKeymap.key,e=>({...e,CreateCodeBlock:{...e.CreateCodeBlock,shortcuts:n.codeBlock}})),e.update(C.inlineCodeKeymap.key,e=>({...e,ToggleInlineCode:{...e.ToggleInlineCode,shortcuts:n.inlineCode}}))},bo=e=>{let t=ho(e).taskList;return(0,I.$useKeymap)(`taskListTransform`,{WrapInTaskList:{shortcuts:t,command:()=>(e,t,n)=>n?ao(n,`taskList`):!1}})},xo=`zt-md-selection-tooltip`,So=e=>[{command:`strong`,iconName:`Bold`,title:e.selectionTooltipStrongTitle,markNames:[`strong`]},{command:`em`,iconName:`Italic`,title:e.selectionTooltipEmTitle,markNames:[`em`,`emphasis`]},{command:`strike`,iconName:`Strikethrough`,title:e.selectionTooltipStrikeTitle,markNames:[`strike_through`,`strikeThrough`]},{command:`inlineCode`,iconName:`Code2`,title:e.selectionTooltipInlineCodeTitle,markNames:[`inlineCode`,`code_inline`]},{command:`link`,iconName:`Code2`,title:e.selectionTooltipLinkTitle,markNames:[`link`]}],X={paragraph:f.Type,heading1:f.Heading1,heading2:f.Heading2,heading3:f.Heading3,heading4:f.Heading4,heading5:f.Heading5,heading6:f.Heading6,bulletList:f.List,orderedList:f.ListOrdered,taskList:f.ListChecks,blockquote:f.TextQuote,codeBlock:f.Code2},Co=(e,t)=>{let n=vo(t);return[{command:`paragraph`,icon:X.paragraph,label:e.selectionTooltipTransformParagraphLabel,shortcut:n.paragraph},{command:`heading1`,icon:X.heading1,label:e.selectionTooltipTransformHeading1Label,shortcut:n.heading1},{command:`heading2`,icon:X.heading2,label:e.selectionTooltipTransformHeading2Label,shortcut:n.heading2},{command:`heading3`,icon:X.heading3,label:e.selectionTooltipTransformHeading3Label,shortcut:n.heading3},{command:`heading4`,icon:X.heading4,label:e.selectionTooltipTransformHeading4Label,shortcut:n.heading4},{command:`heading5`,icon:X.heading5,label:e.selectionTooltipTransformHeading5Label,shortcut:n.heading5},{command:`heading6`,icon:X.heading6,label:e.selectionTooltipTransformHeading6Label,shortcut:n.heading6},{command:`bulletList`,icon:X.bulletList,label:e.selectionTooltipTransformBulletListLabel,shortcut:n.bulletList},{command:`orderedList`,icon:X.orderedList,label:e.selectionTooltipTransformOrderedListLabel,shortcut:n.orderedList},{command:`taskList`,icon:X.taskList,label:e.selectionTooltipTransformTaskListLabel,shortcut:n.taskList},{command:`blockquote`,icon:X.blockquote,label:e.selectionTooltipTransformBlockquoteLabel,shortcut:n.blockquote},{command:`codeBlock`,icon:X.codeBlock,label:e.selectionTooltipTransformCodeBlockLabel,shortcut:n.codeBlock}]},wo=e=>typeof e.props.editable==`function`?e.props.editable(e.state):e.editable,Z=(e,t)=>{let n=e.state.schema.marks,r=t.find(e=>n[e]);return r?n[r]??null:null},To=(e,t)=>{let{from:n,to:r}=e.selection;return e.doc.rangeHasMark(n,r,t)},Eo=(e,t)=>{let{from:n,to:r}=e.selection,i=``;return e.doc.nodesBetween(n,r,e=>{let n=e.marks.find(e=>e.type===t);return n?(i=typeof n.attrs.href==`string`?n.attrs.href:``,!1):!0}),i},Do=e=>{(0,z.toggleMark)(e.markType)(e.view.state,e.view.dispatch,e.view),e.view.focus()},Oo=e=>{e.toggleLinkPopover(e.view)},ko=(e,t)=>{({strong:Do,em:Do,strike:Do,inlineCode:Do,link:Oo})[e](t)},Ao=(e,t,n,r)=>{let i=document.createElement(`button`);i.type=`button`,i.className=`zt-md-selection-tooltip-button`,i.dataset.command=e.command,i.title=e.title,i.setAttribute(`aria-label`,e.title);let a=document.createElement(`span`);return a.className=`zt-md-selection-tooltip-button-icon`,a.innerHTML=q(e.iconName,{size:14,strokeWidth:2}),i.append(a),i.addEventListener(`mousedown`,e=>{e.preventDefault()}),i.addEventListener(`click`,i=>{i.preventDefault();let a=n();!a||a.state.selection.empty||ko(e.command,{view:a,markType:t,toggleLinkPopover:r})}),i},jo=(e,t,n,r,i)=>{let a=document.createElement(`div`);return a.className=`zt-md-selection-tooltip`,a.append(i),t.forEach(t=>{let i=Z(e,t.markNames);i&&t.command!==`link`&&a.append(Ao(t,i,n,r))}),a},Mo=e=>{let t=ga({open:e.open,portalContainer:e.portalContainer,editorWrapper:e.collisionBoundary,offsetY:8,fallbackWidth:224,fallbackHeight:360,onOutside:()=>e.onOpenChange(!1)}),n=e=>{e.preventDefault()},r=t=>{let n=e.getCurrentView();if(!n||n.state.selection.empty){e.onOpenChange(!1);return}ao(n,t),e.onOpenChange(!1),n.focus()};return(0,c.createElement)(c.Fragment,null,(0,c.createElement)(`button`,{ref:t.triggerRef,type:`button`,className:`zt-md-selection-transform-trigger`,"aria-label":e.menuTitle,"aria-expanded":e.open,title:e.menuTitle,onMouseDown:n,onClick:()=>{if(e.open){e.onOpenChange(!1);return}t.updatePosition(),e.onOpenChange(!0)}},(0,c.createElement)(`span`,{className:`zt-md-selection-transform-trigger-label`},e.activeLabel),(0,c.createElement)(f.ChevronDown,{size:e.iconSize,strokeWidth:e.iconStrokeWidth,"aria-hidden":`true`})),(0,c.createElement)(_a,{panel:t,portalContainer:e.portalContainer,className:`zt-md-selection-transform-popover !w-[224px] p-1`,onMouseDown:n},(0,c.createElement)(`p`,{className:`zt-md-selection-transform-popover-title`},e.menuTitle),(0,c.createElement)(`div`,{className:`zt-md-selection-transform-popover-list`},...e.items.map(t=>{let i=e.activeCommands.has(t.command);return(0,c.createElement)(`button`,{key:t.command,type:`button`,className:`zt-md-selection-transform-item`,"data-active":i?`true`:`false`,onMouseDown:n,onClick:()=>r(t.command)},(0,c.createElement)(t.icon,{size:e.iconSize,strokeWidth:e.iconStrokeWidth,className:`zt-md-selection-transform-item-icon`,"aria-hidden":`true`}),(0,c.createElement)(`span`,{className:`zt-md-selection-transform-item-label`},t.label),(0,c.createElement)(`kbd`,{className:`zt-md-selection-transform-item-shortcut`},t.shortcut))}))))},No=e=>{let[t,n]=(0,c.useState)(``),r=(0,c.useRef)(null),i=e=>{e.preventDefault()},a=t=>{let n=e.getCurrentView();if(!n||n.state.selection.empty){e.onOpenChange(!1);return}let r=Z(n,[`link`]);if(!r){e.onOpenChange(!1);return}let i=Ht(t),{from:a,to:o}=n.state.selection,s=n.state.tr.removeMark(a,o,r);i&&s.addMark(a,o,r.create({href:i})),n.dispatch(s.scrollIntoView()),e.onOpenChange(!1),n.focus()},o=t=>{if(!t){e.onOpenChange(!1);return}let r=e.getCurrentView(),i=r?Z(r,[`link`]):null;if(!r||!i||r.state.selection.empty){e.onOpenChange(!1);return}n(Ht(Eo(r.state,i))),e.onOpenChange(!0)},s=ga({open:e.open,portalContainer:e.portalContainer,editorWrapper:e.collisionBoundary,horizontalAlign:`center`,offsetY:8,fallbackWidth:266,fallbackHeight:48,onOutside:()=>o(!1)});return(0,c.useEffect)(()=>{if(!e.open)return;let t=e.getCurrentView(),n=t?Z(t,[`link`]):null;(!t||!n||t.state.selection.empty)&&e.onOpenChange(!1)},[e.open,e.getCurrentView,e.onOpenChange]),(0,c.useEffect)(()=>{e.open&&r.current?.focus()},[e.open]),(0,c.createElement)(c.Fragment,null,(0,c.createElement)(`button`,{ref:t=>{s.triggerRef.current=t,e.triggerRef(t)},type:`button`,className:`zt-md-selection-tooltip-button`,"data-command":`link`,title:e.messages.selectionTooltipLinkTitle,"aria-label":e.messages.selectionTooltipLinkTitle,"aria-expanded":e.open,onMouseDown:i,onClick:()=>{if(e.open){o(!1);return}s.updatePosition(),o(!0)}},(0,c.createElement)(`span`,{className:`zt-md-selection-tooltip-button-icon`},(0,c.createElement)(f.Link2,{size:e.iconSize,strokeWidth:e.iconStrokeWidth}))),(0,c.createElement)(_a,{panel:s,portalContainer:e.portalContainer,className:`zt-md-selection-link-popover w-fit min-w-0 gap-0 p-2`},(0,c.createElement)(`div`,{className:`zt-md-selection-link-popover-row`},(0,c.createElement)(`input`,{ref:r,type:`text`,value:t,placeholder:e.messages.selectionLinkInputPlaceholder,className:`zt-md-selection-link-popover-input`,onChange:e=>n(e.currentTarget.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),a(t.trim()))}}),(0,c.createElement)(`button`,{type:`button`,className:`zt-md-selection-link-popover-action`,onMouseDown:i,onClick:()=>a(t.trim()),"aria-label":e.messages.selectionLinkSaveAriaLabel},(0,c.createElement)(f.Check,{size:e.iconSize,strokeWidth:e.iconStrokeWidth})),(0,c.createElement)(`button`,{type:`button`,className:`zt-md-selection-link-popover-action zt-md-selection-link-popover-action-danger`,onMouseDown:i,onClick:()=>a(``),"aria-label":e.messages.selectionLinkRemoveAriaLabel},(0,c.createElement)(f.Trash2,{size:e.iconSize,strokeWidth:e.iconStrokeWidth})))))},Po=(e,t,n)=>{n.forEach(n=>{let r=Z(t,n.markNames);if(!r)return;let i=e.querySelector(`[data-command="${n.command}"]`);i instanceof HTMLButtonElement&&(i.dataset.active=To(t.state,r)?`true`:`false`)})},Fo=e=>{let{from:t,to:n}=e.state.selection,r=!1;return e.state.doc.nodesBetween(t,n,e=>e.type.name===`code_block`?(r=!0,!1):!0),r},Io=(e,t,n)=>r=>{let{selection:i,doc:a}=r.state,o=e.contains(document.activeElement);return!wo(r)||i.empty||!(i instanceof v.TextSelection)||!r.hasFocus()&&!o&&!t()&&!n()||Fo(r)?!1:e.childElementCount>0&&a.textBetween(i.from,i.to).trim().length>0},Lo=e=>{let{$from:t}=e.state.selection;for(let e=t.depth;e>0;--e){let n=t.node(e).type.name;if(n===`table`||n===`table_cell`||n===`table_header`)return!0}return!1},Ro=(e,t,n,r)=>{let i=So(n),a=Co(n,r),o=e,s=!1,l=!1,u=!1,d=0,f=``,p=document.createElement(`span`),m=(0,oe.createRoot)(p),h=document.createElement(`span`),g=null,_=(0,oe.createRoot)(h),v=t.closest(`.zt-md-editor`),y=e=>{s!==e&&(s=e,C())},b=e=>{l!==e&&(l=e,S())},x=e=>{e.state.selection.empty||y(!s)},S=()=>{let e=o?oo(o):new Set([`paragraph`]),r=o?so(o):`paragraph`,i=`${d}:${r}:${l}:${Array.from(e).sort().join(`,`)}`;if(f===i)return;f=i;let s=a.find(e=>e.command===r)??a[0];m.render((0,c.createElement)(Mo,{getCurrentView:()=>o,portalContainer:t,collisionBoundary:v,iconSize:14,iconStrokeWidth:2,menuTitle:n.selectionTooltipTransformLabel,items:a,activeLabel:s?.label??n.selectionTooltipTransformParagraphLabel,open:l,onOpenChange:b,activeCommands:e}))},C=()=>{_.render((0,c.createElement)(No,{getCurrentView:()=>o,portalContainer:t,collisionBoundary:v,iconSize:14,iconStrokeWidth:2,triggerRef:e=>{g=e},open:s,onOpenChange:y,messages:n}))},w=jo(e,i,()=>o,x,p);S(),Z(e,[`link`])&&(w.append(h),C());let T=Io(w,()=>s,()=>l),E=new fe.TooltipProvider({content:w,debounce:80,offset:8,root:t,shouldShow:T,floatingUIOptions:{placement:`top`}}),D=()=>{w.parentElement||t.appendChild(w)},O=()=>{w.remove()};E.onHide=O;let k=()=>{y(!1),b(!1),E.hide(),O()},A=e=>e instanceof Node?!!o?.dom.contains(e)||w.contains(e)||t.contains(e):!1,j=()=>{requestAnimationFrame(()=>{u||A(document.activeElement)||k()})},M=e=>{A(e.target)||k()};e.dom.addEventListener(`blur`,j),document.addEventListener(`mousedown`,M,!0);let N=W(n,()=>{d+=1,i=So(n),a=Co(n,r),i.forEach(e=>{let t=w.querySelector(`[data-command="${e.command}"]`);t&&(t.title=e.title,t.setAttribute(`aria-label`,e.title))}),S(),Z(e,[`link`])&&C()});return{update:(e,t)=>{if(o=e,o.composing){w.parentElement&&k();return}if(o.state.selection.empty&&(y(!1),b(!1)),!T(o)){E.hide(),O();return}let n=Lo(o);if(p.hidden=n,n?b(!1):S(),Po(w,o,i),g){let e=Z(o,[`link`]);g.dataset.active=e&&To(o.state,e)?`true`:`false`}D(),E.update(o,t)},destroy:()=>{N(),u=!0,o=null,e.dom.removeEventListener(`blur`,j),document.removeEventListener(`mousedown`,M,!0),m.unmount(),_.unmount(),E.destroy(),w.remove()}}},zo=(e,t,n)=>(0,I.$prose)(()=>new v.Plugin({key:new v.PluginKey(xo),view:r=>Ro(r,e,t,n)})),Bo=(e,t)=>e(t.state,t.dispatch,t),Vo=e=>{let t=e?.state?.selection?.$from;if(!t)return!1;for(let e=t.depth;e>0;--e)if(t.node(e)?.type?.name===`table`)return!0;return!1},Ho=(e,t)=>{let n=e?.state?.doc;if(!n||typeof t!=`number`)return-1;let r=Math.min(Math.max(t,0),n.content.size),i=n.resolve(r);for(let e=i.depth;e>0;--e)if(i.node(e)?.type?.name===`table`)return i.before(e);return-1},Uo=(e,t,n,r)=>{let i=e?.state?.schema?.nodes;if(!i)return null;let a=i.table,o=i.table_header_row,s=i.table_row,c=i.table_header,l=i.table_cell;if(!a||!o||!s||!c||!l)return null;let u=Math.max(1,t),d=Math.max(1,n),f=Array.from({length:u},(e,t)=>{let n=r&&t===0,i=n?o:s,a=n?c:l,u=Array.from({length:d},()=>a.createAndFill()).filter(Boolean);return i.create(null,u)});return a.create(null,f)},Wo=e=>{if(!e?.state||!e?.dispatch||Vo(e))return!1;let t=e.state.selection.from,n=Uo(e,3,3,!0);if(!n)return!1;e.dispatch(e.state.tr.replaceSelectionWith(n).scrollIntoView());let r=Ho(e,t);if(r<0&&t>0&&(r=Ho(e,t-1)),r<0)return!0;let i=r+2;if(i>e.state.doc.content.size)return!0;let a=v.TextSelection.near(e.state.doc.resolve(i),1);return e.dispatch(e.state.tr.setSelection(a).scrollIntoView()),e.focus(),!0},Go=(e,t)=>{let n=e?.state?.schema?.marks??{},r=t.find(e=>n[e]);return r?n[r]??null:null},Ko=new Set([`paragraph`,`heading1`,`heading2`,`heading3`,`heading4`,`heading5`,`heading6`,`bulletList`,`orderedList`,`taskList`,`blockquote`,`codeBlock`]),qo=e=>Ko.has(e),Jo={inlineCode:e=>{let t=Go(e,[`inlineCode`,`code_inline`]);return t?Bo((0,z.toggleMark)(t),e):!1},inlineMath:e=>{let t=e?.state?.schema?.nodes?.math_inline;if(!t||!e?.dispatch)return!1;let n=e.state.selection.from,r=t.create({value:``});return e.dispatch(e.state.tr.replaceSelectionWith(r).setMeta(J,{type:`open`,position:n}).scrollIntoView()),!0},mathBlock:e=>{let t=e.state.schema.nodes?.math_block;if(!t||!Bo((0,z.setBlockType)(t),e))return!1;let n=e.state.selection?.$from;if(!n)return!0;let r=null;for(let e=n.depth;e>0;--e)if(n.node(e)?.type?.name===`math_block`){r=n.before(e);break}if(r===null)return!0;let i=v.NodeSelection.create(e.state.doc,r);return e.dispatch(e.state.tr.setSelection(i).scrollIntoView()),!0},table:Wo},Yo=(e,t)=>!e?.state||!e?.dispatch?!1:qo(t)?ao(e,t):t===`image`?!1:Jo[t](e),Xo=e=>typeof e?.props?.editable==`function`?e.props.editable(e.state):!!e?.editable,Zo=[{id:`paragraph`,label:`普通文本`,group:`标题`,icon:`Type`,command:`paragraph`},{id:`heading-1`,label:`标题 1`,group:`标题`,icon:`Heading1`,command:`heading1`},{id:`heading-2`,label:`标题 2`,group:`标题`,icon:`Heading2`,command:`heading2`},{id:`heading-3`,label:`标题 3`,group:`标题`,icon:`Heading3`,command:`heading3`},{id:`heading-4`,label:`标题 4`,group:`标题`,icon:`Heading4`,command:`heading4`},{id:`heading-5`,label:`标题 5`,group:`标题`,icon:`Heading5`,command:`heading5`},{id:`heading-6`,label:`标题 6`,group:`标题`,icon:`Heading6`,command:`heading6`},{id:`bullet-list`,label:`无序列表`,group:`列表`,icon:`List`,command:`bulletList`},{id:`ordered-list`,label:`有序列表`,group:`列表`,icon:`ListOrdered`,command:`orderedList`},{id:`task-list`,label:`任务列表`,group:`列表`,icon:`ListTodo`,command:`taskList`},{id:`blockquote`,label:`引用块`,group:`插入`,icon:`TextQuote`,command:`blockquote`},{id:`inline-code`,label:`行内代码`,group:`插入`,icon:`Code`,command:`inlineCode`},{id:`code-block`,label:`代码块`,group:`插入`,icon:`SquareCode`,command:`codeBlock`},{id:`table`,label:`表格`,group:`插入`,icon:`Table`,command:`table`},{id:`inline-math`,label:`行内公式`,group:`公式`,icon:`Sigma`,command:`inlineMath`},{id:`math-block`,label:`公式块`,group:`公式`,icon:`SquareFunction`,command:`mathBlock`},{id:`image`,label:`图片`,group:`媒体`,icon:`Image`,command:`image`}],Qo=[{id:`paragraph`,label:`Paragraph`,group:`Headings`,icon:`Type`,command:`paragraph`},{id:`heading-1`,label:`Heading 1`,group:`Headings`,icon:`Heading1`,command:`heading1`},{id:`heading-2`,label:`Heading 2`,group:`Headings`,icon:`Heading2`,command:`heading2`},{id:`heading-3`,label:`Heading 3`,group:`Headings`,icon:`Heading3`,command:`heading3`},{id:`heading-4`,label:`Heading 4`,group:`Headings`,icon:`Heading4`,command:`heading4`},{id:`heading-5`,label:`Heading 5`,group:`Headings`,icon:`Heading5`,command:`heading5`},{id:`heading-6`,label:`Heading 6`,group:`Headings`,icon:`Heading6`,command:`heading6`},{id:`bullet-list`,label:`Bullet list`,group:`Lists`,icon:`List`,command:`bulletList`},{id:`ordered-list`,label:`Ordered list`,group:`Lists`,icon:`ListOrdered`,command:`orderedList`},{id:`task-list`,label:`Task list`,group:`Lists`,icon:`ListTodo`,command:`taskList`},{id:`blockquote`,label:`Blockquote`,group:`Insert`,icon:`TextQuote`,command:`blockquote`},{id:`inline-code`,label:`Inline code`,group:`Insert`,icon:`Code`,command:`inlineCode`},{id:`code-block`,label:`Code block`,group:`Insert`,icon:`SquareCode`,command:`codeBlock`},{id:`table`,label:`Table`,group:`Insert`,icon:`Table`,command:`table`},{id:`inline-math`,label:`Inline math`,group:`Math`,icon:`Sigma`,command:`inlineMath`},{id:`math-block`,label:`Math block`,group:`Math`,icon:`SquareFunction`,command:`mathBlock`},{id:`image`,label:`Image`,group:`Media`,icon:`Image`,command:`image`}],$o=(e,t=`zh-CN`)=>e?.items&&e.items.length>0?e.items:t===`en-US`?Qo:Zo,es=e=>{let t=e?.state?.selection?.$from;if(!t)return!1;let n=String(t.parent?.type?.name??``);if(n.includes(`code`)||n===`math_block`)return!0;for(let e=t.depth;e>0;--e){let n=String(t.node(e)?.type?.name??``);if(n===`table`||n===`table_cell`||n===`table_header`)return!0}return!1},ts=e=>{let t=e?.state,n=t?.selection?.$from;if(!t||!n)return``;let r=n.start(),i=n.pos;return t.doc.textBetween(r,i,`
|
|
18
18
|
`,`
|
|
19
|
-
`)},
|
|
19
|
+
`)},ns=e=>{let t=ts(e),n=t.lastIndexOf(`/`);if(n<0)return null;let r=t.slice(n+1);return/\s/.test(r)?null:r},rs=(e,t)=>{if(t===null||t.length===0)return e;let n=t.toLowerCase();return e.filter(e=>[e.label,e.group,e.command,e.id].some(e=>String(e).toLowerCase().startsWith(n)))},is=(e,t)=>{if(!Xo(e))return{visibleItems:[],shouldShow:!1};let n=ns(e),r=rs(t,n);return{visibleItems:r,shouldShow:!es(e)&&n!==null&&r.length>0}},as=e=>{let t=e?.state,n=t?.selection?.$from;if(!t||!n||!e?.dispatch)return!1;let r=n.start(),i=n.pos,a=t.doc.textBetween(r,i,`
|
|
20
20
|
`,`
|
|
21
|
-
`).lastIndexOf(`/`);if(a<0)return!1;let o=r+a,s=t.tr.delete(o,i);return e.dispatch(s.scrollIntoView()),!0},Fo=(e,t)=>{let n=t?`true`:`false`;e.dataset.selected=n,e.setAttribute(`aria-selected`,n)},Io=(e,t,n,r)=>{e.innerHTML=``;let i=[],a=``;return t.forEach((t,o)=>{if(t.group!==a){let n=document.createElement(`div`);n.className=`slash-menu-group`,n.textContent=t.group,e.appendChild(n),a=t.group}let s=document.createElement(`div`);s.className=`slash-menu-item`,s.setAttribute(`role`,`option`),s.dataset.command=t.command,s.dataset.index=String(o),Fo(s,o===n);let c=document.createElement(`span`);c.className=`slash-menu-item-icon`,t.icon&&(c.innerHTML=K(mt(t.icon,`Circle`),{size:16,strokeWidth:2}));let l=document.createElement(`span`);l.className=`slash-menu-item-label`,l.textContent=t.label;let u=r[t.command],d=u?document.createElement(`kbd`):null;d&&(d.className=`slash-menu-item-shortcut`,d.textContent=u),s.appendChild(c),s.appendChild(l),d&&s.appendChild(d),e.appendChild(s),i.push(s)}),i},Lo=(e,t)=>{let n=document.createElement(`div`);n.className=`slash-menu`,n.setAttribute(`role`,`listbox`),n.style.display=`none`,e.appendChild(n);let r=!1,i=``,a=-1,o=[],s=!1,c=null,l=Ga(t),u=()=>{if(!r||!c)return;let{editorWrapper:t,anchorTopInContent:i,anchorBottomInContent:a,anchorLeftInContent:o,placement:s,offsetY:l}=c,u=Hi({wrapper:t,anchor:{anchorTopInContent:i,anchorBottomInContent:a,anchorLeftInContent:o},overlaySize:{width:n.offsetWidth||210},placement:s,offsetY:l,boundaryInset:4},e);n.style.left=`${u.left}px`,n.style.top=`${u.top}px`,n.dataset.placement=s},d=Ui(()=>{r&&u()}),f=()=>{n.style.top=``,n.style.left=``,n.style.transform=``,delete n.dataset.placement};return{menu:n,isVisible:()=>r,setVisible:(e,t)=>{if(r!==e){if(r=e,n.style.display=e?`block`:`none`,!e){d.unbindGlobal(),d.bindWrapper(null),f(),i=``,a=-1,o=[],s=!0;return}d.bindGlobal(),t&&(t(),s&&=(t(),!1))}},renderIfNeeded:(e,t)=>{let r=JSON.stringify(e.map(e=>[e.command,e.label,e.group,e.icon]));if(i!==r){o=Io(n,e,t,l),i=r,a=t;return}a!==t&&(a>=0&&o[a]&&Fo(o[a],!1),t>=0&&o[t]&&Fo(o[t],!0),a=t)},scrollActiveItemIntoView:e=>{let t=o[a]??null;t&&(t.scrollIntoView({block:`nearest`,inline:`nearest`}),e&&e())},updatePositionContext:e=>{c=e,d.bindWrapper(e?.editorWrapper??null)},updatePosition:u,destroy:()=>{d.destroy(),o=[],n.remove()}}},Ro=(e,t)=>{if(!(!e||typeof e!=`object`))return e[t]},zo=()=>{if(typeof pe.slashFactory!=`function`)return console.error(`[zt-md/slash] slashFactory not found`),null;let e=(0,pe.slashFactory)(`zt-md-slash`),t=Array.isArray(e)?e[0]:void 0,n=Array.isArray(e)?e[1]:e,r=Array.isArray(e)?e[2]:void 0;if(!n)return null;let i=Array.isArray(e)?e.filter((e,t)=>t<2&&e!=null):[n],a=Ro(t,`key`)??Ro(n,`key`)??Ro(r,`key`)??Ro(e,`key`);return i.length===0||a===void 0?null:{plugins:i,key:a}},Bo=(e,t,n,r,i=`zh-CN`,a=`modShift`)=>{if(t?.enabled===!1)return{plugins:[],config:null};try{let o=zo();if(!o)return{plugins:[],config:null};let s=Oo(t,i),c=Lo(e,a),l=0,u=null,d=s,f=!1,p=new Set([`ArrowDown`,`ArrowUp`,`Enter`,`Escape`]),m=e=>e.isComposing||!p.has(e.key)||!f?!1:e.key===`ArrowDown`?(e.preventDefault(),d.length===0?!0:(l=(l+1)%d.length,c.renderIfNeeded(d,l),c.scrollActiveItemIntoView(()=>{c.updatePosition()}),!0)):e.key===`ArrowUp`?(e.preventDefault(),d.length===0?!0:(l=(l-1+d.length)%d.length,c.renderIfNeeded(d,l),c.scrollActiveItemIntoView(()=>{c.updatePosition()}),!0)):e.key===`Enter`?(e.preventDefault(),_(),!0):e.key===`Escape`?(e.preventDefault(),c.setVisible(!1),!0):!1,h=e=>{let t=e?.state?.selection?.from;if(typeof t!=`number`)return null;let n=e?.coordsAtPos?.(t);return n?new DOMRect(n.left,n.top,Math.max(n.right-n.left,1),n.bottom-n.top):null},g=e=>{if(!To(e)){d=[],f=!1,c.updatePositionContext(null),c.setVisible(!1);return}let t=No(e,s);if(d=t.visibleItems,f=t.shouldShow,t.shouldShow&&l>=d.length&&(l=0),t.shouldShow&&!c.isVisible()&&(l=0),!t.shouldShow){c.updatePositionContext(null),c.setVisible(!1);return}let n=h(e),r=Li(e?.dom);if(n&&r){let e=Ri(n,320),t=zi(n,r);c.updatePositionContext({editorWrapper:r,anchorTopInContent:t.anchorTopInContent,anchorBottomInContent:t.anchorBottomInContent,anchorLeftInContent:t.anchorLeftInContent,placement:e,offsetY:8})}c.renderIfNeeded(d,l),c.isVisible()?c.updatePosition():c.setVisible(!0,()=>{c.updatePosition()})},_=()=>{if(!To(u)){f=!1,c.updatePositionContext(null),c.setVisible(!1);return}if(!u||l<0||l>=d.length)return;let t=d[l];if(Po(u)){if(t.command===`image`){c.setVisible(!1),n&&Vn({portalContainer:e,view:u,messages:n,imageUpload:r});return}wo(u,t.command)&&(c.setVisible(!1),t.command===`mathBlock`&&queueMicrotask(()=>{let e=u?.dom?.querySelector?.(`.zt-md-math-block-editing .zt-md-math-block-textarea`);!e||document.activeElement===e||e.focus()}))}};return c.menu.addEventListener(`mousemove`,e=>{if(!f)return;let t=e.target?.closest(`.slash-menu-item`),n=Number(t?.dataset.index??-1);n>=0&&n<d.length&&n!==l&&(l=n,c.renderIfNeeded(d,l))}),c.menu.addEventListener(`mousedown`,e=>{e.preventDefault();let t=(e.target?.closest(`.slash-menu-item`))?.dataset.command??``;if(!t)return;let n=d.findIndex(e=>e.command===t);n<0||(l=n,_())}),{plugins:o.plugins,config:e=>{e.set(o.key,{props:{handleKeyDown:(e,t)=>m(t)},view:()=>({update:e=>{u=e,!e?.composing&&g(e)},destroy:()=>{u=null,f=!1,c.destroy()}})})},updateLocale:e=>{if(i===e)return;let n=d[l]?.command;if(i=e,s=Oo(t,i),u){let e=No(u,s).visibleItems;l=Math.max(0,e.findIndex(e=>e.command===n)),g(u)}}}}catch(e){return console.error(`[zt-md/slash] init failed`,e),{plugins:[],config:null}}},Vo=/Mac|iPhone|iPad|iPod/,Ho=(e,t)=>(typeof navigator<`u`&&Vo.test(navigator.platform)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey)?t===`modAlt`?e.altKey&&!e.shiftKey:e.shiftKey&&!e.altKey:!1,Uo=(e,t,n,r)=>(Vn({portalContainer:t,view:e,messages:n,imageUpload:r}),!0),Wo=(e,t,n,r)=>{let i=za(n),a=Object.fromEntries(Object.entries(i).map(([e,t])=>[t.code,e]));return(i,o)=>{if(o.isComposing||!Ho(o,n)||!To(i))return!1;let s=a[o.code];if(!s)return!1;let c=s===`image`?Uo(i,e,t,r):wo(i,s);return c&&o.preventDefault(),c}},Go=`table`,Ko=`ArrowUp`,qo=e=>e.key!==Ko||e.defaultPrevented||e.altKey||e.ctrlKey||e.metaKey,Jo=(e,t)=>{let n=t.nodeBefore;return!n||n.type.name!==Go?null:{tableNode:n,tableStart:e-n.nodeSize}},Yo=e=>{if(e.parent.type.name!==`paragraph`||e.parentOffset!==0||e.parent.childCount>0||e.depth<1)return null;let t=e.index(e.depth-1);if(t<=0)return null;let n=e.node(e.depth-1).child(t-1);return n.type.name===Go?{tableNode:n,tableStart:e.before(e.depth)-n.nodeSize}:null},Xo=(e,t)=>{if(e.childCount===0)return null;let n=e.childCount-1,r=e.child(n);if(r.childCount===0)return null;let i=0;for(let t=0;t<n;t+=1)i+=e.child(t).nodeSize;let a=r.childCount-1,o=r.child(a),s=0;for(let e=0;e<a;e+=1)s+=r.child(e).nodeSize;return t+1+i+1+s+o.nodeSize-1},Zo=e=>{let{selection:t}=e.state,n=t.$from,r=null;if(t instanceof R.GapCursor?r=Jo(t.from,n):t.empty&&(r=Yo(n)),!r)return!1;let i=Xo(r.tableNode,r.tableStart);if(i===null)return!1;let a=e.state.tr.setSelection(v.TextSelection.near(e.state.doc.resolve(i),-1)).scrollIntoView();return e.dispatch(a),e.focus(),!0},Qo=(0,L.$prose)(()=>new v.Plugin({key:new v.PluginKey(`zt-md-table-arrow-entry`),props:{handleKeyDown:(e,t)=>qo(t)?!1:Zo(e)}})),$o=`table`,es=`table_header_row`,ts=`table_row`,ns=`table_header`,rs=`table_cell`,Z=e=>{let t=e.selection.$from,n=-1,r=-1;for(let e=t.depth;e>=0;--e){let i=t.node(e);if(r<0&&(i.type.name===rs||i.type.name===ns)&&(r=t.index(e-1)),n<0&&(i.type.name===ts||i.type.name===es)&&(n=t.index(e-1)),i.type.name===$o)return{tableNode:i,tableStart:e===0?0:t.before(e),tableNodeSize:i.nodeSize,rowIndex:n,columnIndex:r}}return null},is=(e,t,n,r)=>{if(n<0||n>=e.childCount)return null;let i=0;for(let t=0;t<n;t+=1)i+=e.child(t).nodeSize;let a=e.child(n);if(r<0||r>=a.childCount)return null;let o=0;for(let e=0;e<r;e+=1)o+=a.child(e).nodeSize;return t+1+i+1+o+1+1},as=e=>{if(e.columnIndex<0||e.tableNode.childCount===0)return!1;let t=e.tableNode.child(0);return e.columnIndex<t.childCount},os=(e,t,n,r)=>{let i=is(t.tableNode,t.tableStart,n,r);if(i===null)return!1;let a=e.state.tr.setSelection(v.TextSelection.near(e.state.tr.doc.resolve(i),1));return e.dispatch(a),!0},ss=(e,t)=>t(e.state,e.dispatch,e)?(e.dispatch(e.state.tr.scrollIntoView()),e.focus(),!0):!1,cs=(e,t,n)=>t.rowIndex<0||t.columnIndex<0||!os(e,t,t.rowIndex,t.columnIndex)?!1:ss(e,n===`above`?me.addRowBefore:me.addRowAfter),ls=(e,t)=>t.rowIndex<=0||t.columnIndex<0||!os(e,t,t.rowIndex,t.columnIndex)?!1:ss(e,me.deleteRow),us=(e,t,n)=>t.rowIndex<0||t.columnIndex<0||!os(e,t,t.rowIndex,t.columnIndex)?!1:ss(e,n===`left`?me.addColumnBefore:me.addColumnAfter),ds=(e,t)=>t.rowIndex<0||t.columnIndex<0||(t.tableNode.childCount>0?t.tableNode.child(0).childCount:0)<=1||!os(e,t,t.rowIndex,t.columnIndex)?!1:ss(e,me.deleteColumn),fs=(e,t,n)=>{if(t.columnIndex<0)return!1;let r=me.TableMap.get(t.tableNode),i=t.tableStart+1,a=t.columnIndex,o=e.state.tr;for(let e=0;e<r.height;e+=1){let t=e*r.width+a,s=r.map[t];if(typeof s!=`number`)continue;let c=i+s,l=o.doc.nodeAt(c);if(!l)continue;let u={...l.attrs,alignment:n};o.setNodeMarkup(c,l.type,u,l.marks)}return o.docChanged?(o.scrollIntoView(),e.dispatch(o),e.focus(),!0):!1},ps=e=>{let t=Z(e.state);!t||t.rowIndex<=0||ls(e,t)},ms=e=>{let t=Z(e.state);!t||t.rowIndex<0||t.columnIndex<0||ds(e,t)},hs=e=>{let[t,n]=(0,c.useState)(!1),r=Gi({open:t,portalContainer:e.portalContainer,editorWrapper:e.collisionBoundary,horizontalAlign:`start`,offsetY:10,fallbackWidth:156,fallbackHeight:240,onOutside:()=>n(!1)}),i=e=>{e.preventDefault()},a=()=>{if(t){n(!1);return}r.updatePosition(),n(!0)},o=e=>{e(),n(!1)},s=[{key:`insert-row-above`,label:e.messages.tableInsertRowAboveLabel,icon:f.ArrowUpToLine,disabled:!e.canInsertRowAbove,onAction:e.onInsertRowAbove},{key:`insert-row-below`,label:e.messages.tableInsertRowBelowLabel,icon:f.ArrowDownToLine,onAction:e.onInsertRowBelow},{key:`insert-column-left`,label:e.messages.tableInsertColumnLeftLabel,icon:f.ArrowLeftToLine,disabled:!e.canInsertColumn,onAction:e.onInsertColumnLeft},{key:`insert-column-right`,label:e.messages.tableInsertColumnRightLabel,icon:f.ArrowRightToLine,disabled:!e.canInsertColumn,onAction:e.onInsertColumnRight}],l=[{key:`delete-row`,label:e.messages.tableDeleteRowLabel,icon:f.Trash2,disabled:!e.canDeleteRow,danger:!0,onAction:e.onDeleteRow},{key:`delete-column`,label:e.messages.tableDeleteColumnLabel,icon:f.Trash2,disabled:!e.canDeleteColumn,danger:!0,onAction:e.onDeleteColumn}],u=e=>(0,c.createElement)(H,{key:e.key,type:`button`,variant:`ghost`,size:`sm`,className:e.danger?`zt-md-table-action-menu-item zt-md-table-action-menu-item-danger disabled:pointer-events-auto disabled:cursor-not-allowed`:`zt-md-table-action-menu-item disabled:pointer-events-auto disabled:cursor-not-allowed`,disabled:e.disabled,onMouseDown:i,onClick:()=>o(e.onAction)},(0,c.createElement)(e.icon,{size:14,strokeWidth:1.8,className:`zt-md-table-action-menu-item-icon`,"aria-hidden":`true`}),(0,c.createElement)(`span`,{className:`zt-md-table-action-menu-item-label`},e.label));return(0,c.createElement)(c.Fragment,null,(0,c.createElement)(`button`,{ref:r.triggerRef,type:`button`,className:`zt-md-table-action-button`,"aria-label":e.messages.tableMoreAriaLabel,"aria-expanded":t,onMouseDown:i,onClick:a},(0,c.createElement)(f.EllipsisVertical,{size:15,strokeWidth:2,"aria-hidden":`true`})),(0,c.createElement)(Ki,{panel:r,portalContainer:e.portalContainer,className:`zt-md-table-action-popover`,onMouseDown:i},(0,c.createElement)(`div`,{className:`zt-md-table-action-menu-group`},...s.map(u)),(0,c.createElement)(`div`,{className:`zt-md-table-action-menu-divider`,"aria-hidden":`true`}),(0,c.createElement)(`div`,{className:`zt-md-table-action-menu-group`},...l.map(u))))},gs=`zt-md-table-focus-actions`,_s=8,vs=8,ys=`left`,bs=K(`Trash2`,{size:15,strokeWidth:2}),xs=K(`AlignLeft`,{size:15,strokeWidth:2}),Ss=K(`AlignCenter`,{size:15,strokeWidth:2}),Cs=K(`AlignRight`,{size:15,strokeWidth:2}),ws=e=>typeof e.props.editable==`function`?e.props.editable(e.state):e.editable,Ts=e=>{let{selection:t,doc:n}=e.state;return t.empty||!(t instanceof v.TextSelection)?!1:n.textBetween(t.from,t.to).trim().length>0},Es=()=>{let e=document.createElement(`span`);return e.className=`zt-md-table-actions-divider`,e.setAttribute(`aria-hidden`,`true`),e},Ds=(e,t,n)=>t<0||n<0?null:e.rows.item(t)?.cells.item(n)??null,Os=class{constructor(e,t,n){this.isAttached=!1,this.messageVersion=0,this.lastMoreActionsKey=``,this.currentTableStart=null,this.currentTableNodeSize=null,this.currentColumnIndex=null,this.currentColumnAlignment=ys,this.currentAnchorElement=null,this.currentTableWrapper=null,this.hasPositionContext=!1,this.repositionScheduler=Ui(()=>{this.hasPositionContext&&this.updateOverlayPosition()}),this.handleActionsMouseDown=e=>{e.preventDefault()},this.handleTableWrapperScroll=()=>{this.repositionScheduler.schedule()},this.handleDeleteClick=e=>{if(e.preventDefault(),this.currentTableStart===null||this.currentTableNodeSize===null)return;let t=this.currentTableStart,n=this.currentTableStart+this.currentTableNodeSize,r=this.view.state.tr.delete(t,n).scrollIntoView();this.view.dispatch(r),this.view.focus()},this.handleAlignLeftClick=()=>{this.applyColumnAlignment(`left`)},this.handleAlignCenterClick=()=>{this.applyColumnAlignment(`center`)},this.handleAlignRightClick=()=>{this.applyColumnAlignment(`right`)},this.handleInsertRowBelow=()=>{let e=Z(this.view.state);!e||e.rowIndex<0||cs(this.view,e,`below`)},this.handleInsertRowAbove=()=>{let e=Z(this.view.state);!e||e.rowIndex<=0||cs(this.view,e,`above`)},this.handleInsertColumnLeft=()=>{this.insertColumn(`left`)},this.handleInsertColumnRight=()=>{this.insertColumn(`right`)},this.handleDeleteRow=()=>{ps(this.view)},this.handleDeleteColumn=()=>{ms(this.view)},this.view=e,this.messages=t,this.portalContainer=n,this.editorWrapper=Li(e.dom),this.actionsContainer=document.createElement(`div`),this.actionsContainer.className=`zt-md-table-actions-overlay`,this.deleteButton=document.createElement(`button`),this.deleteButton.type=`button`,this.deleteButton.className=`zt-md-table-action-button zt-md-table-action-button-danger`,this.deleteButton.style.display=`inline-flex`,this.deleteButton.setAttribute(`aria-label`,t.tableDeleteAriaLabel),this.deleteButton.innerHTML=bs,this.alignLeftButton=this.createColumnAlignmentButton(t.tableAlignLeftAriaLabel,xs),this.alignCenterButton=this.createColumnAlignmentButton(t.tableAlignCenterAriaLabel,Ss),this.alignRightButton=this.createColumnAlignmentButton(t.tableAlignRightAriaLabel,Cs),this.moreActionsMount=document.createElement(`span`),this.moreActionsMount.className=`zt-md-table-more-actions-mount`,this.moreActionsRoot=(0,ae.createRoot)(this.moreActionsMount),this.actionsContainer.append(this.moreActionsMount,Es(),this.alignLeftButton,this.alignCenterButton,this.alignRightButton,Es(),this.deleteButton),this.actionsContainer.addEventListener(`mousedown`,this.handleActionsMouseDown),this.deleteButton.addEventListener(`click`,this.handleDeleteClick),this.alignLeftButton.addEventListener(`click`,this.handleAlignLeftClick),this.alignCenterButton.addEventListener(`click`,this.handleAlignCenterClick),this.alignRightButton.addEventListener(`click`,this.handleAlignRightClick),this.update(e),this.stopObservingMessages=W(t,()=>{this.messageVersion+=1,this.deleteButton.setAttribute(`aria-label`,t.tableDeleteAriaLabel),this.alignLeftButton.setAttribute(`aria-label`,t.tableAlignLeftAriaLabel),this.alignCenterButton.setAttribute(`aria-label`,t.tableAlignCenterAriaLabel),this.alignRightButton.setAttribute(`aria-label`,t.tableAlignRightAriaLabel),this.isAttached&&this.update(this.view)})}bindTableWrapperScroll(e){let t=e.closest(`.tableWrapper`);this.currentTableWrapper!==t&&(this.unbindTableWrapperScroll(),this.currentTableWrapper=t,this.currentTableWrapper&&this.currentTableWrapper.addEventListener(`scroll`,this.handleTableWrapperScroll,{passive:!0}))}unbindTableWrapperScroll(){this.currentTableWrapper&&=(this.currentTableWrapper.removeEventListener(`scroll`,this.handleTableWrapperScroll),null)}createColumnAlignmentButton(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`zt-md-table-action-button`,n.style.display=`inline-flex`,n.setAttribute(`aria-label`,e),n.innerHTML=t,n}resolveColumnAlignment(e){return e===`center`||e===`right`?e:ys}updateAlignmentButtonsState(e){this.alignLeftButton.disabled=!e,this.alignCenterButton.disabled=!e,this.alignRightButton.disabled=!e,this.alignLeftButton.classList.toggle(`zt-md-table-action-button-active`,e&&this.currentColumnAlignment===`left`),this.alignCenterButton.classList.toggle(`zt-md-table-action-button-active`,e&&this.currentColumnAlignment===`center`),this.alignRightButton.classList.toggle(`zt-md-table-action-button-active`,e&&this.currentColumnAlignment===`right`)}applyColumnAlignment(e){let t=Z(this.view.state);!t||t.rowIndex<0||t.columnIndex<0||fs(this.view,t,e)}insertColumn(e){let t=Z(this.view.state);!t||t.rowIndex<0||t.columnIndex<0||us(this.view,t,e)}renderMoreActions(e,t,n,r){let i=`${this.messageVersion}:${e}:${t}:${n}:${r}`;this.lastMoreActionsKey!==i&&(this.lastMoreActionsKey=i,this.moreActionsRoot.render((0,c.createElement)(hs,{messages:this.messages,portalContainer:this.portalContainer,collisionBoundary:this.editorWrapper,canInsertRowAbove:e,canInsertColumn:t,canDeleteRow:n,canDeleteColumn:r,onInsertRowAbove:this.handleInsertRowAbove,onInsertRowBelow:this.handleInsertRowBelow,onInsertColumnLeft:this.handleInsertColumnLeft,onInsertColumnRight:this.handleInsertColumnRight,onDeleteRow:this.handleDeleteRow,onDeleteColumn:this.handleDeleteColumn})))}resolveTableElement(e){if(e instanceof HTMLTableElement)return e;let t=e.querySelector(`table`);return t instanceof HTMLTableElement?t:null}resolveActionsContainerSize(){let e=this.actionsContainer.getBoundingClientRect();return e.width<=0||e.height<=0?null:{width:e.width,height:e.height}}updateOverlayPosition(){if(!this.editorWrapper||!this.currentAnchorElement||this.actionsContainer.parentElement!==this.portalContainer)return;let e=this.resolveActionsContainerSize();if(!e)return;let t=this.currentAnchorElement.getBoundingClientRect(),n=this.editorWrapper.getBoundingClientRect(),r=t.top-n.top,i=n.bottom-t.bottom,a=r>=e.height+_s+vs||r>=i?`top`:`bottom`,o=zi(t,this.editorWrapper,n),s=Hi({wrapper:this.editorWrapper,anchor:o,overlaySize:e,placement:a,horizontalAlign:`center`,offsetY:_s,boundaryInset:vs},this.portalContainer,n);this.actionsContainer.style.left=`${s.left}px`,this.actionsContainer.style.top=`${s.top}px`}update(e){if(this.view=e,e.composing)return;if(!this.editorWrapper||!ws(e)||Ts(e)){this.detach();return}let t=Z(e.state);if(!t){this.detach();return}let n=e.nodeDOM(t.tableStart);if(!(n instanceof HTMLElement)){this.detach();return}let r=this.resolveTableElement(n);if(!r){this.detach();return}let i=this.isAttached;this.isAttached||(this.isAttached=!0,this.repositionScheduler.bindGlobal(),this.repositionScheduler.bindWrapper(this.editorWrapper)),this.actionsContainer.parentElement!==this.portalContainer&&this.portalContainer.append(this.actionsContainer);let a=as(t),o=a&&t.tableNode.child(0).childCount>1,s=t.rowIndex>0,c=t.rowIndex>0,l=t.tableNode.childCount>0?t.tableNode.child(0):null;this.currentColumnIndex=a?t.columnIndex:null,this.currentColumnAlignment=this.resolveColumnAlignment(this.currentColumnIndex===null?null:l?.maybeChild(this.currentColumnIndex)?.attrs?.alignment),this.updateAlignmentButtonsState(a),this.renderMoreActions(s,a,c,o),this.bindTableWrapperScroll(r),this.currentAnchorElement=Ds(r,t.rowIndex,t.columnIndex)??r,this.currentTableStart=t.tableStart,this.currentTableNodeSize=t.tableNodeSize,this.hasPositionContext=!0,i?this.repositionScheduler.schedule():this.updateOverlayPosition()}detach(){this.isAttached&&(this.isAttached=!1,this.repositionScheduler.unbindGlobal(),this.repositionScheduler.bindWrapper(null),this.unbindTableWrapperScroll(),this.lastMoreActionsKey=``,this.moreActionsRoot.render(null),this.actionsContainer.remove(),this.currentAnchorElement=null,this.currentTableStart=null,this.currentTableNodeSize=null,this.currentColumnIndex=null,this.currentColumnAlignment=ys,this.updateAlignmentButtonsState(!1),this.hasPositionContext=!1)}destroy(){this.stopObservingMessages(),this.detach(),this.repositionScheduler.destroy(),this.moreActionsRoot.unmount(),this.actionsContainer.removeEventListener(`mousedown`,this.handleActionsMouseDown),this.deleteButton.removeEventListener(`click`,this.handleDeleteClick),this.alignLeftButton.removeEventListener(`click`,this.handleAlignLeftClick),this.alignCenterButton.removeEventListener(`click`,this.handleAlignCenterClick),this.alignRightButton.removeEventListener(`click`,this.handleAlignRightClick)}},ks=(e,t)=>{let n=t??U();return(0,L.$prose)(()=>new v.Plugin({key:new v.PluginKey(gs),view:t=>new Os(t,n,e)}))},As=`list_item`,js=`li[data-item-type="task"]`,Ms=24,Ns=(e,t)=>{let n=t.getBoundingClientRect();return e.clientX>=n.left&&e.clientX<=n.left+Ms&&e.clientY>=n.top&&e.clientY<=n.top+Ms},Ps=e=>{if(!(e instanceof Element))return null;let t=e.closest(js);return t instanceof HTMLElement?t:null},Fs=(e,t)=>{if(!e.editable)return!1;let n=Ps(t.target);return!n||!Ns(t,n)?!1:(t.preventDefault(),!0)},Is=(e,t)=>{let n=e.posAtDOM(t,0)-1,r=e.state.doc.nodeAt(n);return!r||r.type.name!==As||r.attrs.checked==null?!1:(e.dispatch(e.state.tr.setNodeMarkup(n,void 0,{...r.attrs,checked:!r.attrs.checked})),!0)},Ls=(0,L.$prose)(()=>new v.Plugin({props:{handleDOMEvents:{mousedown:(e,t)=>Fs(e,t),dblclick:(e,t)=>Fs(e,t),click:(e,t)=>{if(!e.editable)return!1;let n=Ps(t.target);return!n||!Ns(t,n)||!Is(e,n)?!1:(t.preventDefault(),!0)}}}})),Rs=`Tab`,zs=4,Bs=/^ */,Vs=`list_item`,Hs=e=>typeof e.props.editable==`function`?e.props.editable(e.state):e.editable,Us=e=>{let{$from:t}=e.selection;for(let e=t.depth;e>=0;--e){let n=t.node(e);if(n.type.name===Vs)return n.type}return null},Ws=e=>{let{selection:t,doc:n}=e;if(t.empty)return[t.$from.start()];let r=new Set;return n.nodesBetween(t.from,t.to,(e,t)=>{e.isTextblock&&r.add(t+1)}),Array.from(r)},Gs=(e,t)=>{let{state:n}=e,r=` `.repeat(zs),i=Ws(n).sort((e,t)=>t-e),a=n.tr;return n.selection.empty?a.insertText(r,n.selection.to):i.forEach(e=>{a.insertText(r,e)}),a.docChanged?(t.preventDefault(),e.dispatch(a),!0):!1},Ks=(e,t)=>{let{state:n}=e,{selection:r}=n;if(!(r instanceof v.TextSelection))return!1;let i=Ws(n).sort((e,t)=>t-e),a=n.tr;return i.forEach(e=>{let t=n.doc.resolve(e).parent.textContent.match(Bs)?.[0].length??0,r=Math.min(t,zs);r<=0||a.delete(e,e+r)}),a.docChanged?(t.preventDefault(),e.dispatch(a),!0):!1},qs=(0,L.$prose)(()=>new v.Plugin({key:new v.PluginKey(`zt-md-tab-space-indent`),props:{handleKeyDown:(e,t)=>{let n=e;if(!Hs(n)||t.defaultPrevented||t.key!==Rs||t.altKey||t.ctrlKey||t.metaKey)return!1;let r=Us(n.state);if(r){let e=(t.shiftKey?(0,fe.liftListItem)(r):(0,fe.sinkListItem)(r))(n.state,n.dispatch);return t.preventDefault(),e||!0}return t.shiftKey?Ks(n,t):Gs(n,t)}}})),Js=e=>{let t=(e instanceof Element?e:e.parentElement)?.closest(`code`);return t instanceof HTMLElement&&!t.closest(`pre`)?t:null},Ys=(e,t,n)=>Js(e.domAtPos(t,n).node),Xs=e=>{let t=e.ownerDocument.createTreeWalker(e,NodeFilter.SHOW_TEXT),n=t.nextNode(),r=null;for(;n;)n.data.length>0&&(r=n),n=t.nextNode();return r},Zs=(e,t,n)=>{let r=e.domAtPos(t,n);e.dom.ownerDocument.getSelection()?.collapse(r.node,r.offset)},Qs=(e,t)=>{let n=e.domAtPos(t,-1),r=Js(n.node),i=e.dom.ownerDocument.getSelection();if(!r){i?.collapse(n.node,n.offset);return}let a=Xs(r);if(!a){let e=r.childNodes.length;i?.collapse(r,e);return}let o=a.data.length;i?.collapse(a,o)},$s={left:{inwardKey:`ArrowRight`,outwardKey:`ArrowLeft`},right:{inwardKey:`ArrowLeft`,outwardKey:`ArrowRight`}},ec={left:`nodeAfter`,right:`nodeBefore`},tc=(e,t)=>{e.dispatch(e.state.tr.setMeta(t,null))},nc=(e,t,n,r,i)=>{if(t.key===`ArrowRight`)return tc(e,i),!1;if(t.key!==`ArrowLeft`)return!1;t.preventDefault();let a=(e.state.storedMarks??e.state.selection.$from.marks()).filter(e=>e.type!==n);return e.dispatch(e.state.tr.setStoredMarks(a).setMeta(i,{...r,placement:`outside`})),!0},rc=(e,t,n,r,i)=>{if(r.placement===`inside`)return nc(e,t,n,r,i);let a=$s[r.side];if(t.key===a.outwardKey)return tc(e,i),!1;if(t.key!==a.inwardKey)return!1;let o=ec[r.side],s=e.state.selection.$from[o],c=s?n.isInSet(s.marks):null;if(!c)return tc(e,i),!1;t.preventDefault();let l=e.state.storedMarks??e.state.selection.$from.marks(),u=c.addToSet(l);return e.dispatch(e.state.tr.setSelection(v.TextSelection.create(e.state.doc,r.position)).setStoredMarks(u).setMeta(i,r.side===`left`?{...r,placement:`inside`}:null)),r.side===`right`&&Qs(e,r.position),!0},Q=(e,t)=>!!t.isInSet(e),ic=(e,t,n)=>{let r=e.state.doc.resolve(t),i=r.nodeBefore,a=r.nodeAfter;return!a||Q(i?.marks??[],n)||!Q(a.marks,n)?null:n.isInSet(a.marks)},ac=(e,t,n)=>{let r=e.state.doc.resolve(t),i=r.nodeBefore,a=r.nodeAfter;return!i||!Q(i.marks,n)||Q(a?.marks??[],n)?null:n.isInSet(i.marks)},$=new v.PluginKey(`zt-md-inline-code-boundary-navigation`),oc=`inlineCode`,sc=2,cc=(e,t,n,r)=>{let i=t>0?[t,t-1]:[t];for(let[t,a]of i.entries()){let i=ac(e,a,r);if(!i)continue;let o=e.state.doc.resolve(a).nodeAfter;if(o!==null&&!o.isText)continue;let s=Ys(e,a,-1);if(!s)continue;let c=n<=s.getBoundingClientRect().right+sc;if(!(t>0&&!c))return{boundaryPosition:a,inlineCodeMark:i,rightPlainTextNode:o,codeElement:s}}return null},lc=(e,t)=>{if(t.button!==0||t.altKey||t.ctrlKey||t.metaKey||t.shiftKey||!e.editable)return!1;let n=e.posAtCoords({left:t.clientX,top:t.clientY}),r=e.state.schema.marks[oc];if(!n||!r)return!1;let i=n.pos,a=e.state.doc.resolve(i),o=ic(e,i,r),s=a.nodeBefore;if(o&&(!s||s.isText)){let n=Ys(e,i,1);if(!n)return!1;let c=n.getBoundingClientRect(),l=t.clientX>=c.left,u=(s?.marks??a.marks()).filter(e=>e.type!==r),d=l?o.addToSet(a.marks()):u,f=l?{position:i,side:`left`,placement:`inside`}:null;return t.preventDefault(),e.dispatch(e.state.tr.setSelection(v.TextSelection.create(e.state.doc,i)).setStoredMarks(d).setMeta($,f)),e.focus(),l||Zs(e,i,-1),!0}let c=cc(e,i,t.clientX,r);if(!c)return!1;let l=c.boundaryPosition,u=e.state.doc.resolve(l),d=c.codeElement.getBoundingClientRect(),f=t.clientX>=d.right,p=(c.rightPlainTextNode?.marks??u.marks()).filter(e=>e.type!==r),m=f?p:c.inlineCodeMark.addToSet(u.marks()),h=f?{position:l,side:`right`,placement:`outside`}:null;return t.preventDefault(),e.dispatch(e.state.tr.setSelection(v.TextSelection.create(e.state.doc,l)).setStoredMarks(m).setMeta($,h)),e.focus(),f||Qs(e,l),!0},uc=`inlineCode`,dc=`zt-md-inline-code-boundary-indicator`,fc=`zt-md-inline-code-boundary-indicator-widget`,pc=`zt-md-inline-code-boundary-active`,mc={left:-1,right:1},hc={left:1,right:-1},gc=e=>{let t=document.createElement(`span`);return t.className=dc,t.dataset.side=e.side,t.dataset.placement=e.placement,t.contentEditable=`false`,t.setAttribute(`aria-hidden`,`true`),t},_c=(e,t)=>{if(t.placement===`outside`)return[];let n=e.schema.marks[uc],r=e.doc.resolve(t.position).nodeAfter,i=r&&n?n.isInSet(r.marks):null;return i?[i]:null},vc=e=>{let t=$.getState(e);if(!t)return I.DecorationSet.empty;let n=_c(e,t);if(!n)return I.DecorationSet.empty;let r=t.placement===`inside`?1:mc[t.side],i=gc(t),a=I.Decoration.widget(t.position,i,{side:r,marks:n,key:`${fc}-${t.side}-${t.placement}`,ignoreSelection:!0,relaxedSide:!0});return I.DecorationSet.create(e.doc,[a])},yc=(e,t)=>{if(t?.placement!==`outside`)return;let n=e.dom.querySelector(`.${dc}[data-side='${t.side}'][data-placement='outside']`),r=hc[t.side],i=Ys(e,t.position,r);if(!n||!i)return;let a=n.getBoundingClientRect().left,o=i.getBoundingClientRect(),s=t.side===`left`?o.left-1:o.right+1,c=Math.round(s-a);n.style.setProperty(`--zt-md-inline-code-boundary-offset-x`,`${c}px`)},bc=`inlineCode`,xc=(e,t)=>{let{selection:n}=e.state;if(!n.empty)return!1;let r=n.$from.nodeBefore,i=n.$from.nodeAfter;return!!(r&&Q(r.marks,t)&&(!i||!Q(i.marks,t)))},Sc=(e,t)=>{let{selection:n}=e.state;if(!n.empty)return!1;let r=n.$from.nodeBefore,i=n.$from.nodeAfter;return!!(i&&Q(i.marks,t)&&(!r||!Q(r.marks,t)))},Cc=(e,t,n)=>{let r=ic(e,t,n);if(!r)return!1;let i=e.state.storedMarks??e.state.doc.resolve(t).marks(),a=r.addToSet(i);return e.dispatch(e.state.tr.setSelection(v.TextSelection.create(e.state.doc,t)).setStoredMarks(a).setMeta($,{position:t,side:`left`,placement:`inside`})),!0},wc=(e,t)=>t.defaultPrevented||t.altKey||t.ctrlKey||t.metaKey||t.shiftKey||!e.editable,Tc=(e,t)=>{let{selection:n}=e.state;if(!n.empty)return null;let r=n.$from.nodeBefore;return!r||!Q(r.marks,t)?null:Array.from(r.textContent).length===1?n.from-r.nodeSize:null},Ec=(e,t,n)=>{if(t.key!==`ArrowLeft`)return!1;let r=Tc(e,n);if(r===null)return!1;let i=e.state.storedMarks??e.state.selection.$from.marks();return Q(i,n)?(t.preventDefault(),e.dispatch(e.state.tr.setSelection(v.TextSelection.create(e.state.doc,r)).setStoredMarks(i).setMeta($,{position:r,side:`left`,placement:`inside`})),!0):!1},Dc=(e,t,n)=>{if(!Sc(e,n))return!1;let r=e.state.storedMarks??e.state.selection.$from.marks();if(!Q(r,n))return Pc(e),!1;t.preventDefault();let i=r.filter(e=>e.type!==n);return e.dispatch(e.state.tr.setStoredMarks(i).setMeta($,{position:e.state.selection.from,side:`left`,placement:`outside`})),Zs(e,e.state.selection.from,-1),!0},Oc=(e,t,n)=>{if(t.key!==`ArrowLeft`||!xc(e,n))return!1;let r=e.state.storedMarks??e.state.selection.$from.marks();return Q(r,n)?!1:(t.preventDefault(),e.dispatch(e.state.tr.setStoredMarks(r).setMeta($,{position:e.state.selection.from,side:`right`,placement:`outside`})),Zs(e,e.state.selection.from,1),!0)},kc=(e,t)=>{let{selection:n}=e.state;if(!n.empty)return null;let r=n.$from.nodeBefore;if(!r?.isText||Q(r.marks,t)||Array.from(r.textContent).length!==1)return null;let i=n.from-r.nodeSize;return ac(e,i,t)?i:null},Ac=(e,t,n)=>{if(t.key!==`ArrowLeft`)return!1;let r=kc(e,n);if(r===null)return!1;let i=(e.state.selection.$from.nodeBefore?.marks??[]).filter(e=>e.type!==n);return t.preventDefault(),e.dispatch(e.state.tr.setSelection(v.TextSelection.create(e.state.doc,r)).setStoredMarks(i).setMeta($,{position:r,side:`right`,placement:`outside`})),Zs(e,r,1),!0},jc=(e,t,n)=>Ac(e,t,n)||Oc(e,t,n)||Ec(e,t,n)||Dc(e,t,n),Mc=()=>null,Nc=(e,t)=>{let n=e.getMeta($);return n===void 0?e.docChanged||e.selectionSet||e.storedMarksSet?null:t:n},Pc=e=>{$.getState(e.state)!=null&&e.dispatch(e.state.tr.setMeta($,null))},Fc=e=>(Pc(e),!1),Ic=class{constructor(e){this.editorDom=e.dom,this.update(e)}update(e){let t=$.getState(e.state),n=t!=null;this.editorDom.classList.toggle(pc,n),yc(e,t)}destroy(){this.editorDom.classList.remove(pc)}},Lc=e=>new Ic(e),Rc=e=>{if(!(e instanceof Element))return!1;let t=e.closest(`code`);return!!(t&&!t.closest(`pre`))},zc=(e,t,n)=>{if(!e.state.selection.empty)return!1;if(lc(e,n))return!0;let r=Rc(n.target),i=e.state.schema.marks[bc];if(i&&r&&Cc(e,t,i))return n.preventDefault(),!0;let a=$.getState(e.state);if(!r||!a)return!1;let o=e.state.storedMarks,s=e.state.tr.setMeta($,null);return o!==null&&i&&!Q(o,i)&&s.setStoredMarks(null),e.dispatch(s),!1},Bc=(e,t,n)=>t.key!==`ArrowRight`||!Sc(e,n)||Q(e.state.storedMarks??e.state.selection.$from.marks(),n)||!Cc(e,e.state.selection.from,n)?!1:(t.preventDefault(),!0),Vc={ArrowLeft:jc,ArrowRight:(e,t,n)=>{if(t.key!==`ArrowRight`)return!1;if(Bc(e,t,n))return!0;if(!xc(e,n))return!1;let r=e.state.storedMarks??e.state.selection.$from.marks();if(!Q(r,n))return Pc(e),!1;t.preventDefault();let i=r.filter(e=>e.type!==n);return e.dispatch(e.state.tr.setStoredMarks(i).setMeta($,{position:e.state.selection.from,side:`right`,placement:`outside`})),Zs(e,e.state.selection.from,1),!0}},Hc=(e,t)=>{if(wc(e,t))return!1;let n=Vc[t.key];if(!n)return!1;let r=e.state.schema.marks[bc];if(!r)return!1;let i=$.getState(e.state);return i?rc(e,t,r,i,$):n(e,t,r)},Uc=(0,L.$prose)(()=>new v.Plugin({key:$,view:Lc,state:{init:Mc,apply:Nc},props:{handleKeyDown:Hc,handleClick:zc,decorations:vc,handleDOMEvents:{blur:Fc}}})),Wc=`.zt-md-code-block-action-button[data-active='true']`,Gc=`.zt-md-search-panel`,Kc=8,qc={current:0,total:0,isInvalidExpression:!1},Jc=e=>typeof e.props.editable==`function`?e.props.editable(e.state):e.editable,Yc=e=>new V.SearchQuery({search:e.search,replace:e.replace,caseSensitive:e.caseSensitive,wholeWord:e.wholeWord,regexp:e.regexp,literal:!0}),Xc=(e,t)=>{if(!t.valid)return[];let n=[],r=0,i=e.doc.content.size;for(;r<i;){let a=t.findNext(e,r,i);if(!a)break;n.push(a),r=Math.max(a.to,r+1)}return n},Zc=(e,t,n)=>{let r=0,i=e.length-1;for(;r<=i;){let a=r+i>>1,o=e[a];if(o.from===t)return o.to===n?a:-1;o.from<t?r=a+1:i=a-1}return-1},Qc=(e,t,n)=>{let r=n.regexp&&n.search.length>0&&!n.valid,i=Zc(t,e.selection.from,e.selection.to);return{current:i<0?0:i+1,total:t.length,isInvalidExpression:r}},$c=(e,t)=>e.current===t.current&&e.total===t.total&&e.isInvalidExpression===t.isInvalidExpression,el=e=>{if(e.state.selection.empty)return;let t=Li(e.dom);if(!t)return;let n=e.coordsAtPos(e.state.selection.from),r=e.coordsAtPos(e.state.selection.to),i=Math.min(n.top,r.top),a=Math.max(n.bottom,r.bottom),o=t.getBoundingClientRect(),s=(t.closest(`.zt-md`)?.querySelector(Gc))?.getBoundingClientRect(),c=Math.max(o.top+Kc,(s?.bottom??o.top)+Kc),l=o.bottom-Kc;if(i<c){t.scrollTop+=i-c;return}a>l&&(t.scrollTop+=a-l)},tl=e=>{if(e.state.selection.empty)return;let t=e.domAtPos(e.state.selection.from),n=(t.node instanceof Element?t.node:t.node.parentElement)?.closest(`.zt-md-code-block`);if(n?.dataset.viewMode!==`preview`){el(e);return}n.querySelector(Wc)?.click(),window.requestAnimationFrame(()=>{el(e)})},nl=class{constructor(e,t){this.onSnapshotChange=t,this.snapshot=qc,this.cachedDoc=null,this.cachedQuery=null,this.cachedResults=[],this.emitSnapshot(e.state)}update(e){this.emitSnapshot(e.state)}destroy(){this.cachedDoc=null,this.cachedQuery=null,this.cachedResults=[],this.onSnapshotChange(qc)}resolveSearchResults(e,t){if(this.cachedDoc===e.doc&&this.cachedQuery&&this.cachedQuery.eq(t))return this.cachedResults;let n=Xc(e,t);return this.cachedDoc=e.doc,this.cachedQuery=t,this.cachedResults=n,n}emitSnapshot(e){let t=(0,V.getSearchState)(e);if(!t){this.cachedDoc=null,this.cachedQuery=null,this.cachedResults=[],$c(this.snapshot,qc)||(this.snapshot=qc,this.onSnapshotChange(qc));return}let n=Qc(e,this.resolveSearchResults(e,t.query),t.query);$c(this.snapshot,n)||(this.snapshot=n,this.onSnapshotChange(n))}},rl=e=>[(0,L.$prose)(()=>(0,V.search)()),(0,L.$prose)(()=>new v.Plugin({view:t=>new nl(t,e)}))],il=e=>{let t=t=>{e(e=>{let n=Yc(t),r=(0,V.setSearchState)(e.state.tr,n);if(n.valid){let t=n.findNext(e.state,e.state.selection.from)??n.findNext(e.state,0,e.state.selection.from);t&&r.setSelection(v.TextSelection.create(r.doc,t.from,t.to)).scrollIntoView()}e.dispatch(r),tl(e)})},n=(e,t)=>{e(t.state,e=>{t.dispatch(e.scrollIntoView())})&&tl(t)};return{updateQuery:t,findPrevious:()=>{e(e=>{n(V.findPrev,e)})},findNext:()=>{e(e=>{n(V.findNext,e)})},replaceCurrent:()=>{e(e=>{Jc(e)&&n(V.replaceNext,e)})},replaceAll:()=>{e(e=>{if(!Jc(e))return;let t=(0,V.getSearchState)(e.state);!t||Xc(e.state,t.query).length===0||(0,V.replaceAll)(e.state,t=>{e.dispatch(t)})})},clear:()=>{e(e=>{let t=new V.SearchQuery({search:``,literal:!0});e.dispatch((0,V.setSearchState)(e.state.tr,t))})},focusCurrent:()=>{e(e=>{e.dispatch(e.state.tr.scrollIntoView()),el(e),e.focus()})}}},al=/^[ \t]+/,ol=/[ \t]+$/,sl=[(0,L.$remark)(`remarkCjkFriendly`,()=>he.default),(0,L.$remark)(`remarkCjkFriendlyGfmStrikethrough`,()=>ge.default)].flat(),cl=e=>{let t=((t,n,r,i)=>{let{delimiter:a,after:o}=e.resolveDelimiters(t,r),s=r.enter(e.constructName),c=r.createTracker(i),l=r.createTracker(i);l.move(a);let u=r.containerPhrasing(t,{before:a,after:o,...l.current()});s();let d=al.exec(u)?.[0]??``,f=ol.exec(u)?.[0]??``,p=u.slice(d.length,u.length-f.length);if(!p)return c.move(u);let m=``;return d&&(m+=c.move(d)),m+=c.move(a),m+=c.move(p),m+=c.move(a),f&&(m+=c.move(f)),m});return t.peek=e.peek,t},ll=e=>{let t=e.get(y.remarkStringifyOptionsCtx)??{},n=cl({constructName:`strong`,resolveDelimiters:(e,t)=>{let n=e.marker||t.options.strong||`*`;return{delimiter:n+n,after:n}},peek:(e,t,n)=>n.options.strong||`*`}),r=cl({constructName:`emphasis`,resolveDelimiters:(e,t)=>{let n=e.marker||t.options.emphasis||`*`;return{delimiter:n,after:n}},peek:(e,t,n)=>n.options.emphasis||`*`}),i=cl({constructName:`strikethrough`,resolveDelimiters:()=>({delimiter:`~~`,after:`~`}),peek:()=>`~`});e.set(y.remarkStringifyOptionsCtx,{...t,handlers:{...t.handlers,strong:n,emphasis:r,delete:i}})},ul=`ZT_MD_READONLY_CHANGE`,dl=new v.PluginKey(`ZT_MD_MARKDOWN_SYNC`),fl=`[data-type="code_block"], [data-type="image"], [data-type="math_block"], [data-type="math_inline"], [data-type="frontmatter"]`,pl=30,ml=e=>{let t=e.target;if(!(t instanceof Element))return null;let n=t.closest(`a[href]`);return n instanceof HTMLAnchorElement?n:null},hl=e=>e?.type.name===`image`,gl=(e,t)=>{let n=ml(e);if(!n)return!1;let r=St(n.getAttribute(`href`));return!r||t||!e.ctrlKey?!1:(e.preventDefault(),e.stopPropagation(),window.open(r,`_blank`,`noopener,noreferrer`),!0)},_l=(e,t)=>!t||!ml(e)?!1:(e.preventDefault(),e.stopPropagation(),!0),vl=(e,t)=>{let n=t?`false`:`true`;e.dom.querySelectorAll(fl).forEach(e=>{if(e.dataset.editable=n,e.dataset.type===`code_block`){let n=e.querySelector(`:scope > .zt-md-code-block-actions`);if(n){let e=n.querySelector(`.zt-md-code-block-action-button`),r=e?!e.hidden:!1;n.dataset.visible=!t||r?`true`:`false`}return}if(t&&e.dataset.type===`math_block`){e.classList.remove(`zt-md-math-block-editing`);let t=e.querySelector(`.zt-md-math-block-source`);t&&(t.hidden=!0)}})},yl=e=>{let t=e.readOnly,n=Math.max(0,e.debounceMs??0),r=!1,i=null,a=null,o=null,s=null,c=null,l=null,u=!1,f=null,p=()=>{f!==null&&(clearTimeout(f),f=null)},m=t=>{if(t.composing){u=!0;return}if(u=!1,t.state.doc===o||(c||=F.action(e=>e.get(y.serializerCtx)),!c))return;o=t.state.doc;let n=c(t.state.doc);n!==a&&(a=n,e.onChange(n))},h=e=>{if(n<=0||!l){m(e);return}l()},g=()=>{l?.cancel(),l=n>0?(0,d.debounce)(()=>{s&&m(s)},n):null};g();let _={...e.messages??U(e.locale)},E=ks(e.contentPortalContainer,_),D=mo(e.contentPortalContainer,_,e.shortcutMode),O=sa(_,e.contentPortalContainer),k=ur(_,e.contentPortalContainer),A=On(e.imageUpload,_),j=rl(e.onSearchSnapshotChange),M=(0,L.$prose)(()=>new v.Plugin({key:dl,props:{handleDOMEvents:{compositionstart:()=>(p(),l?.cancel(),!1),compositionend:()=>(p(),f=setTimeout(()=>{f=null,s&&!s.composing&&!r&&(u||s.state.doc!==o)&&(u=!1,h(s))},pl),!1),blur:e=>e.composing||r?!1:(p(),l?.cancel(),m(e),!1)}},view:e=>(s=e,o=e.state.doc,{update:(e,t)=>{if(s=e,r){o=e.state.doc,a=i,u=!1,p(),l?.cancel();return}if(e.composing){(t.doc!==e.state.doc||e.state.doc!==o)&&(u=!0),p(),l?.cancel();return}let n=t.doc!==e.state.doc,c=u&&e.state.doc!==o;!n&&!c||(u=!1,p(),h(e))},destroy:()=>{p(),u=!1,l?.cancel(),c=null,s=null}})})),N=Bo(e.portalContainer,e.slashMenu,_,e.imageUpload,e.locale,e.shortcutMode),ee=N.plugins,P=Wo(e.portalContainer,_,e.shortcutMode,e.imageUpload),te={commonmark:C.commonmark,frontmatter:va,taskListTransformKeymap:Ja(e.shortcutMode),inlineCodeBoundaryNavigation:Uc,gfm:w.gfm,cjkFriendly:sl,history:x.history,editorSearch:j,codeBlockPrism:[He,T.prismConfig],codeBlockLanguagePicker:O,clipboard:b.clipboard,indent:S.indent,imageDeleteSelection:an,imagePaste:A,tableArrowEntry:Qo,blockBoundaryNavigation:ut,headingBackspaceEmptyParagraph:ri,headingFocusIndicator:ci,mathBackspaceEntry:qn,blockquoteBackspaceLift:Yr,tableFocusActions:E,selectionTooltip:D,gapCursor:Je,dropCursor:qe,math:Hr,mathInlineEdit:k,mathInlineArrowNavigation:Mr,taskListToggle:Ls,tabSpaceIndent:qs,codeBlockModASelect:ma,slash:ee.length>0?ee:null},ne=We(te,{includeRuntime:!1}),re=We(te,{includeRuntime:!0}).filter(e=>e.name===`clipboard`||e.name===`indent`),F=y.Editor.make();F.config(n=>{qa(n,e.shortcutMode),pi(n),n.set(T.prismConfig.key,{configureRefractor:Ne}),Ft(n,e.imageUpload?.allowedProtocols),ll(n),n.set(y.rootCtx,e.root),n.set(y.defaultValueCtx,e.markdown),n.set(y.editorViewOptionsCtx,{editable:()=>!t,handleKeyDown:P,handleDOMEvents:{mousedown:(e,n)=>n instanceof MouseEvent?_l(n,t):!1,click:(e,n)=>n instanceof MouseEvent?_l(n,t):!1},handleClick:(e,n,r)=>gl(r,t),handleClickOn:(e,n,r,i,a,o)=>gl(a,t)?!0:t&&o&&hl(r)?(a.preventDefault(),!0):!1});let r=n.get(y.nodeViewCtx)??[];n.set(y.nodeViewCtx,[...r,[`image`,Gt(_)],[`math_block`,rr(_)],[`math_inline`,gr(_)],[`code_block`,ki(_)],[ha,Oa(_)]]),N.config&&N.config(n)}),ne.forEach(e=>{F.use(e.plugin)}),F.use(M);let I=il(e=>{F.action(t=>{e(t.get(y.editorViewCtx))})}),ie=()=>{re.forEach(e=>{try{F.use(e.plugin),e.name===`indent`&&F.action(e=>{e.set(S.indentConfig,{type:`space`,size:4})})}catch(e){console.error(e)}})},R=Ue(L.replaceAll,F);return{editor:F,updateLocalization:(e,t)=>{Ae(_,t),N.updateLocale?.(e)},setReadOnly:e=>{t!==e&&(t=e,F.action(e=>{let n=e.get(y.editorViewCtx);n.setProps({editable:()=>!t}),vl(n,t),n.dispatch(n.state.tr.setMeta(ul,t))}))},setDebounceMs:e=>{let t=Math.max(0,e);n!==t&&(n=t,g())},installRuntimePlugins:ie,focusEditor:e=>{F.action(t=>{let n=t.get(y.editorViewCtx),r=n.state.doc.lastChild,i=r?n.state.doc.content.size-r.nodeSize:null,a=i===null?null:n.nodeDOM(i),o=a instanceof Element?a:a?.parentElement??null;if(e!==void 0&&o!==null&&e.top>o.getBoundingClientRect().bottom){let e=n.state.schema.nodes.paragraph;if(!(r?.type===e&&r.content.size===0)){let t=n.state.tr.insert(n.state.doc.content.size,e.create());t.setSelection(v.TextSelection.atEnd(t.doc)).scrollIntoView(),n.dispatch(t),n.focus();return}}let s=e?n.posAtCoords(e):null,c=s?v.TextSelection.near(n.state.doc.resolve(s.pos),1):v.TextSelection.atEnd(n.state.doc);n.state.selection.eq(c)||n.dispatch(n.state.tr.setSelection(c).scrollIntoView()),n.focus()})},searchController:I,setMarkdown:e=>{p(),u=!1,l?.cancel(),i=e,r=!0;try{R(e)}finally{r=!1,i=null}}}},bl=(e,t,n,r)=>{let i=e,a=i.create.bind(e);return i.create=async()=>{try{let e=await a();return t(),n(),e}catch(e){throw console.error(`Milkdown init failed:`,e),r(e),e}},i},xl=e=>{let t=(0,c.useRef)(null),n=(0,c.useRef)(e.markdown),r=(0,c.useRef)(e.readOnly),i=(0,c.useRef)(e.debounceMs),a=(0,c.useRef)(e.onMarkdownChange),o=(0,c.useRef)(e.onInitError),s=(0,c.useRef)(e.onInitReady),u=(0,c.useRef)(e.onSearchSnapshotChange);r.current=e.readOnly,i.current=e.debounceMs;let d=(0,l.useEditor)(c=>{t.current=null,e.focusEditorRef&&(e.focusEditorRef.current=null),e.searchControllerRef&&(e.searchControllerRef.current=null),n.current=e.markdown;let l=yl({root:c,portalContainer:e.portalContainer,contentPortalContainer:e.contentPortalContainer,markdown:e.markdown,readOnly:r.current,debounceMs:i.current,messages:e.messages,locale:e.locale,slashMenu:e.slashMenu,imageUpload:e.imageUpload,shortcutMode:e.shortcutMode,onChange:e=>{n.current=e,a.current(e)},onSearchSnapshotChange:e=>{u.current?.(e)}});return bl(l.editor,l.installRuntimePlugins,()=>{t.current=l,e.focusEditorRef&&(e.focusEditorRef.current=l.focusEditor),e.searchControllerRef&&(e.searchControllerRef.current=l.searchController),s.current?.()},e=>{o.current?.(e)})},[e.portalContainer,e.contentPortalContainer,e.shortcutMode,e.focusEditorRef,e.searchControllerRef]);(0,c.useEffect)(()=>{a.current=e.onMarkdownChange},[e.onMarkdownChange]),(0,c.useEffect)(()=>{o.current=e.onInitError},[e.onInitError]),(0,c.useEffect)(()=>{s.current=e.onInitReady},[e.onInitReady]),(0,c.useEffect)(()=>{u.current=e.onSearchSnapshotChange},[e.onSearchSnapshotChange]),(0,c.useEffect)(()=>{d.loading||t.current?.setDebounceMs?.(e.debounceMs)},[d.loading,e.debounceMs]),(0,c.useEffect)(()=>{d.loading||t.current?.setReadOnly?.(e.readOnly)},[d.loading,e.readOnly]),(0,c.useEffect)(()=>()=>{t.current=null,e.focusEditorRef&&(e.focusEditorRef.current=null),e.searchControllerRef&&(e.searchControllerRef.current=null)},[e.portalContainer,e.contentPortalContainer,e.shortcutMode,e.focusEditorRef,e.searchControllerRef]),(0,c.useEffect)(()=>{d.loading||t.current?.updateLocalization(e.locale??`zh-CN`,e.messages??U(e.locale))},[d.loading,e.locale,e.messages]),(0,c.useEffect)(()=>{let r=t.current;!r||d.loading||e.markdown!==n.current&&(n.current=e.markdown,r.setMarkdown(e.markdown))},[d.loading,e.markdown])},Sl=160,Cl=120,wl={search:``,replace:``,caseSensitive:!1,wholeWord:!1,regexp:!1},Tl={current:0,total:0,isInvalidExpression:!1},El={"zh-CN":`只读`,"en-US":`Read only`},Dl=e=>e.length===0?`""`:`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\r\n|\r|\n/g,`\\A `)}"`,Ol=e=>(xl({markdown:e.markdown,portalContainer:e.portalContainer,contentPortalContainer:e.contentPortalContainer,focusEditorRef:e.focusEditorRef,searchControllerRef:e.searchControllerRef,readOnly:e.readOnly,debounceMs:e.debounceMs,messages:e.messages,locale:e.locale,slashMenu:e.slashMenu,imageUpload:e.imageUpload,shortcutMode:e.shortcutMode,onMarkdownChange:e.onMarkdownChange,onInitReady:e.onInitReady,onInitError:e.onInitError,onSearchSnapshotChange:e.onSearchSnapshotChange}),(0,g.jsx)(l.Milkdown,{})),kl=e=>{let[t,n]=(0,c.useState)(``),[r,i]=(0,c.useState)(null),[a,o]=(0,c.useState)(null),[s,f]=(0,c.useState)(!1),[p,m]=(0,c.useState)(!1),[h,_]=(0,c.useState)(wl),[v,y]=(0,c.useState)(Tl),b=(0,c.useRef)(null),x=(0,c.useRef)(null),S=(0,c.useRef)(null),C=(0,c.useRef)(s),w=(0,c.useRef)(h);C.current=s,w.current=h;let T=(0,c.useMemo)(()=>(0,d.debounce)(e=>{x.current?.updateQuery(e)},Cl),[]);(0,c.useEffect)(()=>()=>{T.cancel()},[T]);let E=e.theme??`light`,D=e.readOnly??!1,O=El[e.locale??`zh-CN`],k=e.debounceMs??Sl,A=e.shortcutMode??`modShift`,{markdown:j,setMarkdown:M}=xe(e.value,e.defaultValue,e.onChange),N=(0,c.useMemo)(()=>U(e.locale,e.messages,e.placeholder),[e.locale,e.messages,e.placeholder]),ee=(0,c.useMemo)(()=>({"--zt-gap-placeholder-content":Dl(N.placeholder),...e.maxHeight===void 0?{}:{maxHeight:e.maxHeight,overflowY:`auto`}}),[N.placeholder,e.maxHeight]),P=(0,c.useCallback)(e=>{M(e)},[M]),te=(0,c.useCallback)(()=>{n(``),C.current&&x.current?.updateQuery(w.current)},[]),ne=(0,c.useCallback)(e=>{n(e instanceof Error?e.message:N.initError)},[N.initError]),re=(0,c.useCallback)(e=>{if(D)return;let t=e.target;if(!(t instanceof Element))return;let n=t.closest(`.ProseMirror`);t.closest(`.zt-md-content-portal`)||n!==null&&t!==n||(e.preventDefault(),b.current?.({left:e.clientX,top:e.clientY}))},[D]),F=(0,c.useCallback)(e=>{i(e)},[]),I=(0,c.useCallback)(e=>{o(e)},[]),L=()=>{S.current?.focus(),S.current?.select()},ie=()=>{T.cancel(),f(!0),x.current?.updateQuery(h),requestAnimationFrame(L)},R=()=>{T.cancel();let e=x.current;e?.clear(),y(Tl),f(!1),m(!1),e&&requestAnimationFrame(e.focusCurrent)},ae=e=>{T.cancel(),_(e),x.current?.updateQuery(e)},z=e=>{let t={...h,search:e};_(t),T(t)},oe=e=>{ae({...h,replace:e})},se=e=>{ae({...h,[e]:!h[e]})},ce=()=>{m(e=>!e)},le=()=>{T.flush(),x.current?.findPrevious()},ue=()=>{T.flush(),x.current?.findNext()},de=()=>{T.flush(),x.current?.replaceCurrent()},B=()=>{T.flush(),x.current?.replaceAll()},fe=(0,c.useCallback)(e=>{y(e)},[]);return(0,g.jsxs)(`div`,{className:(0,u.default)(`zt-md`,E===`dark`?`zt-md-dark`:`zt-md-light`,e.className),"data-readonly":D?`true`:`false`,"data-search-open":s?`true`:`false`,"data-search-replace-expanded":!D&&p?`true`:`false`,"data-search-invalid":s&&v.isInvalidExpression?`true`:`false`,"data-readonly-label":O,onKeyDownCapture:e=>{if((e.ctrlKey||e.metaKey)&&!e.altKey&&!e.shiftKey&&e.key.toLowerCase()===`f`){e.preventDefault(),ie();return}if(!(!s||e.nativeEvent.isComposing)){if(e.key===`Escape`){e.preventDefault(),R();return}if(!(!(e.target instanceof HTMLInputElement&&e.target.closest(`.zt-md-search-panel`)!==null)||e.key!==`Enter`)){if(e.preventDefault(),e.shiftKey){le();return}ue()}}},children:[e.headerSlot?(0,g.jsx)(`div`,{className:`zt-md-header`,children:e.headerSlot}):null,(0,g.jsxs)(`div`,{className:`zt-md-body`,children:[t?(0,g.jsx)(`div`,{className:`zt-md-error`,children:t}):null,s?(0,g.jsx)(ye,{options:h,snapshot:v,messages:N,readOnly:D,isReplaceExpanded:p,searchInputRef:S,onSearchChange:z,onReplaceChange:oe,onOptionToggle:se,onReplaceExpandedToggle:ce,onFindPrevious:le,onFindNext:ue,onReplaceCurrent:de,onReplaceAll:B,onClose:R}):null,(0,g.jsxs)(`div`,{className:(0,u.default)(`zt-md-editor`,D?`zt-md-readonly`:`zt-md-editable`),"aria-label":N.editorAriaLabel,"aria-readonly":D,onMouseDown:re,style:ee,children:[r&&a?(0,g.jsx)(l.MilkdownProvider,{children:(0,g.jsx)(Ol,{markdown:j,locale:e.locale,portalContainer:r,contentPortalContainer:a,focusEditorRef:b,searchControllerRef:x,readOnly:D,debounceMs:k,messages:N,slashMenu:e.slashMenu,imageUpload:e.imageUpload,shortcutMode:A,onMarkdownChange:P,onInitReady:te,onInitError:ne,onSearchSnapshotChange:fe})}):null,(0,g.jsx)(`div`,{ref:I,className:`zt-md-content-portal`})]}),(0,g.jsx)(`div`,{ref:F,className:`zt-md-portal`})]})]})};exports.MilkdownEditor=kl;
|
|
21
|
+
`).lastIndexOf(`/`);if(a<0)return!1;let o=r+a,s=t.tr.delete(o,i);return e.dispatch(s.scrollIntoView()),!0},os=(e,t)=>{let n=t?`true`:`false`;e.dataset.selected=n,e.setAttribute(`aria-selected`,n)},ss=(e,t,n,r)=>{e.innerHTML=``;let i=[],a=``;return t.forEach((t,o)=>{if(t.group!==a){let n=document.createElement(`div`);n.className=`slash-menu-group`,n.textContent=t.group,e.appendChild(n),a=t.group}let s=document.createElement(`div`);s.className=`slash-menu-item`,s.setAttribute(`role`,`option`),s.dataset.command=t.command,s.dataset.index=String(o),os(s,o===n);let c=document.createElement(`span`);c.className=`slash-menu-item-icon`,t.icon&&(c.innerHTML=q(Pt(t.icon,`Circle`),{size:16,strokeWidth:2}));let l=document.createElement(`span`);l.className=`slash-menu-item-label`,l.textContent=t.label;let u=r[t.command],d=u?document.createElement(`kbd`):null;d&&(d.className=`slash-menu-item-shortcut`,d.textContent=u),s.appendChild(c),s.appendChild(l),d&&s.appendChild(d),e.appendChild(s),i.push(s)}),i},cs=(e,t)=>{let n=document.createElement(`div`);n.className=`slash-menu`,n.setAttribute(`role`,`listbox`),n.style.display=`none`,e.appendChild(n);let r=!1,i=``,a=-1,o=[],s=!1,c=null,l=_o(t),u=()=>{if(!r||!c)return;let{editorWrapper:t,anchorTopInContent:i,anchorBottomInContent:a,anchorLeftInContent:o,placement:s,offsetY:l}=c,u=pa({wrapper:t,anchor:{anchorTopInContent:i,anchorBottomInContent:a,anchorLeftInContent:o},overlaySize:{width:n.offsetWidth||210},placement:s,offsetY:l,boundaryInset:4},e);n.style.left=`${u.left}px`,n.style.top=`${u.top}px`,n.dataset.placement=s},d=ma(()=>{r&&u()}),f=()=>{n.style.top=``,n.style.left=``,n.style.transform=``,delete n.dataset.placement};return{menu:n,isVisible:()=>r,setVisible:(e,t)=>{if(r!==e){if(r=e,n.style.display=e?`block`:`none`,!e){d.unbindGlobal(),d.bindWrapper(null),f(),i=``,a=-1,o=[],s=!0;return}d.bindGlobal(),t&&(t(),s&&=(t(),!1))}},renderIfNeeded:(e,t)=>{let r=JSON.stringify(e.map(e=>[e.command,e.label,e.group,e.icon]));if(i!==r){o=ss(n,e,t,l),i=r,a=t;return}a!==t&&(a>=0&&o[a]&&os(o[a],!1),t>=0&&o[t]&&os(o[t],!0),a=t)},scrollActiveItemIntoView:e=>{let t=o[a]??null;t&&(t.scrollIntoView({block:`nearest`,inline:`nearest`}),e&&e())},updatePositionContext:e=>{c=e,d.bindWrapper(e?.editorWrapper??null)},updatePosition:u,destroy:()=>{d.destroy(),o=[],n.remove()}}},ls=(e,t)=>{if(!(!e||typeof e!=`object`))return e[t]},us=()=>{if(typeof me.slashFactory!=`function`)return console.error(`[zt-md/slash] slashFactory not found`),null;let e=(0,me.slashFactory)(`zt-md-slash`),t=Array.isArray(e)?e[0]:void 0,n=Array.isArray(e)?e[1]:e,r=Array.isArray(e)?e[2]:void 0;if(!n)return null;let i=Array.isArray(e)?e.filter((e,t)=>t<2&&e!=null):[n],a=ls(t,`key`)??ls(n,`key`)??ls(r,`key`)??ls(e,`key`);return i.length===0||a===void 0?null:{plugins:i,key:a}},ds=(e,t,n,r,i=`zh-CN`,a=`modShift`)=>{if(t?.enabled===!1)return{plugins:[],config:null};try{let o=us();if(!o)return{plugins:[],config:null};let s=$o(t,i),c=cs(e,a),l=0,u=null,d=s,f=!1,p=new Set([`ArrowDown`,`ArrowUp`,`Enter`,`Escape`]),m=e=>e.isComposing||!p.has(e.key)||!f?!1:e.key===`ArrowDown`?(e.preventDefault(),d.length===0?!0:(l=(l+1)%d.length,c.renderIfNeeded(d,l),c.scrollActiveItemIntoView(()=>{c.updatePosition()}),!0)):e.key===`ArrowUp`?(e.preventDefault(),d.length===0?!0:(l=(l-1+d.length)%d.length,c.renderIfNeeded(d,l),c.scrollActiveItemIntoView(()=>{c.updatePosition()}),!0)):e.key===`Enter`?(e.preventDefault(),_(),!0):e.key===`Escape`?(e.preventDefault(),c.setVisible(!1),!0):!1,h=e=>{let t=e?.state?.selection?.from;if(typeof t!=`number`)return null;let n=e?.coordsAtPos?.(t);return n?new DOMRect(n.left,n.top,Math.max(n.right-n.left,1),n.bottom-n.top):null},g=e=>{if(!Xo(e)){d=[],f=!1,c.updatePositionContext(null),c.setVisible(!1);return}let t=is(e,s);if(d=t.visibleItems,f=t.shouldShow,t.shouldShow&&l>=d.length&&(l=0),t.shouldShow&&!c.isVisible()&&(l=0),!t.shouldShow){c.updatePositionContext(null),c.setVisible(!1);return}let n=h(e),r=ca(e?.dom);if(n&&r){let e=la(n,320),t=ua(n,r);c.updatePositionContext({editorWrapper:r,anchorTopInContent:t.anchorTopInContent,anchorBottomInContent:t.anchorBottomInContent,anchorLeftInContent:t.anchorLeftInContent,placement:e,offsetY:8})}c.renderIfNeeded(d,l),c.isVisible()?c.updatePosition():c.setVisible(!0,()=>{c.updatePosition()})},_=()=>{if(!Xo(u)){f=!1,c.updatePositionContext(null),c.setVisible(!1);return}if(!u||l<0||l>=d.length)return;let t=d[l];if(as(u)){if(t.command===`image`){c.setVisible(!1),n&&sr({portalContainer:e,view:u,messages:n,imageUpload:r});return}Yo(u,t.command)&&(c.setVisible(!1),t.command===`mathBlock`&&queueMicrotask(()=>{let e=u?.dom?.querySelector?.(`.zt-md-math-block-editing .zt-md-math-block-textarea`);!e||document.activeElement===e||e.focus()}))}};return c.menu.addEventListener(`mousemove`,e=>{if(!f)return;let t=e.target?.closest(`.slash-menu-item`),n=Number(t?.dataset.index??-1);n>=0&&n<d.length&&n!==l&&(l=n,c.renderIfNeeded(d,l))}),c.menu.addEventListener(`mousedown`,e=>{e.preventDefault();let t=(e.target?.closest(`.slash-menu-item`))?.dataset.command??``;if(!t)return;let n=d.findIndex(e=>e.command===t);n<0||(l=n,_())}),{plugins:o.plugins,config:e=>{e.set(o.key,{props:{handleKeyDown:(e,t)=>m(t)},view:()=>({update:e=>{u=e,!e?.composing&&g(e)},destroy:()=>{u=null,f=!1,c.destroy()}})})},updateLocale:e=>{if(i===e)return;let n=d[l]?.command;if(i=e,s=$o(t,i),u){let e=is(u,s).visibleItems;l=Math.max(0,e.findIndex(e=>e.command===n)),g(u)}}}}catch(e){return console.error(`[zt-md/slash] init failed`,e),{plugins:[],config:null}}},fs=/Mac|iPhone|iPad|iPod/,ps=(e,t)=>(typeof navigator<`u`&&fs.test(navigator.platform)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey)?t===`modAlt`?e.altKey&&!e.shiftKey:e.shiftKey&&!e.altKey:!1,ms=(e,t,n,r)=>(sr({portalContainer:t,view:e,messages:n,imageUpload:r}),!0),hs=(e,t,n,r)=>{let i=uo(n),a=Object.fromEntries(Object.entries(i).map(([e,t])=>[t.code,e]));return(i,o)=>{if(o.isComposing||!ps(o,n)||!Xo(i))return!1;let s=a[o.code];if(!s)return!1;let c=s===`image`?ms(i,e,t,r):Yo(i,s);return c&&o.preventDefault(),c}},gs=`table`,_s=`ArrowUp`,vs=e=>e.key!==_s||e.defaultPrevented||e.altKey||e.ctrlKey||e.metaKey,ys=(e,t)=>{let n=t.nodeBefore;return!n||n.type.name!==gs?null:{tableNode:n,tableStart:e-n.nodeSize}},bs=e=>{if(e.parent.type.name!==`paragraph`||e.parentOffset!==0||e.parent.childCount>0||e.depth<1)return null;let t=e.index(e.depth-1);if(t<=0)return null;let n=e.node(e.depth-1).child(t-1);return n.type.name===gs?{tableNode:n,tableStart:e.before(e.depth)-n.nodeSize}:null},xs=(e,t)=>{if(e.childCount===0)return null;let n=e.childCount-1,r=e.child(n);if(r.childCount===0)return null;let i=0;for(let t=0;t<n;t+=1)i+=e.child(t).nodeSize;let a=r.childCount-1,o=r.child(a),s=0;for(let e=0;e<a;e+=1)s+=r.child(e).nodeSize;return t+1+i+1+s+o.nodeSize-1},Ss=e=>{let{selection:t}=e.state,n=t.$from,r=null;if(t instanceof L.GapCursor?r=ys(t.from,n):t.empty&&(r=bs(n)),!r)return!1;let i=xs(r.tableNode,r.tableStart);if(i===null)return!1;let a=e.state.tr.setSelection(v.TextSelection.near(e.state.doc.resolve(i),-1)).scrollIntoView();return e.dispatch(a),e.focus(),!0},Cs=(0,I.$prose)(()=>new v.Plugin({key:new v.PluginKey(`zt-md-table-arrow-entry`),props:{handleKeyDown:(e,t)=>vs(t)?!1:Ss(e)}})),ws=`table`,Ts=`table_header_row`,Es=`table_row`,Ds=`table_header`,Os=`table_cell`,ks=e=>{let t=e.selection.$from,n=-1,r=-1;for(let e=t.depth;e>=0;--e){let i=t.node(e);if(r<0&&(i.type.name===Os||i.type.name===Ds)&&(r=t.index(e-1)),n<0&&(i.type.name===Es||i.type.name===Ts)&&(n=t.index(e-1)),i.type.name===ws)return{tableNode:i,tableStart:e===0?0:t.before(e),tableNodeSize:i.nodeSize,rowIndex:n,columnIndex:r}}return null},As=(e,t,n,r)=>{if(n<0||n>=e.childCount)return null;let i=0;for(let t=0;t<n;t+=1)i+=e.child(t).nodeSize;let a=e.child(n);if(r<0||r>=a.childCount)return null;let o=0;for(let e=0;e<r;e+=1)o+=a.child(e).nodeSize;return t+1+i+1+o+1+1},js=e=>{if(e.columnIndex<0||e.tableNode.childCount===0)return!1;let t=e.tableNode.child(0);return e.columnIndex<t.childCount},Ms=(e,t,n,r)=>{let i=As(t.tableNode,t.tableStart,n,r);if(i===null)return!1;let a=e.state.tr.setSelection(v.TextSelection.near(e.state.tr.doc.resolve(i),1));return e.dispatch(a),!0},Ns=(e,t)=>t(e.state,e.dispatch,e)?(e.dispatch(e.state.tr.scrollIntoView()),e.focus(),!0):!1,Ps=(e,t,n)=>t.rowIndex<0||t.columnIndex<0||!Ms(e,t,t.rowIndex,t.columnIndex)?!1:Ns(e,n===`above`?he.addRowBefore:he.addRowAfter),Fs=(e,t)=>t.rowIndex<=0||t.columnIndex<0||!Ms(e,t,t.rowIndex,t.columnIndex)?!1:Ns(e,he.deleteRow),Is=(e,t,n)=>t.rowIndex<0||t.columnIndex<0||!Ms(e,t,t.rowIndex,t.columnIndex)?!1:Ns(e,n===`left`?he.addColumnBefore:he.addColumnAfter),Ls=(e,t)=>t.rowIndex<0||t.columnIndex<0||(t.tableNode.childCount>0?t.tableNode.child(0).childCount:0)<=1||!Ms(e,t,t.rowIndex,t.columnIndex)?!1:Ns(e,he.deleteColumn),Rs=(e,t,n)=>{if(t.columnIndex<0)return!1;let r=he.TableMap.get(t.tableNode),i=t.tableStart+1,a=t.columnIndex,o=e.state.tr;for(let e=0;e<r.height;e+=1){let t=e*r.width+a,s=r.map[t];if(typeof s!=`number`)continue;let c=i+s,l=o.doc.nodeAt(c);if(!l)continue;let u={...l.attrs,alignment:n};o.setNodeMarkup(c,l.type,u,l.marks)}return o.docChanged?(o.scrollIntoView(),e.dispatch(o),e.focus(),!0):!1},zs=e=>{let t=ks(e.state);!t||t.rowIndex<=0||Fs(e,t)},Bs=e=>{let t=ks(e.state);!t||t.rowIndex<0||t.columnIndex<0||Ls(e,t)},Vs=e=>{let[t,n]=(0,c.useState)(!1),r=ga({open:t,portalContainer:e.portalContainer,editorWrapper:e.collisionBoundary,horizontalAlign:`start`,offsetY:10,fallbackWidth:156,fallbackHeight:240,onOutside:()=>n(!1)}),i=e=>{e.preventDefault()},a=()=>{if(t){n(!1);return}r.updatePosition(),n(!0)},o=e=>{e(),n(!1)},s=[{key:`insert-row-above`,label:e.messages.tableInsertRowAboveLabel,icon:f.ArrowUpToLine,disabled:!e.canInsertRowAbove,onAction:e.onInsertRowAbove},{key:`insert-row-below`,label:e.messages.tableInsertRowBelowLabel,icon:f.ArrowDownToLine,onAction:e.onInsertRowBelow},{key:`insert-column-left`,label:e.messages.tableInsertColumnLeftLabel,icon:f.ArrowLeftToLine,disabled:!e.canInsertColumn,onAction:e.onInsertColumnLeft},{key:`insert-column-right`,label:e.messages.tableInsertColumnRightLabel,icon:f.ArrowRightToLine,disabled:!e.canInsertColumn,onAction:e.onInsertColumnRight}],l=[{key:`delete-row`,label:e.messages.tableDeleteRowLabel,icon:f.Trash2,disabled:!e.canDeleteRow,danger:!0,onAction:e.onDeleteRow},{key:`delete-column`,label:e.messages.tableDeleteColumnLabel,icon:f.Trash2,disabled:!e.canDeleteColumn,danger:!0,onAction:e.onDeleteColumn}],u=e=>(0,c.createElement)(H,{key:e.key,type:`button`,variant:`ghost`,size:`sm`,className:e.danger?`zt-md-table-action-menu-item zt-md-table-action-menu-item-danger disabled:pointer-events-auto disabled:cursor-not-allowed`:`zt-md-table-action-menu-item disabled:pointer-events-auto disabled:cursor-not-allowed`,disabled:e.disabled,onMouseDown:i,onClick:()=>o(e.onAction)},(0,c.createElement)(e.icon,{size:14,strokeWidth:1.8,className:`zt-md-table-action-menu-item-icon`,"aria-hidden":`true`}),(0,c.createElement)(`span`,{className:`zt-md-table-action-menu-item-label`},e.label));return(0,c.createElement)(c.Fragment,null,(0,c.createElement)(`button`,{ref:r.triggerRef,type:`button`,className:`zt-md-table-action-button`,"aria-label":e.messages.tableMoreAriaLabel,"aria-expanded":t,onMouseDown:i,onClick:a},(0,c.createElement)(f.EllipsisVertical,{size:15,strokeWidth:2,"aria-hidden":`true`})),(0,c.createElement)(_a,{panel:r,portalContainer:e.portalContainer,className:`zt-md-table-action-popover`,onMouseDown:i},(0,c.createElement)(`div`,{className:`zt-md-table-action-menu-group`},...s.map(u)),(0,c.createElement)(`div`,{className:`zt-md-table-action-menu-divider`,"aria-hidden":`true`}),(0,c.createElement)(`div`,{className:`zt-md-table-action-menu-group`},...l.map(u))))},Hs=`zt-md-table-focus-actions`,Us=8,Ws=8,Gs=`left`,Ks=q(`Trash2`,{size:15,strokeWidth:2}),qs=q(`AlignLeft`,{size:15,strokeWidth:2}),Js=q(`AlignCenter`,{size:15,strokeWidth:2}),Ys=q(`AlignRight`,{size:15,strokeWidth:2}),Xs=e=>typeof e.props.editable==`function`?e.props.editable(e.state):e.editable,Zs=e=>{let{selection:t,doc:n}=e.state;return t.empty||!(t instanceof v.TextSelection)?!1:n.textBetween(t.from,t.to).trim().length>0},Qs=()=>{let e=document.createElement(`span`);return e.className=`zt-md-table-actions-divider`,e.setAttribute(`aria-hidden`,`true`),e},$s=(e,t,n)=>t<0||n<0?null:e.rows.item(t)?.cells.item(n)??null,ec=class{constructor(e,t,n){this.isAttached=!1,this.messageVersion=0,this.lastMoreActionsKey=``,this.currentTableStart=null,this.currentTableNodeSize=null,this.currentColumnIndex=null,this.currentColumnAlignment=Gs,this.currentAnchorElement=null,this.currentTableWrapper=null,this.hasPositionContext=!1,this.repositionScheduler=ma(()=>{this.hasPositionContext&&this.updateOverlayPosition()}),this.handleActionsMouseDown=e=>{e.preventDefault()},this.handleTableWrapperScroll=()=>{this.repositionScheduler.schedule()},this.handleDeleteClick=e=>{if(e.preventDefault(),this.currentTableStart===null||this.currentTableNodeSize===null)return;let t=this.currentTableStart,n=this.currentTableStart+this.currentTableNodeSize,r=this.view.state.tr.delete(t,n).scrollIntoView();this.view.dispatch(r),this.view.focus()},this.handleAlignLeftClick=()=>{this.applyColumnAlignment(`left`)},this.handleAlignCenterClick=()=>{this.applyColumnAlignment(`center`)},this.handleAlignRightClick=()=>{this.applyColumnAlignment(`right`)},this.handleInsertRowBelow=()=>{let e=ks(this.view.state);!e||e.rowIndex<0||Ps(this.view,e,`below`)},this.handleInsertRowAbove=()=>{let e=ks(this.view.state);!e||e.rowIndex<=0||Ps(this.view,e,`above`)},this.handleInsertColumnLeft=()=>{this.insertColumn(`left`)},this.handleInsertColumnRight=()=>{this.insertColumn(`right`)},this.handleDeleteRow=()=>{zs(this.view)},this.handleDeleteColumn=()=>{Bs(this.view)},this.view=e,this.messages=t,this.portalContainer=n,this.editorWrapper=ca(e.dom),this.actionsContainer=document.createElement(`div`),this.actionsContainer.className=`zt-md-table-actions-overlay`,this.deleteButton=document.createElement(`button`),this.deleteButton.type=`button`,this.deleteButton.className=`zt-md-table-action-button zt-md-table-action-button-danger`,this.deleteButton.style.display=`inline-flex`,this.deleteButton.setAttribute(`aria-label`,t.tableDeleteAriaLabel),this.deleteButton.innerHTML=Ks,this.alignLeftButton=this.createColumnAlignmentButton(t.tableAlignLeftAriaLabel,qs),this.alignCenterButton=this.createColumnAlignmentButton(t.tableAlignCenterAriaLabel,Js),this.alignRightButton=this.createColumnAlignmentButton(t.tableAlignRightAriaLabel,Ys),this.moreActionsMount=document.createElement(`span`),this.moreActionsMount.className=`zt-md-table-more-actions-mount`,this.moreActionsRoot=(0,oe.createRoot)(this.moreActionsMount),this.actionsContainer.append(this.moreActionsMount,Qs(),this.alignLeftButton,this.alignCenterButton,this.alignRightButton,Qs(),this.deleteButton),this.actionsContainer.addEventListener(`mousedown`,this.handleActionsMouseDown),this.deleteButton.addEventListener(`click`,this.handleDeleteClick),this.alignLeftButton.addEventListener(`click`,this.handleAlignLeftClick),this.alignCenterButton.addEventListener(`click`,this.handleAlignCenterClick),this.alignRightButton.addEventListener(`click`,this.handleAlignRightClick),this.update(e),this.stopObservingMessages=W(t,()=>{this.messageVersion+=1,this.deleteButton.setAttribute(`aria-label`,t.tableDeleteAriaLabel),this.alignLeftButton.setAttribute(`aria-label`,t.tableAlignLeftAriaLabel),this.alignCenterButton.setAttribute(`aria-label`,t.tableAlignCenterAriaLabel),this.alignRightButton.setAttribute(`aria-label`,t.tableAlignRightAriaLabel),this.isAttached&&this.update(this.view)})}bindTableWrapperScroll(e){let t=e.closest(`.tableWrapper`);this.currentTableWrapper!==t&&(this.unbindTableWrapperScroll(),this.currentTableWrapper=t,this.currentTableWrapper&&this.currentTableWrapper.addEventListener(`scroll`,this.handleTableWrapperScroll,{passive:!0}))}unbindTableWrapperScroll(){this.currentTableWrapper&&=(this.currentTableWrapper.removeEventListener(`scroll`,this.handleTableWrapperScroll),null)}createColumnAlignmentButton(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`zt-md-table-action-button`,n.style.display=`inline-flex`,n.setAttribute(`aria-label`,e),n.innerHTML=t,n}resolveColumnAlignment(e){return e===`center`||e===`right`?e:Gs}updateAlignmentButtonsState(e){this.alignLeftButton.disabled=!e,this.alignCenterButton.disabled=!e,this.alignRightButton.disabled=!e,this.alignLeftButton.classList.toggle(`zt-md-table-action-button-active`,e&&this.currentColumnAlignment===`left`),this.alignCenterButton.classList.toggle(`zt-md-table-action-button-active`,e&&this.currentColumnAlignment===`center`),this.alignRightButton.classList.toggle(`zt-md-table-action-button-active`,e&&this.currentColumnAlignment===`right`)}applyColumnAlignment(e){let t=ks(this.view.state);!t||t.rowIndex<0||t.columnIndex<0||Rs(this.view,t,e)}insertColumn(e){let t=ks(this.view.state);!t||t.rowIndex<0||t.columnIndex<0||Is(this.view,t,e)}renderMoreActions(e,t,n,r){let i=`${this.messageVersion}:${e}:${t}:${n}:${r}`;this.lastMoreActionsKey!==i&&(this.lastMoreActionsKey=i,this.moreActionsRoot.render((0,c.createElement)(Vs,{messages:this.messages,portalContainer:this.portalContainer,collisionBoundary:this.editorWrapper,canInsertRowAbove:e,canInsertColumn:t,canDeleteRow:n,canDeleteColumn:r,onInsertRowAbove:this.handleInsertRowAbove,onInsertRowBelow:this.handleInsertRowBelow,onInsertColumnLeft:this.handleInsertColumnLeft,onInsertColumnRight:this.handleInsertColumnRight,onDeleteRow:this.handleDeleteRow,onDeleteColumn:this.handleDeleteColumn})))}resolveTableElement(e){if(e instanceof HTMLTableElement)return e;let t=e.querySelector(`table`);return t instanceof HTMLTableElement?t:null}resolveActionsContainerSize(){let e=this.actionsContainer.getBoundingClientRect();return e.width<=0||e.height<=0?null:{width:e.width,height:e.height}}updateOverlayPosition(){if(!this.editorWrapper||!this.currentAnchorElement||this.actionsContainer.parentElement!==this.portalContainer)return;let e=this.resolveActionsContainerSize();if(!e)return;let t=this.currentAnchorElement.getBoundingClientRect(),n=this.editorWrapper.getBoundingClientRect(),r=t.top-n.top,i=n.bottom-t.bottom,a=r>=e.height+Us+Ws||r>=i?`top`:`bottom`,o=ua(t,this.editorWrapper,n),s=pa({wrapper:this.editorWrapper,anchor:o,overlaySize:e,placement:a,horizontalAlign:`center`,offsetY:Us,boundaryInset:Ws},this.portalContainer,n);this.actionsContainer.style.left=`${s.left}px`,this.actionsContainer.style.top=`${s.top}px`}update(e){if(this.view=e,e.composing)return;if(!this.editorWrapper||!Xs(e)||Zs(e)){this.detach();return}let t=ks(e.state);if(!t){this.detach();return}let n=e.nodeDOM(t.tableStart);if(!(n instanceof HTMLElement)){this.detach();return}let r=this.resolveTableElement(n);if(!r){this.detach();return}let i=this.isAttached;this.isAttached||(this.isAttached=!0,this.repositionScheduler.bindGlobal(),this.repositionScheduler.bindWrapper(this.editorWrapper)),this.actionsContainer.parentElement!==this.portalContainer&&this.portalContainer.append(this.actionsContainer);let a=js(t),o=a&&t.tableNode.child(0).childCount>1,s=t.rowIndex>0,c=t.rowIndex>0,l=t.tableNode.childCount>0?t.tableNode.child(0):null;this.currentColumnIndex=a?t.columnIndex:null,this.currentColumnAlignment=this.resolveColumnAlignment(this.currentColumnIndex===null?null:l?.maybeChild(this.currentColumnIndex)?.attrs?.alignment),this.updateAlignmentButtonsState(a),this.renderMoreActions(s,a,c,o),this.bindTableWrapperScroll(r),this.currentAnchorElement=$s(r,t.rowIndex,t.columnIndex)??r,this.currentTableStart=t.tableStart,this.currentTableNodeSize=t.tableNodeSize,this.hasPositionContext=!0,i?this.repositionScheduler.schedule():this.updateOverlayPosition()}detach(){this.isAttached&&(this.isAttached=!1,this.repositionScheduler.unbindGlobal(),this.repositionScheduler.bindWrapper(null),this.unbindTableWrapperScroll(),this.lastMoreActionsKey=``,this.moreActionsRoot.render(null),this.actionsContainer.remove(),this.currentAnchorElement=null,this.currentTableStart=null,this.currentTableNodeSize=null,this.currentColumnIndex=null,this.currentColumnAlignment=Gs,this.updateAlignmentButtonsState(!1),this.hasPositionContext=!1)}destroy(){this.stopObservingMessages(),this.detach(),this.repositionScheduler.destroy(),this.moreActionsRoot.unmount(),this.actionsContainer.removeEventListener(`mousedown`,this.handleActionsMouseDown),this.deleteButton.removeEventListener(`click`,this.handleDeleteClick),this.alignLeftButton.removeEventListener(`click`,this.handleAlignLeftClick),this.alignCenterButton.removeEventListener(`click`,this.handleAlignCenterClick),this.alignRightButton.removeEventListener(`click`,this.handleAlignRightClick)}},tc=(e,t)=>{let n=t??U();return(0,I.$prose)(()=>new v.Plugin({key:new v.PluginKey(Hs),view:t=>new ec(t,n,e)}))},nc=`list_item`,rc=`li[data-item-type="task"]`,ic=24,ac=(e,t)=>{let n=t.getBoundingClientRect();return e.clientX>=n.left&&e.clientX<=n.left+ic&&e.clientY>=n.top&&e.clientY<=n.top+ic},oc=e=>{if(!(e instanceof Element))return null;let t=e.closest(rc);return t instanceof HTMLElement?t:null},sc=(e,t)=>{if(!e.editable)return!1;let n=oc(t.target);return!n||!ac(t,n)?!1:(t.preventDefault(),!0)},cc=(e,t)=>{let n=e.posAtDOM(t,0)-1,r=e.state.doc.nodeAt(n);return!r||r.type.name!==nc||r.attrs.checked==null?!1:(e.dispatch(e.state.tr.setNodeMarkup(n,void 0,{...r.attrs,checked:!r.attrs.checked})),!0)},lc=(0,I.$prose)(()=>new v.Plugin({props:{handleDOMEvents:{mousedown:(e,t)=>sc(e,t),dblclick:(e,t)=>sc(e,t),click:(e,t)=>{if(!e.editable)return!1;let n=oc(t.target);return!n||!ac(t,n)||!cc(e,n)?!1:(t.preventDefault(),!0)}}}})),uc=`MILKDOWN_KEEP_LIST_ORDER`,dc=`table`,fc=(e,t,n=1)=>{let r=`${t+n}.`;return e.label===r?!1:(e.label=r,!0)},pc=(e,t,n,r,i)=>{let a=Math.max(0,Math.min(e.content.size,t)),o=e.resolve(a);for(let e=1;e<=o.depth;e+=1){let t=o.node(e);if(t.type===n||t.type===r){i.set(o.before(e),t);return}}},mc=(e,t,n,r)=>{let i=new Map,a=e.content.findDiffStart(t.content);if(a==null)return i;let o=e.content.findDiffEnd(t.content);if(!o)return i;let s=Math.max(o.b,a);return pc(t,a,n,r,i),s>a&&(pc(t,s,n,r,i),t.nodesBetween(a,s,(e,t)=>e.type===n||e.type===r?(i.set(t,e),!1):!(e.isTextblock||e.type.name===dc))),i},hc=(0,I.$prose)(e=>{let t=C.orderedListSchema.type(e),n=C.bulletListSchema.type(e),r=C.listItemSchema.type(e),i=(e,a,o,s,c)=>{if(e.type===n){let n=e.maybeChild(0);if(n?.type===r&&n.attrs.listType===`ordered`){let n=c();n.setNodeMarkup(a,t,{spread:!0}),e.forEach((t,o,s)=>{let l=a+1+o;if(t.type===r){let e={...t.attrs};fc(e,s)&&n.setNodeMarkup(l,void 0,e),t.forEach((e,n,r)=>{i(e,l+1+n,t,r,c)});return}i(t,l,e,s,c)});return}}else if(e.type===r&&o?.type===t){let t={...e.attrs},n=!1;t.listType!==`ordered`&&(t.listType=`ordered`,n=!0),o.maybeChild(0)&&fc(t,s,typeof o.attrs.order==`number`?o.attrs.order:1)&&(n=!0),n&&c().setNodeMarkup(a,void 0,t)}e.isTextblock||e.type.name===dc||e.forEach((t,n,r)=>{i(t,a+1+n,e,r,c)})};return new v.Plugin({key:new v.PluginKey(uc),appendTransaction:(e,r,a)=>{if(!a.selection||!e.some(e=>e.docChanged)||e.some(e=>e.getMeta(`addToHistory`)===!1||!e.isGeneric))return null;let o=mc(r.doc,a.doc,t,n);if(o.size===0)return null;let s=null,c=()=>(s||=a.tr,s);return o.forEach((e,t)=>{let n=a.doc.resolve(t);i(e,t,n.parent,n.index(),c)}),s?s.setMeta(`addToHistory`,!1):null}})}),gc=`Tab`,_c=4,vc=/^ */,yc=`list_item`,bc=e=>typeof e.props.editable==`function`?e.props.editable(e.state):e.editable,xc=e=>{let{$from:t}=e.selection;for(let e=t.depth;e>=0;--e){let n=t.node(e);if(n.type.name===yc)return n.type}return null},Sc=e=>{let{selection:t,doc:n}=e;if(t.empty)return[t.$from.start()];let r=new Set;return n.nodesBetween(t.from,t.to,(e,t)=>{e.isTextblock&&r.add(t+1)}),Array.from(r)},Cc=(e,t)=>{let{state:n}=e,r=` `.repeat(_c),i=Sc(n).sort((e,t)=>t-e),a=n.tr;return n.selection.empty?a.insertText(r,n.selection.to):i.forEach(e=>{a.insertText(r,e)}),a.docChanged?(t.preventDefault(),e.dispatch(a),!0):!1},wc=(e,t)=>{let{state:n}=e,{selection:r}=n;if(!(r instanceof v.TextSelection))return!1;let i=Sc(n).sort((e,t)=>t-e),a=n.tr;return i.forEach(e=>{let t=n.doc.resolve(e).parent.textContent.match(vc)?.[0].length??0,r=Math.min(t,_c);r<=0||a.delete(e,e+r)}),a.docChanged?(t.preventDefault(),e.dispatch(a),!0):!1},Tc=(0,I.$prose)(()=>new v.Plugin({key:new v.PluginKey(`zt-md-tab-space-indent`),props:{handleKeyDown:(e,t)=>{let n=e;if(!bc(n)||t.defaultPrevented||t.key!==gc||t.altKey||t.ctrlKey||t.metaKey)return!1;let r=xc(n.state);if(r){let e=(t.shiftKey?(0,pe.liftListItem)(r):(0,pe.sinkListItem)(r))(n.state,n.dispatch);return t.preventDefault(),e||!0}return t.shiftKey?wc(n,t):Cc(n,t)}}})),Ec=e=>{let t=(e instanceof Element?e:e.parentElement)?.closest(`code`);return t instanceof HTMLElement&&!t.closest(`pre`)?t:null},Dc=(e,t,n)=>Ec(e.domAtPos(t,n).node),Oc=e=>{let t=e.ownerDocument.createTreeWalker(e,NodeFilter.SHOW_TEXT),n=t.nextNode(),r=null;for(;n;)n.data.length>0&&(r=n),n=t.nextNode();return r},kc=(e,t,n)=>{let r=e.domAtPos(t,n);e.dom.ownerDocument.getSelection()?.collapse(r.node,r.offset)},Ac=(e,t)=>{let n=e.domAtPos(t,-1),r=Ec(n.node),i=e.dom.ownerDocument.getSelection();if(!r){i?.collapse(n.node,n.offset);return}let a=Oc(r);if(!a){let e=r.childNodes.length;i?.collapse(r,e);return}let o=a.data.length;i?.collapse(a,o)},jc={left:{inwardKey:`ArrowRight`,outwardKey:`ArrowLeft`},right:{inwardKey:`ArrowLeft`,outwardKey:`ArrowRight`}},Mc={left:`nodeAfter`,right:`nodeBefore`},Nc=(e,t)=>{e.dispatch(e.state.tr.setMeta(t,null))},Pc=(e,t,n,r,i)=>{if(t.key===`ArrowRight`)return Nc(e,i),!1;if(t.key!==`ArrowLeft`)return!1;t.preventDefault();let a=(e.state.storedMarks??e.state.selection.$from.marks()).filter(e=>e.type!==n);return e.dispatch(e.state.tr.setStoredMarks(a).setMeta(i,{...r,placement:`outside`})),!0},Fc=(e,t,n,r,i)=>{if(r.placement===`inside`)return Pc(e,t,n,r,i);let a=jc[r.side];if(t.key===a.outwardKey)return Nc(e,i),!1;if(t.key!==a.inwardKey)return!1;let o=Mc[r.side],s=e.state.selection.$from[o],c=s?n.isInSet(s.marks):null;if(!c)return Nc(e,i),!1;t.preventDefault();let l=e.state.storedMarks??e.state.selection.$from.marks(),u=c.addToSet(l);return e.dispatch(e.state.tr.setSelection(v.TextSelection.create(e.state.doc,r.position)).setStoredMarks(u).setMeta(i,r.side===`left`?{...r,placement:`inside`}:null)),r.side===`right`&&Ac(e,r.position),!0},Q=(e,t)=>!!t.isInSet(e),Ic=(e,t,n)=>{let r=e.state.doc.resolve(t),i=r.nodeBefore,a=r.nodeAfter;return!a||Q(i?.marks??[],n)||!Q(a.marks,n)?null:n.isInSet(a.marks)},Lc=(e,t,n)=>{let r=e.state.doc.resolve(t),i=r.nodeBefore,a=r.nodeAfter;return!i||!Q(i.marks,n)||Q(a?.marks??[],n)?null:n.isInSet(i.marks)},$=new v.PluginKey(`zt-md-inline-code-boundary-navigation`),Rc=`inlineCode`,zc=2,Bc=(e,t,n,r)=>{let i=t>0?[t,t-1]:[t];for(let[t,a]of i.entries()){let i=Lc(e,a,r);if(!i)continue;let o=e.state.doc.resolve(a).nodeAfter;if(o!==null&&!o.isText)continue;let s=Dc(e,a,-1);if(!s)continue;let c=n<=s.getBoundingClientRect().right+zc;if(!(t>0&&!c))return{boundaryPosition:a,inlineCodeMark:i,rightPlainTextNode:o,codeElement:s}}return null},Vc=(e,t)=>{if(t.button!==0||t.altKey||t.ctrlKey||t.metaKey||t.shiftKey||!e.editable)return!1;let n=e.posAtCoords({left:t.clientX,top:t.clientY}),r=e.state.schema.marks[Rc];if(!n||!r)return!1;let i=n.pos,a=e.state.doc.resolve(i),o=Ic(e,i,r),s=a.nodeBefore;if(o&&(!s||s.isText)){let n=Dc(e,i,1);if(!n)return!1;let c=n.getBoundingClientRect(),l=t.clientX>=c.left,u=(s?.marks??a.marks()).filter(e=>e.type!==r),d=l?o.addToSet(a.marks()):u,f=l?{position:i,side:`left`,placement:`inside`}:null;return t.preventDefault(),e.dispatch(e.state.tr.setSelection(v.TextSelection.create(e.state.doc,i)).setStoredMarks(d).setMeta($,f)),e.focus(),l||kc(e,i,-1),!0}let c=Bc(e,i,t.clientX,r);if(!c)return!1;let l=c.boundaryPosition,u=e.state.doc.resolve(l),d=c.codeElement.getBoundingClientRect(),f=t.clientX>=d.right,p=(c.rightPlainTextNode?.marks??u.marks()).filter(e=>e.type!==r),m=f?p:c.inlineCodeMark.addToSet(u.marks()),h=f?{position:l,side:`right`,placement:`outside`}:null;return t.preventDefault(),e.dispatch(e.state.tr.setSelection(v.TextSelection.create(e.state.doc,l)).setStoredMarks(m).setMeta($,h)),e.focus(),f||Ac(e,l),!0},Hc=`inlineCode`,Uc=`zt-md-inline-code-boundary-indicator`,Wc=`zt-md-inline-code-boundary-indicator-widget`,Gc=`zt-md-inline-code-boundary-active`,Kc={left:-1,right:1},qc={left:1,right:-1},Jc=e=>{let t=document.createElement(`span`);return t.className=Uc,t.dataset.side=e.side,t.dataset.placement=e.placement,t.contentEditable=`false`,t.setAttribute(`aria-hidden`,`true`),t},Yc=(e,t)=>{if(t.placement===`outside`)return[];let n=e.schema.marks[Hc],r=e.doc.resolve(t.position).nodeAfter,i=r&&n?n.isInSet(r.marks):null;return i?[i]:null},Xc=e=>{let t=$.getState(e);if(!t)return F.DecorationSet.empty;let n=Yc(e,t);if(!n)return F.DecorationSet.empty;let r=t.placement===`inside`?1:Kc[t.side],i=Jc(t),a=F.Decoration.widget(t.position,i,{side:r,marks:n,key:`${Wc}-${t.side}-${t.placement}`,ignoreSelection:!0,relaxedSide:!0});return F.DecorationSet.create(e.doc,[a])},Zc=(e,t)=>{if(t?.placement!==`outside`)return;let n=e.dom.querySelector(`.${Uc}[data-side='${t.side}'][data-placement='outside']`),r=qc[t.side],i=Dc(e,t.position,r);if(!n||!i)return;let a=n.getBoundingClientRect().left,o=i.getBoundingClientRect(),s=t.side===`left`?o.left-1:o.right+1,c=Math.round(s-a);n.style.setProperty(`--zt-md-inline-code-boundary-offset-x`,`${c}px`)},Qc=`inlineCode`,$c=(e,t)=>{let{selection:n}=e.state;if(!n.empty)return!1;let r=n.$from.nodeBefore,i=n.$from.nodeAfter;return!!(r&&Q(r.marks,t)&&(!i||!Q(i.marks,t)))},el=(e,t)=>{let{selection:n}=e.state;if(!n.empty)return!1;let r=n.$from.nodeBefore,i=n.$from.nodeAfter;return!!(i&&Q(i.marks,t)&&(!r||!Q(r.marks,t)))},tl=(e,t,n)=>{let r=Ic(e,t,n);if(!r)return!1;let i=e.state.storedMarks??e.state.doc.resolve(t).marks(),a=r.addToSet(i);return e.dispatch(e.state.tr.setSelection(v.TextSelection.create(e.state.doc,t)).setStoredMarks(a).setMeta($,{position:t,side:`left`,placement:`inside`})),!0},nl=(e,t)=>t.defaultPrevented||t.altKey||t.ctrlKey||t.metaKey||t.shiftKey||!e.editable,rl=(e,t)=>{let{selection:n}=e.state;if(!n.empty)return null;let r=n.$from.nodeBefore;return!r||!Q(r.marks,t)?null:Array.from(r.textContent).length===1?n.from-r.nodeSize:null},il=(e,t,n)=>{if(t.key!==`ArrowLeft`)return!1;let r=rl(e,n);if(r===null)return!1;let i=e.state.storedMarks??e.state.selection.$from.marks();return Q(i,n)?(t.preventDefault(),e.dispatch(e.state.tr.setSelection(v.TextSelection.create(e.state.doc,r)).setStoredMarks(i).setMeta($,{position:r,side:`left`,placement:`inside`})),!0):!1},al=(e,t,n)=>{if(!el(e,n))return!1;let r=e.state.storedMarks??e.state.selection.$from.marks();if(!Q(r,n))return fl(e),!1;t.preventDefault();let i=r.filter(e=>e.type!==n);return e.dispatch(e.state.tr.setStoredMarks(i).setMeta($,{position:e.state.selection.from,side:`left`,placement:`outside`})),kc(e,e.state.selection.from,-1),!0},ol=(e,t,n)=>{if(t.key!==`ArrowLeft`||!$c(e,n))return!1;let r=e.state.storedMarks??e.state.selection.$from.marks();return Q(r,n)?!1:(t.preventDefault(),e.dispatch(e.state.tr.setStoredMarks(r).setMeta($,{position:e.state.selection.from,side:`right`,placement:`outside`})),kc(e,e.state.selection.from,1),!0)},sl=(e,t)=>{let{selection:n}=e.state;if(!n.empty)return null;let r=n.$from.nodeBefore;if(!r?.isText||Q(r.marks,t)||Array.from(r.textContent).length!==1)return null;let i=n.from-r.nodeSize;return Lc(e,i,t)?i:null},cl=(e,t,n)=>{if(t.key!==`ArrowLeft`)return!1;let r=sl(e,n);if(r===null)return!1;let i=(e.state.selection.$from.nodeBefore?.marks??[]).filter(e=>e.type!==n);return t.preventDefault(),e.dispatch(e.state.tr.setSelection(v.TextSelection.create(e.state.doc,r)).setStoredMarks(i).setMeta($,{position:r,side:`right`,placement:`outside`})),kc(e,r,1),!0},ll=(e,t,n)=>cl(e,t,n)||ol(e,t,n)||il(e,t,n)||al(e,t,n),ul=()=>null,dl=(e,t)=>{let n=e.getMeta($);return n===void 0?e.docChanged||e.selectionSet||e.storedMarksSet?null:t:n},fl=e=>{$.getState(e.state)!=null&&e.dispatch(e.state.tr.setMeta($,null))},pl=e=>(fl(e),!1),ml=class{constructor(e){this.isBoundaryActive=!1,this.editorDom=e.dom,this.update(e)}update(e){if(e.composing)return;let t=$.getState(e.state),n=t!=null;n!==this.isBoundaryActive&&(this.isBoundaryActive=n,this.editorDom.classList.toggle(Gc,n)),Zc(e,t)}destroy(){this.editorDom.classList.remove(Gc)}},hl=e=>new ml(e),gl=e=>{if(!(e instanceof Element))return!1;let t=e.closest(`code`);return!!(t&&!t.closest(`pre`))},_l=(e,t,n)=>{if(!e.state.selection.empty)return!1;if(Vc(e,n))return!0;let r=gl(n.target),i=e.state.schema.marks[Qc];if(i&&r&&tl(e,t,i))return n.preventDefault(),!0;let a=$.getState(e.state);if(!r||!a)return!1;let o=e.state.storedMarks,s=e.state.tr.setMeta($,null);return o!==null&&i&&!Q(o,i)&&s.setStoredMarks(null),e.dispatch(s),!1},vl=(e,t,n)=>t.key!==`ArrowRight`||!el(e,n)||Q(e.state.storedMarks??e.state.selection.$from.marks(),n)||!tl(e,e.state.selection.from,n)?!1:(t.preventDefault(),!0),yl={ArrowLeft:ll,ArrowRight:(e,t,n)=>{if(t.key!==`ArrowRight`)return!1;if(vl(e,t,n))return!0;if(!$c(e,n))return!1;let r=e.state.storedMarks??e.state.selection.$from.marks();if(!Q(r,n))return fl(e),!1;t.preventDefault();let i=r.filter(e=>e.type!==n);return e.dispatch(e.state.tr.setStoredMarks(i).setMeta($,{position:e.state.selection.from,side:`right`,placement:`outside`})),kc(e,e.state.selection.from,1),!0}},bl=(e,t)=>{if(nl(e,t))return!1;let n=yl[t.key];if(!n)return!1;let r=e.state.schema.marks[Qc];if(!r)return!1;let i=$.getState(e.state);return i?Fc(e,t,r,i,$):n(e,t,r)},xl=(0,I.$prose)(()=>new v.Plugin({key:$,view:hl,state:{init:ul,apply:dl},props:{handleKeyDown:bl,handleClick:_l,decorations:Xc,handleDOMEvents:{blur:pl}}})),Sl=`.zt-md-code-block-action-button[data-active='true']`,Cl=`.zt-md-search-panel`,wl=8,Tl={current:0,total:0,isInvalidExpression:!1},El=e=>typeof e.props.editable==`function`?e.props.editable(e.state):e.editable,Dl=e=>new B.SearchQuery({search:e.search,replace:e.replace,caseSensitive:e.caseSensitive,wholeWord:e.wholeWord,regexp:e.regexp,literal:!0}),Ol=(e,t)=>{if(!t.valid)return[];let n=[],r=0,i=e.doc.content.size;for(;r<i;){let a=t.findNext(e,r,i);if(!a)break;n.push(a),r=Math.max(a.to,r+1)}return n},kl=(e,t,n)=>{let r=0,i=e.length-1;for(;r<=i;){let a=r+i>>1,o=e[a];if(o.from===t)return o.to===n?a:-1;o.from<t?r=a+1:i=a-1}return-1},Al=(e,t,n)=>{let r=n.regexp&&n.search.length>0&&!n.valid,i=kl(t,e.selection.from,e.selection.to);return{current:i<0?0:i+1,total:t.length,isInvalidExpression:r}},jl=(e,t)=>e.current===t.current&&e.total===t.total&&e.isInvalidExpression===t.isInvalidExpression,Ml=e=>{if(e.state.selection.empty)return;let t=ca(e.dom);if(!t)return;let n=e.coordsAtPos(e.state.selection.from),r=e.coordsAtPos(e.state.selection.to),i=Math.min(n.top,r.top),a=Math.max(n.bottom,r.bottom),o=t.getBoundingClientRect(),s=(t.closest(`.zt-md`)?.querySelector(Cl))?.getBoundingClientRect(),c=Math.max(o.top+wl,(s?.bottom??o.top)+wl),l=o.bottom-wl;if(i<c){t.scrollTop+=i-c;return}a>l&&(t.scrollTop+=a-l)},Nl=e=>{if(e.state.selection.empty)return;let t=e.domAtPos(e.state.selection.from),n=(t.node instanceof Element?t.node:t.node.parentElement)?.closest(`.zt-md-code-block`);if(n?.dataset.viewMode!==`preview`){Ml(e);return}n.querySelector(Sl)?.click(),window.requestAnimationFrame(()=>{Ml(e)})},Pl=class{constructor(e,t){this.onSnapshotChange=t,this.snapshot=Tl,this.cachedDoc=null,this.cachedQuery=null,this.cachedResults=[],this.emitSnapshot(e.state)}update(e){e.composing||this.emitSnapshot(e.state)}destroy(){this.cachedDoc=null,this.cachedQuery=null,this.cachedResults=[],this.onSnapshotChange(Tl)}resolveSearchResults(e,t){if(this.cachedDoc===e.doc&&this.cachedQuery&&this.cachedQuery.eq(t))return this.cachedResults;let n=Ol(e,t);return this.cachedDoc=e.doc,this.cachedQuery=t,this.cachedResults=n,n}emitSnapshot(e){let t=(0,B.getSearchState)(e);if(!t){this.cachedDoc=null,this.cachedQuery=null,this.cachedResults=[],jl(this.snapshot,Tl)||(this.snapshot=Tl,this.onSnapshotChange(Tl));return}let n=Al(e,this.resolveSearchResults(e,t.query),t.query);jl(this.snapshot,n)||(this.snapshot=n,this.onSnapshotChange(n))}},Fl=e=>[(0,I.$prose)(()=>(0,B.search)()),(0,I.$prose)(()=>new v.Plugin({view:t=>new Pl(t,e)}))],Il=e=>{let t=t=>{e(e=>{let n=Dl(t),r=(0,B.setSearchState)(e.state.tr,n);if(n.valid){let t=n.findNext(e.state,e.state.selection.from)??n.findNext(e.state,0,e.state.selection.from);t&&r.setSelection(v.TextSelection.create(r.doc,t.from,t.to)).scrollIntoView()}e.dispatch(r),Nl(e)})},n=(e,t)=>{e(t.state,e=>{t.dispatch(e.scrollIntoView())})&&Nl(t)};return{updateQuery:t,findPrevious:()=>{e(e=>{n(B.findPrev,e)})},findNext:()=>{e(e=>{n(B.findNext,e)})},replaceCurrent:()=>{e(e=>{El(e)&&n(B.replaceNext,e)})},replaceAll:()=>{e(e=>{if(!El(e))return;let t=(0,B.getSearchState)(e.state);!t||Ol(e.state,t.query).length===0||(0,B.replaceAll)(e.state,t=>{e.dispatch(t)})})},clear:()=>{e(e=>{let t=new B.SearchQuery({search:``,literal:!0});e.dispatch((0,B.setSearchState)(e.state.tr,t))})},focusCurrent:()=>{e(e=>{e.dispatch(e.state.tr.scrollIntoView()),Ml(e),e.focus()})}}},Ll=/^[ \t]+/,Rl=/[ \t]+$/,zl=[(0,I.$remark)(`remarkCjkFriendly`,()=>ge.default),(0,I.$remark)(`remarkCjkFriendlyGfmStrikethrough`,()=>_e.default)].flat(),Bl=e=>{let t=((t,n,r,i)=>{let{delimiter:a,after:o}=e.resolveDelimiters(t,r),s=r.enter(e.constructName),c=r.createTracker(i),l=r.createTracker(i);l.move(a);let u=r.containerPhrasing(t,{before:a,after:o,...l.current()});s();let d=Ll.exec(u)?.[0]??``,f=Rl.exec(u)?.[0]??``,p=u.slice(d.length,u.length-f.length);if(!p)return c.move(u);let m=``;return d&&(m+=c.move(d)),m+=c.move(a),m+=c.move(p),m+=c.move(a),f&&(m+=c.move(f)),m});return t.peek=e.peek,t},Vl=e=>{let t=e.get(y.remarkStringifyOptionsCtx)??{},n=Bl({constructName:`strong`,resolveDelimiters:(e,t)=>{let n=e.marker||t.options.strong||`*`;return{delimiter:n+n,after:n}},peek:(e,t,n)=>n.options.strong||`*`}),r=Bl({constructName:`emphasis`,resolveDelimiters:(e,t)=>{let n=e.marker||t.options.emphasis||`*`;return{delimiter:n,after:n}},peek:(e,t,n)=>n.options.emphasis||`*`}),i=Bl({constructName:`strikethrough`,resolveDelimiters:()=>({delimiter:`~~`,after:`~`}),peek:()=>`~`});e.set(y.remarkStringifyOptionsCtx,{...t,handlers:{...t.handlers,strong:n,emphasis:r,delete:i}})},Hl=`ZT_MD_READONLY_CHANGE`,Ul=`[data-type="code_block"], [data-type="image"], [data-type="math_block"], [data-type="math_inline"], [data-type="frontmatter"]`,Wl=e=>{let t=e.target;if(!(t instanceof Element))return null;let n=t.closest(`a[href]`);return n instanceof HTMLAnchorElement?n:null},Gl=e=>e?.type.name===`image`,Kl=(e,t)=>{let n=Wl(e);if(!n)return!1;let r=Ht(n.getAttribute(`href`));return!r||t||!e.ctrlKey?!1:(e.preventDefault(),e.stopPropagation(),window.open(r,`_blank`,`noopener,noreferrer`),!0)},ql=(e,t)=>!t||!Wl(e)?!1:(e.preventDefault(),e.stopPropagation(),!0),Jl=(e,t)=>{let n=t?`false`:`true`;e.dom.querySelectorAll(Ul).forEach(e=>{if(e.dataset.editable=n,e.dataset.type===`code_block`){let n=e.querySelector(`:scope > .zt-md-code-block-actions`);if(n){let e=n.querySelector(`.zt-md-code-block-action-button`),r=e?!e.hidden:!1;n.dataset.visible=!t||r?`true`:`false`}return}if(t&&e.dataset.type===`math_block`){e.classList.remove(`zt-md-math-block-editing`);let t=e.querySelector(`.zt-md-math-block-source`);t&&(t.hidden=!0)}})},Yl=e=>{let t=e.readOnly,n=ut({debounceMs:e.debounceMs??0,getSerializer:()=>_.action(e=>e.get(y.serializerCtx)),onChange:e.onChange}),r={...e.messages??U(e.locale)},i=tc(e.contentPortalContainer,r),a=zo(e.contentPortalContainer,r,e.shortcutMode),o=Ma(r,e.contentPortalContainer),s=Ar(r,e.contentPortalContainer),c=Jn(e.imageUpload,r),l=Fl(e.onSearchSnapshotChange),u=[...C.commonmark.filter(e=>e!==C.syncHeadingIdPlugin&&e!==C.syncListOrderPlugin),Ni,hc],d=ds(e.portalContainer,e.slashMenu,r,e.imageUpload,e.locale,e.shortcutMode),f=d.plugins,p=hs(e.portalContainer,r,e.shortcutMode,e.imageUpload),m={commonmark:u,frontmatter:Ua,taskListTransformKeymap:bo(e.shortcutMode),inlineCodeBoundaryNavigation:xl,gfm:w.gfm,cjkFriendly:zl,history:x.history,editorSearch:l,codeBlockPrism:[Ue,T.prismConfig],codeBlockLanguagePicker:o,clipboard:b.clipboard,indent:S.indent,imageDeleteSelection:Tn,imagePaste:c,tableArrowEntry:Cs,blockBoundaryNavigation:At,headingBackspaceEmptyParagraph:Ci,headingFocusIndicator:Oi,mathBackspaceEntry:pr,blockquoteBackspaceLift:hi,tableFocusActions:i,selectionTooltip:a,gapCursor:ht,dropCursor:mt,math:ci,mathInlineEdit:s,mathInlineArrowNavigation:Qr,taskListToggle:lc,tabSpaceIndent:Tc,codeBlockModASelect:za,slash:f.length>0?f:null},h=dt(m,{includeRuntime:!1}),g=dt(m,{includeRuntime:!0}).filter(e=>e.name===`clipboard`||e.name===`indent`),_=y.Editor.make();_.config(n=>{yo(n,e.shortcutMode),Ri(n),n.set(T.prismConfig.key,{configureRefractor:Ne}),tn(n,e.imageUpload?.allowedProtocols),Vl(n),n.set(y.rootCtx,e.root),n.set(y.defaultValueCtx,e.markdown),n.set(y.editorViewOptionsCtx,{editable:()=>!t,attributes:{spellcheck:`false`},handleScrollToSelection:e=>e.composing,handleKeyDown:p,handleDOMEvents:{mousedown:(e,n)=>n instanceof MouseEvent?ql(n,t):!1,click:(e,n)=>n instanceof MouseEvent?ql(n,t):!1},handleClick:(e,n,r)=>Kl(r,t),handleClickOn:(e,n,r,i,a,o)=>Kl(a,t)?!0:t&&o&&Gl(r)?(a.preventDefault(),!0):!1});let i=n.get(y.nodeViewCtx)??[];n.set(y.nodeViewCtx,[...i,[`image`,fn(r)],[`math_block`,Cr(r)],[`math_inline`,Ir(r)],[`code_block`,ea(r)],[Ba,$a(r)]]),d.config&&d.config(n)}),h.forEach(e=>{_.use(e.plugin)}),_.use(n.plugin),_.use(nt);let E=Il(e=>{_.action(t=>{e(t.get(y.editorViewCtx))})}),D=()=>{g.forEach(e=>{try{_.use(e.plugin),e.name===`indent`&&_.action(e=>{e.set(S.indentConfig,{type:`space`,size:4})})}catch(e){console.error(e)}})},O=We(I.replaceAll,_);return{editor:_,updateLocalization:(e,t)=>{Ae(r,t),d.updateLocale?.(e)},setReadOnly:e=>{t!==e&&(t=e,_.action(e=>{let n=e.get(y.editorViewCtx);n.setProps({editable:()=>!t}),Jl(n,t),n.dispatch(n.state.tr.setMeta(Hl,t))}))},setDebounceMs:n.setDebounceMs,installRuntimePlugins:D,focusEditor:e=>{_.action(t=>{let n=t.get(y.editorViewCtx),r=n.state.doc.lastChild,i=r?n.state.doc.content.size-r.nodeSize:null,a=i===null?null:n.nodeDOM(i),o=a instanceof Element?a:a?.parentElement??null;if(e!==void 0&&o!==null&&e.top>o.getBoundingClientRect().bottom){let e=n.state.schema.nodes.paragraph;if(!(r?.type===e&&r.content.size===0)){let t=n.state.tr.insert(n.state.doc.content.size,e.create());t.setSelection(v.TextSelection.atEnd(t.doc)).scrollIntoView(),n.dispatch(t),n.focus();return}}let s=e?n.posAtCoords(e):null,c=s?v.TextSelection.near(n.state.doc.resolve(s.pos),1):v.TextSelection.atEnd(n.state.doc);n.state.selection.eq(c)||n.dispatch(n.state.tr.setSelection(c).scrollIntoView()),n.focus()})},searchController:E,setMarkdown:e=>{n.runWithExternalMarkdown(e,()=>{O(e)})}}},Xl=(e,t,n,r)=>{let i=e,a=i.create.bind(e);return i.create=async()=>{try{let e=await a();return t(),n(),e}catch(e){throw console.error(`Milkdown init failed:`,e),r(e),e}},i},Zl=e=>{let t=(0,c.useRef)(null),n=(0,c.useRef)(e.markdown),r=(0,c.useRef)(e.readOnly),i=(0,c.useRef)(e.debounceMs),a=(0,c.useRef)(e.onMarkdownChange),o=(0,c.useRef)(e.onInitError),s=(0,c.useRef)(e.onInitReady),u=(0,c.useRef)(e.onSearchSnapshotChange);r.current=e.readOnly,i.current=e.debounceMs;let d=(0,l.useEditor)(c=>{t.current=null,e.focusEditorRef&&(e.focusEditorRef.current=null),e.searchControllerRef&&(e.searchControllerRef.current=null),n.current=e.markdown;let l=Yl({root:c,portalContainer:e.portalContainer,contentPortalContainer:e.contentPortalContainer,markdown:e.markdown,readOnly:r.current,debounceMs:i.current,messages:e.messages,locale:e.locale,slashMenu:e.slashMenu,imageUpload:e.imageUpload,shortcutMode:e.shortcutMode,onChange:e=>{n.current=e,a.current(e)},onSearchSnapshotChange:e=>{u.current?.(e)}});return Xl(l.editor,l.installRuntimePlugins,()=>{t.current=l,e.focusEditorRef&&(e.focusEditorRef.current=l.focusEditor),e.searchControllerRef&&(e.searchControllerRef.current=l.searchController),s.current?.()},e=>{o.current?.(e)})},[e.portalContainer,e.contentPortalContainer,e.shortcutMode,e.focusEditorRef,e.searchControllerRef]);(0,c.useEffect)(()=>{a.current=e.onMarkdownChange},[e.onMarkdownChange]),(0,c.useEffect)(()=>{o.current=e.onInitError},[e.onInitError]),(0,c.useEffect)(()=>{s.current=e.onInitReady},[e.onInitReady]),(0,c.useEffect)(()=>{u.current=e.onSearchSnapshotChange},[e.onSearchSnapshotChange]),(0,c.useEffect)(()=>{d.loading||t.current?.setDebounceMs?.(e.debounceMs)},[d.loading,e.debounceMs]),(0,c.useEffect)(()=>{d.loading||t.current?.setReadOnly?.(e.readOnly)},[d.loading,e.readOnly]),(0,c.useEffect)(()=>()=>{t.current=null,e.focusEditorRef&&(e.focusEditorRef.current=null),e.searchControllerRef&&(e.searchControllerRef.current=null)},[e.portalContainer,e.contentPortalContainer,e.shortcutMode,e.focusEditorRef,e.searchControllerRef]),(0,c.useEffect)(()=>{d.loading||t.current?.updateLocalization(e.locale??`zh-CN`,e.messages??U(e.locale))},[d.loading,e.locale,e.messages]),(0,c.useEffect)(()=>{let r=t.current;!r||d.loading||e.markdown!==n.current&&(n.current=e.markdown,r.setMarkdown(e.markdown))},[d.loading,e.markdown])},Ql=160,$l=120,eu={search:``,replace:``,caseSensitive:!1,wholeWord:!1,regexp:!1},tu={current:0,total:0,isInvalidExpression:!1},nu={"zh-CN":`只读`,"en-US":`Read only`},ru=e=>e.length===0?`""`:`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\r\n|\r|\n/g,`\\A `)}"`,iu=e=>(Zl({markdown:e.markdown,portalContainer:e.portalContainer,contentPortalContainer:e.contentPortalContainer,focusEditorRef:e.focusEditorRef,searchControllerRef:e.searchControllerRef,readOnly:e.readOnly,debounceMs:e.debounceMs,messages:e.messages,locale:e.locale,slashMenu:e.slashMenu,imageUpload:e.imageUpload,shortcutMode:e.shortcutMode,onMarkdownChange:e.onMarkdownChange,onInitReady:e.onInitReady,onInitError:e.onInitError,onSearchSnapshotChange:e.onSearchSnapshotChange}),(0,g.jsx)(l.Milkdown,{})),au=e=>{let[t,n]=(0,c.useState)(``),[r,i]=(0,c.useState)(null),[a,o]=(0,c.useState)(null),[s,f]=(0,c.useState)(!1),[p,m]=(0,c.useState)(!1),[h,_]=(0,c.useState)(eu),[v,y]=(0,c.useState)(tu),b=(0,c.useRef)(null),x=(0,c.useRef)(null),S=(0,c.useRef)(null),C=(0,c.useRef)(s),w=(0,c.useRef)(h);C.current=s,w.current=h;let T=(0,c.useMemo)(()=>(0,d.debounce)(e=>{x.current?.updateQuery(e)},$l),[]);(0,c.useEffect)(()=>()=>{T.cancel()},[T]);let E=e.theme??`light`,D=e.readOnly??!1,O=nu[e.locale??`zh-CN`],k=e.debounceMs??Ql,A=e.shortcutMode??`modShift`,{markdown:j,setMarkdown:M}=xe(e.value,e.defaultValue,e.onChange),N=(0,c.useMemo)(()=>U(e.locale,e.messages,e.placeholder),[e.locale,e.messages,e.placeholder]),ee=(0,c.useMemo)(()=>({"--zt-gap-placeholder-content":ru(N.placeholder),...e.maxHeight===void 0?{}:{maxHeight:e.maxHeight,overflowY:`auto`}}),[N.placeholder,e.maxHeight]),P=(0,c.useCallback)(e=>{M(e)},[M]),te=(0,c.useCallback)(()=>{n(``),C.current&&x.current?.updateQuery(w.current)},[]),ne=(0,c.useCallback)(e=>{n(e instanceof Error?e.message:N.initError)},[N.initError]),re=(0,c.useCallback)(e=>{if(D)return;let t=e.target;if(!(t instanceof Element))return;let n=t.closest(`.ProseMirror`);t.closest(`.zt-md-content-portal`)||n!==null&&t!==n||(e.preventDefault(),b.current?.({left:e.clientX,top:e.clientY}))},[D]),ie=(0,c.useCallback)(e=>{i(e)},[]),F=(0,c.useCallback)(e=>{o(e)},[]),I=()=>{S.current?.focus(),S.current?.select()},ae=()=>{T.cancel(),f(!0),x.current?.updateQuery(h),requestAnimationFrame(I)},L=()=>{T.cancel();let e=x.current;e?.clear(),y(tu),f(!1),m(!1),e&&requestAnimationFrame(e.focusCurrent)},oe=e=>{T.cancel(),_(e),x.current?.updateQuery(e)},R=e=>{let t={...h,search:e};_(t),T(t)},se=e=>{oe({...h,replace:e})},ce=e=>{oe({...h,[e]:!h[e]})},le=()=>{m(e=>!e)},ue=()=>{T.flush(),x.current?.findPrevious()},de=()=>{T.flush(),x.current?.findNext()},fe=()=>{T.flush(),x.current?.replaceCurrent()},z=()=>{T.flush(),x.current?.replaceAll()},pe=(0,c.useCallback)(e=>{y(e)},[]);return(0,g.jsxs)(`div`,{className:(0,u.default)(`zt-md`,E===`dark`?`zt-md-dark`:`zt-md-light`,e.className),"data-readonly":D?`true`:`false`,"data-search-open":s?`true`:`false`,"data-search-replace-expanded":!D&&p?`true`:`false`,"data-search-invalid":s&&v.isInvalidExpression?`true`:`false`,"data-readonly-label":O,onKeyDownCapture:e=>{if((e.ctrlKey||e.metaKey)&&!e.altKey&&!e.shiftKey&&e.key.toLowerCase()===`f`){e.preventDefault(),ae();return}if(!(!s||e.nativeEvent.isComposing)){if(e.key===`Escape`){e.preventDefault(),L();return}if(!(!(e.target instanceof HTMLInputElement&&e.target.closest(`.zt-md-search-panel`)!==null)||e.key!==`Enter`)){if(e.preventDefault(),e.shiftKey){ue();return}de()}}},children:[e.headerSlot?(0,g.jsx)(`div`,{className:`zt-md-header`,children:e.headerSlot}):null,(0,g.jsxs)(`div`,{className:`zt-md-body`,children:[t?(0,g.jsx)(`div`,{className:`zt-md-error`,children:t}):null,s?(0,g.jsx)(ye,{options:h,snapshot:v,messages:N,readOnly:D,isReplaceExpanded:p,searchInputRef:S,onSearchChange:R,onReplaceChange:se,onOptionToggle:ce,onReplaceExpandedToggle:le,onFindPrevious:ue,onFindNext:de,onReplaceCurrent:fe,onReplaceAll:z,onClose:L}):null,(0,g.jsxs)(`div`,{className:(0,u.default)(`zt-md-editor`,D?`zt-md-readonly`:`zt-md-editable`),"aria-label":N.editorAriaLabel,"aria-readonly":D,onMouseDown:re,style:ee,children:[r&&a?(0,g.jsx)(l.MilkdownProvider,{children:(0,g.jsx)(iu,{markdown:j,locale:e.locale,portalContainer:r,contentPortalContainer:a,focusEditorRef:b,searchControllerRef:x,readOnly:D,debounceMs:k,messages:N,slashMenu:e.slashMenu,imageUpload:e.imageUpload,shortcutMode:A,onMarkdownChange:P,onInitReady:te,onInitError:ne,onSearchSnapshotChange:pe})}):null,(0,g.jsx)(`div`,{ref:F,className:`zt-md-content-portal`})]}),(0,g.jsx)(`div`,{ref:ie,className:`zt-md-portal`})]})]})};exports.MilkdownEditor=au;
|