@smartdoca/markdown 0.4.3 → 0.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +10 -1
  2. package/README.zh-CN.md +10 -1
  3. package/dist/chunks/index-Cd3grnUT.js +2815 -0
  4. package/dist/chunks/index-DQLDZhUI.cjs +86 -0
  5. package/dist/chunks/pdf-file-impl-CMlXt-sQ.cjs +8 -0
  6. package/dist/chunks/pdf-file-impl-Hh_4oE89.js +622 -0
  7. package/dist/index.cjs +1 -51
  8. package/dist/index.js +48 -2351
  9. package/dist/style.css +1 -1
  10. package/dist/types/components/ImageLightbox.d.ts +13 -0
  11. package/dist/types/components/ImageLightbox.d.ts.map +1 -0
  12. package/dist/types/components/MarkdownPreview.d.ts +4 -1
  13. package/dist/types/components/MarkdownPreview.d.ts.map +1 -1
  14. package/dist/types/components/MermaidDiagram.d.ts.map +1 -1
  15. package/dist/types/editor/i18n.d.ts +777 -3
  16. package/dist/types/editor/i18n.d.ts.map +1 -1
  17. package/dist/types/editor/image-preview.d.ts +30 -0
  18. package/dist/types/editor/image-preview.d.ts.map +1 -0
  19. package/dist/types/editor/locales/es.d.ts +130 -0
  20. package/dist/types/editor/locales/es.d.ts.map +1 -0
  21. package/dist/types/editor/locales/fr.d.ts +130 -0
  22. package/dist/types/editor/locales/fr.d.ts.map +1 -0
  23. package/dist/types/editor/locales/ja.d.ts +130 -0
  24. package/dist/types/editor/locales/ja.d.ts.map +1 -0
  25. package/dist/types/editor/locales/ko.d.ts +130 -0
  26. package/dist/types/editor/locales/ko.d.ts.map +1 -0
  27. package/dist/types/editor/locales/ru.d.ts +130 -0
  28. package/dist/types/editor/locales/ru.d.ts.map +1 -0
  29. package/dist/types/editor/locales/zh-Hant.d.ts +130 -0
  30. package/dist/types/editor/locales/zh-Hant.d.ts.map +1 -0
  31. package/dist/types/editor/locales.d.ts +771 -0
  32. package/dist/types/editor/locales.d.ts.map +1 -0
  33. package/dist/types/editor/pdf-contract.d.ts +77 -0
  34. package/dist/types/editor/pdf-contract.d.ts.map +1 -0
  35. package/dist/types/editor/pdf-file-impl.d.ts +7 -0
  36. package/dist/types/editor/pdf-file-impl.d.ts.map +1 -0
  37. package/dist/types/editor/pdf-file.d.ts +4 -78
  38. package/dist/types/editor/pdf-file.d.ts.map +1 -1
  39. package/dist/types/lib/CollaborativeMarkdownEditor.d.ts +3 -0
  40. package/dist/types/lib/CollaborativeMarkdownEditor.d.ts.map +1 -1
  41. package/dist/types/lib/index.d.ts +1 -0
  42. package/dist/types/lib/index.d.ts.map +1 -1
  43. package/docs/COLLABORATION.md +4 -0
  44. package/docs/IMAGE_PREVIEW.md +62 -0
  45. package/package.json +3 -2
package/dist/index.cjs CHANGED
@@ -1,51 +1 @@
1
- "use strict";var Rn=Object.create;var Mt=Object.defineProperty;var Fn=Object.getOwnPropertyDescriptor;var Ln=Object.getOwnPropertyNames;var In=Object.getPrototypeOf,Cn=Object.prototype.hasOwnProperty;var Dn=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ln(e))!Cn.call(t,o)&&o!==n&&Mt(t,o,{get:()=>e[o],enumerable:!(r=Fn(e,o))||r.enumerable});return t};var On=(t,e,n)=>(n=t!=null?Rn(In(t)):{},Dn(e||!t||!t.__esModule?Mt(n,"default",{value:t,enumerable:!0}):n,t));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const m=require("react/jsx-runtime"),v=require("react"),Nn=require("@uiw/react-codemirror"),jn=require("react-dom"),_n=require("@codemirror/lang-markdown"),Tt=require("@codemirror/language"),Q=require("@codemirror/view"),ce=require("@codemirror/state"),At=require("y-codemirror.next"),Un=require("yjs"),Z=require("lucide-react"),Bn=require("react-markdown"),qn=require("remark-gfm"),Hn=require("remark-math"),Wn=require("rehype-katex"),$n=require("rehype-raw"),Ie=require("rehype-sanitize"),ne=require("highlight.js/lib/core"),Kn=require("highlight.js/lib/languages/bash"),Vn=require("highlight.js/lib/languages/c"),zn=require("highlight.js/lib/languages/cpp"),Xn=require("highlight.js/lib/languages/csharp"),Gn=require("highlight.js/lib/languages/css"),Yn=require("highlight.js/lib/languages/dockerfile"),Jn=require("highlight.js/lib/languages/go"),Qn=require("highlight.js/lib/languages/graphql"),Zn=require("highlight.js/lib/languages/java"),er=require("highlight.js/lib/languages/javascript"),tr=require("highlight.js/lib/languages/json"),nr=require("highlight.js/lib/languages/kotlin"),rr=require("highlight.js/lib/languages/markdown"),or=require("highlight.js/lib/languages/php"),ar=require("highlight.js/lib/languages/python"),ir=require("highlight.js/lib/languages/ruby"),sr=require("highlight.js/lib/languages/rust"),cr=require("highlight.js/lib/languages/sql"),lr=require("highlight.js/lib/languages/swift"),dr=require("highlight.js/lib/languages/typescript"),ur=require("highlight.js/lib/languages/xml"),fr=require("highlight.js/lib/languages/yaml"),Ge=require("micromark"),mr=require("micromark-extension-gfm"),hr=require("micromark-util-decode-string"),gr=require("y-indexeddb"),pr=require("y-websocket"),Nt=require("y-protocols/awareness"),de=require("pdfjs-dist/legacy/build/pdf.mjs");require("pdfjs-dist/legacy/build/pdf.worker.mjs");const H=require("pdf-lib"),wr=require("@pdf-lib/fontkit");function xr(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:!0,get:()=>t[n]})}}return e.default=t,Object.freeze(e)}const X=xr(Un);function rt(t){return t==null||t===""||t==="zh"?"zh":"en"}function jt(t){return rt(t)==="zh"?"zh-CN":"en"}const _t={"toolbar.label":"Markdown formatting toolbar","toolbar.undo":"Undo","toolbar.redo":"Redo","toolbar.insertCode":"Insert code block","toolbar.codeLanguage":"Code language","toolbar.textColor":"Text color","toolbar.uploadImage":"Upload image","toolbar.insertDiagram":"Insert diagram","toolbar.insertFormula":"Insert math formula","toolbar.viewEdit":"Edit only","toolbar.viewSplit":"Split view","toolbar.viewPreview":"Preview only","format.heading1":"Heading 1","format.heading2":"Heading 2","format.heading3":"Heading 3","format.heading4":"Heading 4","format.heading5":"Heading 5","format.bold":"Bold","format.italic":"Italic","format.strike":"Strikethrough","format.inlineCode":"Inline code","format.quote":"Quote","format.bulletList":"Bulleted list","format.orderedList":"Numbered list","format.task":"Task list","format.link":"Link","format.boldPlaceholder":"bold text","format.italicPlaceholder":"italic text","format.strikePlaceholder":"strikethrough text","format.codePlaceholder":"code","format.linkPlaceholder":"link text","format.colorPlaceholder":"colored text","insert.diagram":`
2
- \`\`\`mermaid
3
- flowchart TD
4
- A[Start] --> B{Decision}
5
- B -->|Yes| C[Done]
6
- B -->|No| D[Revise]
7
- \`\`\`
8
- `,"insert.codePlaceholder":"Type code here","diagram.syntaxError":"The diagram syntax is invalid. Check the Mermaid code.","selection.toolbar":"Selection actions","notice.imageRequired":"Choose an image file","notice.readOnly":"This document is read-only","notice.uploadFailed":"Image upload failed","notice.downloadFailed":"Download failed","notice.uploading":"Processing image…","editor.pane":"Markdown editor","editor.characters.one":"{count} character","editor.characters.other":"{count} characters","editor.transportRequired":"roomId and websocketUrl are required, or pass a host-managed collaboration session","preview.pane":"Document preview","preview.label":"Preview","preview.updating":"Updating preview…","preview.syncScroll":"Scroll sync","preview.live":"Live render","document.title":"Collaborative document","status.ready":"Collaboration ready","status.error":"Collaboration error","status.offline":"Offline","status.offlineEditing":"Offline editing","status.syncing":"Syncing document","status.loading":"Loading document","header.room":"Room · {roomId}","presence.online.one":"{count} person online","presence.online.other":"{count} people online","presence.cursor":"{name}'s cursor","presence.anonymous":"Anonymous","loading.document":"Loading collaborative document…","footer.formats":"CommonMark · GFM · Mermaid","footer.readOnly":"Read-only","footer.dropImages":"Drop or paste images","collaboration.schemaMismatch":"This document format is not supported","collaboration.initializationFailed":"Failed to load local collaboration data","pdf.aborted":"PDF conversion was cancelled","pdf.fileTooLarge":"PDF exceeds the {maxBytes}-byte limit","pdf.readFailed":"Could not read the PDF file","pdf.passwordRequired":"This PDF requires a password. Password-protected PDFs are not supported in this phase","pdf.errorDetail":"{message} ({detail})","pdf.timeout":"PDF conversion exceeded the {timeoutMs} ms limit","pdf.pageLimit":"PDF exceeds the {maxPages}-page limit","pdf.unsafeLink":"Skipped an unsafe or unverifiable PDF link","pdf.multiColumn":"Possible multi-column layout detected. Text order is reconstructed approximately from PDF coordinates","pdf.imagePixelLimit":"An image in the PDF exceeds the {maxImagePixels}-pixel limit","pdf.pngFailed":"Could not convert a PDF image to PNG","pdf.imageSkipped":"Could not extract an embedded PDF image. It was skipped","pdf.canvasUnavailable":"No Canvas is available in this environment, so embedded PDF images could not be extracted","pdf.imageParseFailed":"Failed to parse an embedded PDF image. Text import continued","pdf.noTextPage":"This page has no extractable text. Scanned PDFs are not OCR'd in this phase","pdf.imageAlt":"PDF image","pdf.complexTableImport":"PDF tables are reconstructed approximately from text coordinates. Complex merged cells may be lossy","pdf.noText":"The PDF has no extractable text. Scanned PDFs are not OCR'd in this phase","pdf.invalid":"The PDF is damaged or uses an unsupported format","pdf.unsafeLinkText":"Downgraded an unsafe link to plain text","pdf.mathDegraded":"Math was downgraded to readable plain text","pdf.complexTableExport":"Tables are drawn at a fixed width. Merged cells and overly wide columns may be lossy","pdf.fontFallback":"No font covering every character was provided. Unsupported characters were replaced with question marks. Provide a Chinese TTF/OTF font in PdfExportOptions.fontBytes","pdf.fontFallbackCjk":"No Chinese font was provided. Characters the standard fonts cannot encode are replaced with question marks. Provide a Chinese TTF/OTF font in PdfExportOptions.fontBytes","pdf.imageUnresolved":"No resolveResource callback was provided for a Markdown image. Alternate text was exported instead","pdf.imageFailed":"Failed to resolve a Markdown image. Alternate text was exported instead","pdf.inlineImageUnresolved":"No resolveResource callback was provided for an inline Markdown image. Alternate text was exported instead","pdf.inlineImageUnsupported":"The inline Markdown image format is unsupported. Alternate text was exported instead","pdf.inlineImageFailed":"Failed to resolve an inline Markdown image. Alternate text was exported instead","pdf.pageGeometry":"PDF page size and margins must be positive numbers","validation.positiveInteger":"{name} must be a positive safe integer","validation.nonNegativeInteger":"{name} must be a non-negative safe integer","validation.markdownString":"markdown must be a string","validation.loneSurrogate":"Markdown contains an isolated UTF-16 surrogate and cannot be exported to UTF-8 without data loss","markdown.resourcePreserved":"Only the Markdown source is exchanged. Image, attachment, and internal-link IDs, paths, and addresses are kept as-is. Resources were not read and authorization was not checked. Platform-internal resources are not guaranteed to work outside the platform.","markdown.unsupportedExtension":"Only .md and .markdown files are supported","markdown.fileTooLarge":"File exceeds the {maxBytes}-byte limit","markdown.readFailed":"Could not read the Markdown file","markdown.invalidUtf8":"The file is not valid UTF-8. Convert the encoding first. No damaged characters were replaced","markdown.binary":"The file contains a NUL character and may be binary or unsupported UTF-16/UTF-32","markdown.bomRemoved":"Removed the UTF-8 BOM at the start of the file. U+FEFF in the body was kept","markdown.mixedLineEndings":"The file mixes line-ending styles. They were kept as-is and not normalized","upload.failed":"Upload failed ({status})","upload.missingUrl":"The upload endpoint did not return an image URL","upload.readFailed":"Could not read the image"},Ut={"toolbar.label":"Markdown 格式工具栏","toolbar.undo":"撤销","toolbar.redo":"重做","toolbar.insertCode":"插入代码块","toolbar.codeLanguage":"代码语言","toolbar.textColor":"文字颜色","toolbar.uploadImage":"上传图片","toolbar.insertDiagram":"插入流程图","toolbar.insertFormula":"插入数学公式","toolbar.viewEdit":"仅编辑","toolbar.viewSplit":"分栏","toolbar.viewPreview":"仅预览","format.heading1":"一级标题","format.heading2":"二级标题","format.heading3":"三级标题","format.heading4":"四级标题","format.heading5":"五级标题","format.bold":"加粗","format.italic":"斜体","format.strike":"删除线","format.inlineCode":"行内代码","format.quote":"引用","format.bulletList":"无序列表","format.orderedList":"有序列表","format.task":"待办事项","format.link":"链接","format.boldPlaceholder":"加粗文字","format.italicPlaceholder":"斜体文字","format.strikePlaceholder":"删除文字","format.codePlaceholder":"代码","format.linkPlaceholder":"链接文字","format.colorPlaceholder":"彩色文字","insert.diagram":`
9
- \`\`\`mermaid
10
- flowchart TD
11
- A[开始] --> B{判断}
12
- B -->|是| C[完成]
13
- B -->|否| D[调整]
14
- \`\`\`
15
- `,"insert.codePlaceholder":"在这里输入代码","diagram.syntaxError":"流程图语法有误,请检查 Mermaid 代码。","selection.toolbar":"选中文字操作","notice.imageRequired":"请选择图片文件","notice.readOnly":"当前文档为只读模式","notice.uploadFailed":"图片上传失败","notice.downloadFailed":"下载失败","notice.uploading":"正在处理图片…","editor.pane":"Markdown 编辑器","editor.characters.one":"{count} 字符","editor.characters.other":"{count} 字符","editor.transportRequired":"roomId 和 websocketUrl 必填,或传入宿主管理的 collaboration 会话","preview.pane":"文档预览","preview.label":"预览","preview.updating":"预览更新中…","preview.syncScroll":"同步滚动","preview.live":"实时渲染","document.title":"协作文档","status.ready":"协同就绪","status.error":"协同错误","status.offline":"离线","status.offlineEditing":"离线编辑","status.syncing":"同步文档中","status.loading":"加载文档中","header.room":"房间 · {roomId}","presence.online.one":"{count} 人在线","presence.online.other":"{count} 人在线","presence.cursor":"{name} 的光标","presence.anonymous":"匿名","loading.document":"正在获取协作文档…","footer.formats":"支持 CommonMark · GFM · Mermaid","footer.readOnly":"只读模式","footer.dropImages":"图片可直接拖入或粘贴","collaboration.schemaMismatch":"文档格式不受支持","collaboration.initializationFailed":"本地协同数据加载失败","pdf.aborted":"PDF 转换已取消","pdf.fileTooLarge":"PDF 文件超过 {maxBytes} 字节限制","pdf.readFailed":"无法读取 PDF 文件","pdf.passwordRequired":"PDF 需要密码,第一阶段不支持密码 PDF","pdf.errorDetail":"{message}({detail})","pdf.timeout":"PDF 转换超过 {timeoutMs} 毫秒限制","pdf.pageLimit":"PDF 页数超过 {maxPages} 页限制","pdf.unsafeLink":"已跳过不安全或无法验证的 PDF 链接","pdf.multiColumn":"检测到可能的多栏布局,文本顺序按 PDF 坐标近似重建","pdf.imagePixelLimit":"PDF 内图片超过 {maxImagePixels} 像素限制","pdf.pngFailed":"无法将 PDF 图片转换为 PNG","pdf.imageSkipped":"PDF 内嵌图片无法提取,已跳过","pdf.canvasUnavailable":"当前运行环境没有可用的 Canvas,无法提取 PDF 内嵌图片","pdf.imageParseFailed":"PDF 内嵌图片解析失败,已继续导入文本","pdf.noTextPage":"此页没有可提取文本;扫描 PDF 第一阶段不执行 OCR","pdf.imageAlt":"PDF 图片","pdf.complexTableImport":"PDF 表格按坐标文本近似还原,复杂合并单元格可能有损","pdf.noText":"PDF 没有可提取文本;扫描 PDF 第一阶段不执行 OCR","pdf.invalid":"PDF 文件损坏或格式不受支持","pdf.unsafeLinkText":"已将不安全链接降级为纯文本","pdf.mathDegraded":"数学公式已按可读纯文本降级","pdf.complexTableExport":"表格按固定宽度绘制;合并单元格和超宽列可能有损","pdf.fontFallback":"未提供可覆盖全部字符的字体;不兼容字符已替换为问号。建议在 PdfExportOptions.fontBytes 中提供中文 TTF/OTF 字体","pdf.fontFallbackCjk":"未提供中文字体;导出会将标准字体无法编码的字符降级为问号。请在 PdfExportOptions.fontBytes 中提供中文 TTF/OTF 字体","pdf.imageUnresolved":"Markdown 图片未提供 resolveResource,已用替代文本导出","pdf.imageFailed":"Markdown 图片资源解析失败,已用替代文本导出","pdf.inlineImageUnresolved":"Markdown 行内图片未提供 resolveResource,已用替代文本导出","pdf.inlineImageUnsupported":"Markdown 行内图片格式不受支持,已用替代文本导出","pdf.inlineImageFailed":"Markdown 行内图片资源解析失败,已用替代文本导出","pdf.pageGeometry":"PDF 页面尺寸和页边距必须为正数","validation.positiveInteger":"{name} 必须为正安全整数","validation.nonNegativeInteger":"{name} 必须为非负安全整数","validation.markdownString":"markdown 必须为字符串","validation.loneSurrogate":"Markdown 包含孤立 UTF-16 代理字符,无法无损导出为 UTF-8","markdown.resourcePreserved":"仅交换 Markdown 原文;图片、附件和内部链接的 ID/path/地址原样保留,未读取资源或验证授权,平台内部资源离开平台不保证可访问。","markdown.unsupportedExtension":"只支持 .md 和 .markdown 文件","markdown.fileTooLarge":"文件超过 {maxBytes} 字节限制","markdown.readFailed":"无法读取 Markdown 文件","markdown.invalidUtf8":"文件不是有效 UTF-8;请先转换编码,未替换任何损坏字符","markdown.binary":"文件包含 NUL 字符,可能是二进制或不受支持的 UTF-16/UTF-32 编码","markdown.bomRemoved":"已移除文件开头的 UTF-8 BOM;正文内的 U+FEFF 保留","markdown.mixedLineEndings":"文件混用了换行格式;原样保留,未统一换行","upload.failed":"上传失败({status})","upload.missingUrl":"上传接口未返回图片地址","upload.readFailed":"读取图片失败"};function br(t,e){const n=Object.keys(t).filter(o=>!Object.prototype.hasOwnProperty.call(e,o)),r=Object.keys(e).filter(o=>!Object.prototype.hasOwnProperty.call(t,o));if(n.length||r.length)throw new Error(`Message catalog mismatch. Missing zh: ${n.join(", ")}. Extra zh: ${r.join(", ")}`)}br(_t,Ut);const St={en:_t,zh:Ut};function z(t,e,n,r){const o=rt(t),l=n&&typeof n.count=="number"?n.count:void 0,c=l===void 0?[e]:[`${e}.${l===1?"one":"other"}`,e],a=[r,St[o],St.en];let s;for(const i of a)if(i){for(const d of c)if(Object.prototype.hasOwnProperty.call(i,d)){s=i[d];break}if(s!==void 0)break}return s===void 0&&(s=c[0]),n?s.replace(/\{([A-Za-z0-9_]+)\}/g,(i,d)=>{const u=n[d];return u==null?i:String(u)}):s}function Bt(t,e){return(n,r)=>z(t,n,r,e)}function vr(t,e,n){return t.code==="INITIALIZATION_FAILED"?z(e,"collaboration.initializationFailed",void 0,n):t.code==="SCHEMA_MISMATCH"&&!(t.cause instanceof Error)?z(e,"collaboration.schemaMismatch",void 0,n):t.message}let Pt=!1;const qt=v.memo(function({code:e,locale:n,messages:r}){const o=v.useId().replace(/:/g,""),[l,c]=v.useState(""),[a,s]=v.useState(!1);return v.useEffect(()=>{let i=!0;const d=`mermaid-${o}-${Date.now()}`;return import("mermaid").then(({default:u})=>(Pt||(u.initialize({startOnLoad:!1,theme:"neutral",securityLevel:"strict",fontFamily:"Inter, system-ui, sans-serif"}),Pt=!0),u.render(d,e))).then(({svg:u})=>{i&&(c(u),s(!1))}).catch(()=>{i&&(c(""),s(!0))}),()=>{i=!1}},[e,o]),a?m.jsx("div",{className:"diagram-error",children:z(n,"diagram.syntaxError",void 0,r)}):m.jsx("div",{className:"mermaid-diagram",dangerouslySetInnerHTML:{__html:l}})}),yr={bash:Kn,c:Vn,cpp:zn,csharp:Xn,css:Gn,dockerfile:Yn,go:Jn,graphql:Qn,java:Zn,javascript:er,json:tr,kotlin:nr,markdown:rr,php:or,python:ar,ruby:ir,rust:sr,sql:cr,swift:lr,typescript:dr,xml:ur,yaml:fr};Object.entries(yr).forEach(([t,e])=>{ne.getLanguage(t)||ne.registerLanguage(t,e)});ne.registerAliases(["js","jsx"],{languageName:"javascript"});ne.registerAliases(["ts","tsx"],{languageName:"typescript"});ne.registerAliases(["sh","shell"],{languageName:"bash"});ne.registerAliases(["html","svg","vue"],{languageName:"xml"});ne.registerAliases(["yml"],{languageName:"yaml"});ne.registerAliases(["cs","dotnet"],{languageName:"csharp"});ne.registerAliases(["md"],{languageName:"markdown"});function ot(t,e,n){if(!e)return;const r=t.at(-1);r&&r.scope===n?r.text+=e:t.push({text:e,scope:n})}function Ht(t,e,n){if(typeof t=="string"){ot(e,t,n);return}const r=t.scope||n;for(const o of t.children||[])Ht(o,e,r)}function kr(t){const e=[[]];for(const n of t){const r=n.text.split(`
16
- `);for(let o=0;o<r.length;o++)ot(e.at(-1),r[o],n.scope),o<r.length-1&&e.push([])}return e}function Er(t){const e={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#039;"};return t.replace(/[&<>"']/g,n=>e[n])}function Wt(t,e){const n=(e||"").toLowerCase(),r=ne.getLanguage(n)?n:"plaintext";if(r==="plaintext")return{language:r,html:Er(t),lines:t.split(`
17
- `).map(a=>a?[{text:a}]:[])};const o=ne.highlight(t,{language:r}),l=o._emitter.rootNode,c=[];return l?Ht(l,c):ot(c,t),{language:r,html:o.value,lines:kr(c)}}function $t({code:t,language:e}){const n=t.replace(/\n$/,""),r=Wt(n,e);return m.jsx("pre",{className:"highlighted-code",children:m.jsx("code",{className:`hljs language-${r.language}`,dangerouslySetInnerHTML:{__html:r.html}})})}function Mr(t){const e=[];let n=0;for(const[i,d]of Ge.postprocess(Ge.parse({extensions:[mr.gfm()]}).document().write(Ge.preprocess()(t,"utf8",!0)))){if(d.type==="codeText"&&(n+=i==="enter"?1:-1),i!=="enter")continue;const u=d.start.offset,y=d.end.offset,w=t.slice(u,y);if(["data","codeTextData","autolinkProtocol","autolinkEmail"].includes(d.type))for(let k=0;k<w.length;k++)e.push({from:u+k,to:u+k+1,value:w[k]==="\0"?"�":w[k]});else if(d.type==="characterEscape"||d.type==="characterReference")for(const k of hr.decodeString(w).split(""))e.push({from:u,to:y,value:k});else if(d.type==="lineEnding")if(n)e.push({from:u,to:y,value:" "});else for(let k=0;k<w.length;k++)e.push({from:u+k,to:u+k+1,value:w[k]})}e.sort((i,d)=>i.from-d.from);const r={source:t,runs:new Map},o=new Map,l=i=>`${i.position?.start?.offset}:${i.position?.end?.offset}`,c=i=>{let d=0,u=e.length;for(;d<u;){const y=d+u>>>1;e[y].from<i?d=y+1:u=y}return d};return{mapping:r,beforeRaw:()=>i=>{r.runs.clear(),o.clear();const d=(u,y=!1)=>{y||=u.tagName==="pre"||u.tagName==="code"&&!!u.properties?.className,!(!u.children||y)&&(u.children=u.children.map(w=>{if(w.type!=="text")return d(w,y),w;const k=w.position?.start?.offset,T=w.position?.end?.offset;if(k===void 0||T===void 0||!w.value)return w;const L=[];for(let I=c(k);I<e.length&&e[I].to<=T;I++)L.push(e[I]);if(L.map(I=>I.value).join("")!==w.value)return w;const M=String(r.runs.size);return r.runs.set(M,{value:w.value,characters:L.map(({from:I,to:R})=>({from:I,to:R}))}),o.set(l(w),M),{type:"element",tagName:"span",properties:{},position:w.position,children:[w]}}))};d(i)},afterSanitize:()=>i=>{const d=u=>{u.type==="element"&&u.position?.start?.line&&(u.properties={...u.properties,dataExmdSourceLine:u.position.start.line,dataExmdSourceEndLine:u.position.end?.line??u.position.start.line});const y=u.tagName==="span"?o.get(l(u)):void 0;y!==void 0&&u.children?.length===1&&u.children[0].type==="text"&&u.children[0].value===r.runs.get(y)?.value&&(u.properties={...u.properties,dataExmdText:y}),u.children?.forEach(d)};d(i)}}}function Kt(t,e){const n=[],r=t.ownerDocument.createTreeWalker(t,4);for(let o=r.nextNode();o;o=r.nextNode()){const l=o.parentElement?.closest("[data-exmd-text]"),c=l&&e.runs.get(l.dataset.exmdText);c&&o.nodeValue===c.value&&t.contains(l)&&n.push({node:o,run:c})}return n}function Rt(t,e){const n=t.ownerDocument.getSelection();if(!n||n.isCollapsed||n.rangeCount!==1)return null;const r=n.getRangeAt(0);if(!t.contains(r.startContainer)||!t.contains(r.endContainer))return null;const o=new Map(Kt(t,e).map(s=>[s.node,s.run]));let l,c;const a=t.ownerDocument.createTreeWalker(t,4);for(let s=a.nextNode();s;s=a.nextNode()){if(!r.intersectsNode(s))continue;const i=s===r.startContainer?r.startOffset:0,d=s===r.endContainer?r.endOffset:s.nodeValue.length;if(i>=d)continue;const u=o.get(s);if(!u){if(s.nodeValue.slice(i,d).trim())return null;continue}if(!u.characters[i]||!u.characters[d-1])return null;l??=u.characters[i].from,c=u.characters[d-1].to}for(const s of t.querySelectorAll("img,svg,.katex,pre"))if(r.intersectsNode(s))return null;return l!==void 0&&c!==void 0&&l<c?{from:l,to:c,range:r.cloneRange()}:null}function Tr(t,e,n,r){const o=[];for(const{node:l,run:c}of Kt(t,e)){let a=-1,s=-1;if(c.characters.forEach((d,u)=>{d.to>n&&d.from<r&&(a<0&&(a=u),s=u+1)}),a<0)continue;const i=t.ownerDocument.createRange();i.setStart(l,a),i.setEnd(l,s),o.push(i)}return o}const Ar={...Ie.defaultSchema,attributes:{...Ie.defaultSchema.attributes,span:[...Ie.defaultSchema.attributes?.span||[],"dataColor"]}},Sr={a:({children:t,...e})=>m.jsx("a",{...e,target:"_blank",rel:"noreferrer",children:t}),span:({node:t,children:e,...n})=>{const r=t?.properties?.dataColor,o=typeof r=="string"&&/^#[0-9a-fA-F]{6}$/.test(r)?r:void 0;return m.jsx("span",{...n,style:o?{color:o}:void 0,children:e})},pre:({children:t,node:e})=>m.jsx("div",{"data-exmd-source-line":e?.position?.start.line,"data-exmd-source-end-line":e?.position?.end.line,children:t})},Vt=v.memo(function({value:e,resolveImageUrl:n,interaction:r,locale:o,messages:l}){const c=v.useRef(null),a=v.useMemo(()=>r?Mr(e):null,[e,r]);v.useLayoutEffect(()=>{if(c.current&&a&&r)return r.attach(c.current,a.mapping)},[a,r]);const s=v.useMemo(()=>({...Sr,code:({className:i,children:d,...u})=>{const y=/language-([\w-]+)/.exec(i||""),w=String(d);return y?.[1]==="mermaid"?m.jsx(qt,{code:w.replace(/\n$/,""),locale:o,messages:l}):y?m.jsx($t,{code:w,language:y[1]}):m.jsx("code",{className:i,...u,children:d})},img:({alt:i,src:d,...u})=>m.jsx(Pr,{...u,alt:i||"",path:d||"",resolveUrl:n})}),[n,o,l]);return m.jsx("article",{ref:c,className:"markdown-body",children:m.jsx(Bn,{remarkPlugins:[qn,Hn],rehypePlugins:[...a?[a.beforeRaw]:[],...e.includes("<")?[$n]:[],[Ie,Ar],...a?[a.afterSanitize]:[],Wn],components:s,children:e})})});function Pr({path:t,resolveUrl:e,alt:n,...r}){const[o,l]=v.useState(()=>e?"":t);return v.useEffect(()=>{let c=!0;return e?(Promise.resolve(e(t)).then(a=>{c&&l(a)}).catch(()=>{c&&l("")}),()=>{c=!1}):(l(t),()=>{c=!1})},[t,e]),m.jsx("img",{...r,src:o||void 0,alt:n||"",loading:"lazy"})}const Rr=[{id:"heading1",label:"H1",titleKey:"format.heading1",prefix:"# ",block:!0},{id:"heading2",label:"H2",titleKey:"format.heading2",prefix:"## ",block:!0},{id:"heading3",label:"H3",titleKey:"format.heading3",prefix:"### ",block:!0},{id:"heading4",label:"H4",titleKey:"format.heading4",prefix:"#### ",block:!0},{id:"heading5",label:"H5",titleKey:"format.heading5",prefix:"##### ",block:!0},{id:"bold",label:"B",titleKey:"format.bold",prefix:"**",suffix:"**",placeholderKey:"format.boldPlaceholder"},{id:"italic",label:"I",titleKey:"format.italic",prefix:"*",suffix:"*",placeholderKey:"format.italicPlaceholder"},{id:"strike",label:"S",titleKey:"format.strike",prefix:"~~",suffix:"~~",placeholderKey:"format.strikePlaceholder"},{id:"code",label:"</>",titleKey:"format.inlineCode",prefix:"`",suffix:"`",placeholderKey:"format.codePlaceholder"},{id:"quote",label:"“",titleKey:"format.quote",prefix:"> ",block:!0},{id:"bullet",label:"•",titleKey:"format.bulletList",prefix:"- ",block:!0},{id:"ordered",label:"1.",titleKey:"format.orderedList",prefix:"1. ",block:!0},{id:"task",label:"☑",titleKey:"format.task",prefix:"- [ ] ",block:!0},{id:"link",label:"↗",titleKey:"format.link",prefix:"[",suffix:"](https://)",placeholderKey:"format.linkPlaceholder"}];function Fr(t,e){const n=t.state.selection.main,r=t.state.sliceDoc(n.from,n.to);if(e.block){const o=t.state.doc.lineAt(n.from),l=e.prefix;t.dispatch({changes:{from:o.from,insert:l},selection:{anchor:n.from+l.length,head:n.to+l.length}})}else{const o=r||e.placeholder||"",l=`${e.prefix}${o}${e.suffix||""}`,c=n.from+e.prefix.length;t.dispatch({changes:{from:n.from,to:n.to,insert:l},selection:{anchor:c,head:c+o.length}})}t.focus()}function Me(t,e){const n=t.state.selection.main;t.dispatch({changes:{from:n.from,to:n.to,insert:e},selection:{anchor:n.from+e.length}}),t.focus()}function Lr(t,e,n){return{label:t.label,title:e,prefix:t.prefix,suffix:t.suffix,placeholder:n,block:t.block}}function zt(t){const e=t.readOnly,n=r=>z(t.locale,r,void 0,t.messages);return m.jsxs("div",{className:"toolbar",role:"toolbar","aria-label":n("toolbar.label"),children:[m.jsxs("div",{className:"tool-group history-tools",children:[m.jsx("button",{disabled:e,onClick:t.onUndo,title:n("toolbar.undo"),children:m.jsx(Z.Undo2,{})}),m.jsx("button",{disabled:e,onClick:t.onRedo,title:n("toolbar.redo"),children:m.jsx(Z.Redo2,{})})]}),m.jsx("div",{className:"tool-divider"}),m.jsx("div",{className:"tool-group format-tools",children:Rr.map(r=>{const o=n(r.titleKey);return m.jsx("button",{disabled:e,onClick:()=>t.onAction(Lr(r,o,r.placeholderKey?n(r.placeholderKey):void 0)),title:o,className:r.label==="I"?"italic":"",children:r.label},r.id)})}),m.jsx("div",{className:"tool-divider"}),m.jsxs("div",{className:"tool-group rich-tools",children:[m.jsxs("select",{disabled:e,defaultValue:"","aria-label":n("toolbar.insertCode"),title:n("toolbar.insertCode"),onChange:r=>{r.target.value&&t.onCodeBlock(r.target.value),r.target.value=""},children:[m.jsx("option",{value:"",disabled:!0,children:n("toolbar.codeLanguage")}),m.jsx("option",{value:"typescript",children:"TypeScript"}),m.jsx("option",{value:"javascript",children:"JavaScript"}),m.jsx("option",{value:"tsx",children:"TSX"}),m.jsx("option",{value:"python",children:"Python"}),m.jsx("option",{value:"java",children:"Java"}),m.jsx("option",{value:"go",children:"Go"}),m.jsx("option",{value:"rust",children:"Rust"}),m.jsx("option",{value:"cpp",children:"C++"}),m.jsx("option",{value:"csharp",children:"C#"}),m.jsx("option",{value:"php",children:"PHP"}),m.jsx("option",{value:"ruby",children:"Ruby"}),m.jsx("option",{value:"swift",children:"Swift"}),m.jsx("option",{value:"kotlin",children:"Kotlin"}),m.jsx("option",{value:"bash",children:"Shell"}),m.jsx("option",{value:"sql",children:"SQL"}),m.jsx("option",{value:"json",children:"JSON"}),m.jsx("option",{value:"yaml",children:"YAML"}),m.jsx("option",{value:"html",children:"HTML"}),m.jsx("option",{value:"css",children:"CSS"}),m.jsx("option",{value:"graphql",children:"GraphQL"}),m.jsx("option",{value:"dockerfile",children:"Dockerfile"}),m.jsx("option",{value:"markdown",children:"Markdown"})]}),m.jsxs("label",{className:"color-tool",title:n("toolbar.textColor"),children:[m.jsx("span",{children:"A"}),m.jsx("input",{disabled:e,type:"color",defaultValue:"#d14f4f","aria-label":n("toolbar.textColor"),onChange:r=>t.onColor(r.target.value)})]})]}),m.jsx("div",{className:"tool-divider"}),m.jsxs("div",{className:"tool-group",children:[m.jsx("button",{disabled:e,onClick:t.onImage,title:n("toolbar.uploadImage"),children:m.jsx(Z.ImagePlus,{})}),m.jsx("button",{disabled:e,onClick:t.onDiagram,title:n("toolbar.insertDiagram"),children:m.jsx(Z.Workflow,{})}),m.jsx("button",{disabled:e,onClick:t.onFormula,title:n("toolbar.insertFormula"),children:m.jsx(Z.Sigma,{})})]}),m.jsx("div",{className:"toolbar-spacer"}),t.hostActions,m.jsxs("div",{className:"tool-group view-switcher",children:[m.jsx("button",{className:t.mode==="edit"?"active":"",onClick:()=>t.onModeChange("edit"),title:n("toolbar.viewEdit"),children:m.jsx(Z.PanelLeft,{})}),m.jsx("button",{className:t.mode==="split"?"active":"",onClick:()=>t.onModeChange("split"),title:n("toolbar.viewSplit"),children:m.jsx(Z.Columns2,{})}),m.jsx("button",{className:t.mode==="preview"?"active":"",onClick:()=>t.onModeChange("preview"),title:n("toolbar.viewPreview"),children:m.jsx(Z.PanelRight,{})})]})]})}function Ft({actions:t,context:e,capture:n}){return m.jsx("div",{className:"exmd-host-actions",children:t.map(r=>m.jsx("button",{type:"button",title:r.title,"aria-label":r.title,disabled:r.disabled||r.requiresSelection!==!1&&!e.anchor,onPointerDown:o=>o.preventDefault(),onMouseDown:o=>o.preventDefault(),onClick:()=>{const o=n();!r.disabled&&(r.requiresSelection===!1||o.anchor)&&r.onClick(o)},children:r.icon||r.title},r.id))})}function Ce(t){return{bytes:X.encodeRelativePosition(t)}}function Lt(t){return X.decodeRelativePosition(new Uint8Array(t.bytes))}function De(t,e){if(!Number.isInteger(e)||e<0||e>t.length)throw new RangeError("Invalid Markdown text position")}function Xt(t,e,n){return De(t,e),De(t,n),{kind:"text",anchor:Ce(X.createRelativePositionFromTypeIndex(t,e)),focus:Ce(X.createRelativePositionFromTypeIndex(t,n))}}function Ir(t,e,n){const r=at(t,e,n);return r?{from:Math.min(r.anchor,r.focus),to:Math.max(r.anchor,r.focus)}:null}function at(t,e,n){try{if(n.kind!=="text")return null;const r=X.createAbsolutePositionFromRelativePosition(Lt(n.anchor),t,!1),o=X.createAbsolutePositionFromRelativePosition(Lt(n.focus),t,!1);return!r||!o||r.type!==e||o.type!==e?null:{anchor:r.index,focus:o.index}}catch{return null}}function it(t,e,n){if(De(t,e),De(t,n),e>=n)throw new RangeError("A comment anchor requires a nonempty forward range");return{kind:"markdown-text-range",start:Ce(X.createRelativePositionFromTypeIndex(t,e,0)),end:Ce(X.createRelativePositionFromTypeIndex(t,n,-1)),content:Cr(t,e,n)}}function we(t,e,n){if(!n||n.kind!=="markdown-text-range"||!Array.isArray(n.content)||!n.content.length||n.content&&(!Array.isArray(n.content)||n.content.some(o=>!o||!Number.isSafeInteger(o.client)||o.client<0||!Number.isSafeInteger(o.clock)||o.clock<0||!Number.isSafeInteger(o.length)||o.length<=0)))return null;if(n.content?.length){const o=X.createDeleteSetFromStructStore(t.store);if(n.content.every(c=>{let a=c.clock;for(const s of o.clients.get(c.client)||[]){if(s.clock>a)break;if(s.clock+s.len>a&&(a=s.clock+s.len),a>=c.clock+c.length)return!0}return!1}))return null}const r=at(t,e,{kind:"text",anchor:n.start,focus:n.end});return r&&r.anchor<r.focus?{from:r.anchor,to:r.focus}:null}function Cr(t,e,n){const r=t.doc;if(!r)throw new Error("The text must belong to a Y.Doc");const o=[];for(const l of r.store.clients.values())for(const c of l){if(!(c instanceof X.Item)||c.parent!==t||c.deleted||!c.countable)continue;const a=X.createAbsolutePositionFromRelativePosition(X.createRelativePositionFromJSON({item:c.id,assoc:0}),r,!1);if(!a)continue;const s=Math.max(e,a.index),i=Math.min(n,a.index+c.length);s<i&&o.push({client:c.id.client,clock:c.id.clock+s-a.index,length:i-s})}return o}function Dr(t,e){let n,r,o=[],l=null,c=null,a=!1,s=()=>{};const i=()=>!!(n&&r&&r.source===t.toString()),d=()=>{if(!i())return null;const w=Rt(n,r);return w?it(t,w.from,w.to):null},u=w=>{const k=t.doc&&we(t.doc,t,w);return i()&&k?Tr(n,r,k.from,k.to):[]};return{capture:d,selectionRect:()=>i()&&Rt(n,r)?.range.getBoundingClientRect()||null,clearSelection:()=>{c=null,a=!1},setComments:w=>{o=[...new Map(w.map(k=>[k.id,k])).values()],s()},setActive:w=>{l=w,s()},reveal:w=>{const k=u(w);return k.length?(e.activate(),k[0].startContainer.parentElement?.scrollIntoView({block:"center",inline:"nearest"}),s(),!0):!1},attach:(w,k)=>{n=w,r=k;const T=n.ownerDocument,L=T.defaultView,M=T.createElement("div");M.className="exmd-preview-annotations",M.setAttribute("aria-hidden","true"),Object.assign(M.style,{position:"fixed",inset:"0",pointerEvents:"none",zIndex:"4"}),T.body.append(M);let I=0,R=[];const D=()=>{if(I=0,M.replaceChildren(),R=[],!o.length||!i()||!w.getClientRects().length)return;let h={left:0,top:0,right:L.innerWidth,bottom:L.innerHeight};for(let f=w;f;f=f.parentElement){const x=L.getComputedStyle(f);if(/(auto|scroll|hidden|clip)/.test(x.overflow+x.overflowX+x.overflowY)){const E=f.getBoundingClientRect();h={left:Math.max(h.left,E.left),right:Math.min(h.right,E.right),top:Math.max(h.top,E.top),bottom:Math.min(h.bottom,E.bottom)}}if(f.classList.contains("preview-pane")){const E=f.querySelector(".pane-label")?.getBoundingClientRect();E&&(h.top=Math.max(h.top,E.bottom))}}for(const f of o)if(!(f.resolved||f.deleted))for(const x of u(f.anchor))for(const E of x.getClientRects()){const O=Math.max(E.left,h.left),A=Math.min(E.right,h.right),P=Math.max(E.top,h.top),N=Math.min(E.bottom,h.bottom);if(A<=O||N<=P)continue;const C=T.createElement("span");C.dataset.commentId=f.id,C.className="exmd-preview-comment"+(f.id===l?" exmd-preview-comment-active":""),Object.assign(C.style,{position:"absolute",left:O+"px",top:P+"px",width:A-O+"px",height:N-P+"px",boxSizing:"border-box",borderBottom:"2px solid #d8a12c",background:f.id===l?"#ffd86666":"transparent"}),M.append(C),R.push({id:f.id,left:O,right:A,top:P,bottom:N})}};s=()=>{I||(I=L.requestAnimationFrame(D))};const U=()=>{const h=T.getSelection(),f=h?.anchorNode&&w.contains(h.anchorNode);!f&&!e.isActive()||i()&&(f&&e.activate(),e.isActive()&&(c=d(),e.selectionChanged()))},$=()=>{e.activate(),c=null,a=!1},p=h=>{if(!i()||!T.getSelection()?.isCollapsed)return;const f=[...new Set(R.filter(E=>h.clientX>=E.left&&h.clientX<=E.right&&h.clientY>=E.top&&h.clientY<=E.bottom).map(E=>E.id))];if(!f.length)return;h.preventDefault();const x=f[(f.indexOf(l||"")+1)%f.length];e.click(x)},F=()=>{a=e.isActive()&&!!c,s()};w.addEventListener("pointerdown",$),w.addEventListener("click",p),T.addEventListener("selectionchange",U),T.addEventListener("scroll",s,!0),L.addEventListener("resize",s),L.visualViewport?.addEventListener("resize",s),L.visualViewport?.addEventListener("scroll",s);const _=new ResizeObserver(s);_.observe(w);const b=new MutationObserver(s);for(let h=w;h;h=h.parentElement)b.observe(h,{attributes:!0,attributeFilter:["style","class"]});if(T.fonts?.addEventListener("loadingdone",s),t.observe(F),a&&c&&e.isActive()){const h=u(c);if(h.length){const f=T.createRange(),x=h[h.length-1];f.setStart(h[0].startContainer,h[0].startOffset),f.setEnd(x.endContainer,x.endOffset);const E=T.getSelection();E?.removeAllRanges(),E?.addRange(f)}else c=null,T.getSelection()?.removeAllRanges()}return a=!1,s(),()=>{w.removeEventListener("pointerdown",$),w.removeEventListener("click",p),T.removeEventListener("selectionchange",U),T.removeEventListener("scroll",s,!0),L.removeEventListener("resize",s),L.visualViewport?.removeEventListener("resize",s),L.visualViewport?.removeEventListener("scroll",s),_.disconnect(),b.disconnect(),T.fonts?.removeEventListener("loadingdone",s),t.unobserve(F),L.cancelAnimationFrame(I),M.remove(),n=void 0,r=void 0,s=()=>{}}}}}function Or(t,e,n){if(n.button!==0||n.shiftKey||n.ctrlKey||n.metaKey||n.altKey)return!1;const r=n.target;if(r!==e&&r!==t.dom.parentElement&&r!==t.dom&&r!==t.scrollDOM&&r!==t.contentDOM)return!1;const o=e.getBoundingClientRect(),l=o.width/e.offsetWidth,c=o.height/e.offsetHeight;if(n.clientX<o.left+e.clientLeft*l||n.clientX>=o.left+(e.clientLeft+e.clientWidth)*l||n.clientY>=o.top+(e.clientTop+e.clientHeight)*c)return!1;const a=t.state.doc.length,s=t.coordsAtPos(a);return!s||n.clientY<s.bottom?!1:(t.dispatch({selection:{anchor:a},scrollIntoView:!0}),t.focus(),!0)}function It(t){if(t.length>=1e4)return 150;let e=1;for(let n=0;n<t.length;n++)if(t[n]===`
18
- `&&++e>=500)return 150;return 0}function Nr(t,e,n){const r=n===void 0?It(t):Number.isFinite(n)?Math.min(2e3,Math.max(0,n)):It(t),[o,l]=v.useState(t),c=v.useRef(e);return v.useLayoutEffect(()=>{const a=e&&!c.current;if(c.current=e,!e)return;if(a||r===0){l(t);return}const s=window.setTimeout(()=>l(t),r);return()=>window.clearTimeout(s)},[t,e,r]),r===0?t:o}function jr(t,e){if(!t.length)return e;if(e<=t[0].source)return t[0].target;for(let n=1;n<t.length;n++){const r=t[n-1],o=t[n];if(e<=o.source)return r.target+(o.target-r.target)*(e-r.source)/Math.max(1,o.source-r.source)}return t[t.length-1].target}function _r(t,e,n){let r=0,o=null,l=null,c="",a=[];const s=()=>{const u=t();if(!u)return[];const y=[e.scrollHeight,n.scrollHeight,e.clientWidth,n.clientWidth,u.state.doc.length].join(":");if(c===y&&a.length)return a;c=y;const w=u.documentTop-e.getBoundingClientRect().top+e.scrollTop,k=n.getBoundingClientRect().top-n.scrollTop,T=[{source:0,target:0}],L=new Set;for(const M of n.querySelectorAll(".markdown-body > [data-exmd-source-line]")){const I=Math.max(1,Math.min(u.state.doc.lines,Number(M.dataset.exmdSourceLine)));if(!Number.isFinite(I)||L.has(I))continue;L.add(I),T.push({source:w+u.lineBlockAt(u.state.doc.line(I).from).top,target:M.getBoundingClientRect().top-k});const R=Number(M.dataset.exmdSourceEndLine)+1;R>I&&R<=u.state.doc.lines&&!L.has(R)&&(T.push({source:w+u.lineBlockAt(u.state.doc.line(R).from).top,target:M.getBoundingClientRect().bottom-k}),L.add(R))}T.push({source:e.scrollHeight,target:n.scrollHeight}),a=T.sort((M,I)=>M.source-I.source).filter((M,I,R)=>!I||M.source>R[I-1].source);for(let M=1;M<a.length;M++)a[M].target=Math.max(a[M-1].target,a[M].target);return a},i=()=>{r=0;const u=o;if(o=null,!u)return;const y=u===e?n:e,w=Math.max(0,u.scrollHeight-u.clientHeight),k=Math.max(0,y.scrollHeight-y.clientHeight),T=s(),L=u===e?T:T.map(I=>({source:I.target,target:I.source})).filter((I,R,D)=>!R||I.source>D[R-1].source),M=u.scrollTop<=1?0:u.scrollTop>=w-1?k:Math.max(0,Math.min(k,jr(L,u.scrollTop+u.clientHeight/2)-y.clientHeight/2));l={node:y,top:M},y.scrollTop=M},d=u=>{const y=u.currentTarget;if(l?.node===y&&Math.abs(y.scrollTop-l.top)<1){l=null;return}o=y,r||(r=requestAnimationFrame(i))};return e.addEventListener("scroll",d,{passive:!0}),n.addEventListener("scroll",d,{passive:!0}),()=>{cancelAnimationFrame(r),e.removeEventListener("scroll",d),n.removeEventListener("scroll",d)}}const Gt=1,_e="markdown-ytext",Ue=1,Ur="markdown",Yt="exmd:meta",Te={bootstrap:Symbol("exmd.bootstrap"),remote:Symbol("exmd.remote")};function Be(t){return t.getText(Ur)}function st(t){const e=t.getMap(Yt);return{codec:e.get("codec"),schemaVersion:e.get("schemaVersion")}}function Jt(t,e){const n=Be(t),r=t.getMap(Yt);t.transact(()=>{n.length===0&&e&&n.insert(0,e),r.has("codec")||r.set("codec",_e),r.has("schemaVersion")||r.set("schemaVersion",Ue)},Te.bootstrap)}function Oe(t){const e=st(t);if(e.codec!==_e)throw new Error(`Unsupported codec: ${e.codec}`);if(e.schemaVersion!==Ue)throw new Error(`Unsupported schema version: ${e.schemaVersion}`)}function Br(t){return X.encodeStateAsUpdate(t)}const Qe=["#7357d8","#d9547a","#16866f","#d57828","#3676c8","#8a5b3d"],qr=`# 一起写点什么
19
-
20
- 这是一个支持 **实时协作** 的 Markdown 文档。试试从另一个窗口打开相同链接。
21
-
22
- ## 快速开始
23
-
24
- - 使用上方工具栏插入常用格式
25
- - 拖入或粘贴图片
26
- - 用 Mermaid 描述流程图
27
-
28
- \`\`\`mermaid
29
- flowchart LR
30
- A[想法] --> B{一起讨论}
31
- B --> C[写成文档]
32
- B --> D[继续迭代]
33
- \`\`\`
34
- `;function Hr(){const t=localStorage.getItem("collab-markdown:user");if(t)try{return JSON.parse(t)}catch{}const e={name:`访客 ${Math.floor(100+Math.random()*900)}`,color:Qe[Math.floor(Math.random()*Qe.length)]};return localStorage.setItem("collab-markdown:user",JSON.stringify(e)),e}function Qt(t){const{roomId:e,websocketUrl:n,initialValue:r="",user:o,persistence:l=!0,persistenceKey:c,readOnly:a=!1,enabled:s=!0,locale:i,messages:d}=t,u=v.useRef(i),y=v.useRef(d);u.current=i,y.current=d;const w=v.useRef(()=>{}),k=o?.name,T=o?.color,L=o?.colorLight,M=v.useMemo(()=>{const b=new X.Doc,h=Be(b),f=new Nt.Awareness(b),x=new X.UndoManager(h);return{doc:b,text:h,awareness:f,undoManager:x}},[e]),[I,R]=v.useState("loading"),[D,U]=v.useState(!1),[$,p]=v.useState([]),[F,_]=v.useState();return v.useEffect(()=>{if(!s)return()=>{w.current=()=>{},M.undoManager.destroy(),M.doc.destroy()};const{doc:b,awareness:h,text:f}=M,x=new pr.WebsocketProvider(n,e,b,{awareness:h}),E=l?new gr.IndexeddbPersistence(c||`collab-markdown:${e}`,b):void 0;a?h.setLocalState(null):h.setLocalStateField("user",k&&T?{name:k,color:T,colorLight:L}:Hr());let O=!E,A=!1,P=!1;const N=()=>{if(!(P||!O||!A))try{Oe(b),Jt(b,r),P=!0,U(!0),R("ready")}catch(B){_({code:"SCHEMA_MISMATCH",message:B instanceof Error?B.message:"文档格式不受支持",retryable:!1,cause:B}),R("error")}};E&&E.whenSynced.then(()=>{O=!0,(f.length>0||st(b).codec)&&(P=!0,U(!0)),N()}).catch(B=>{_({code:"INITIALIZATION_FAILED",message:"本地协同数据加载失败",retryable:!0,cause:B}),R("error")});const C=B=>{if(B)if(A=!0,P)try{Oe(b),R("ready")}catch(q){_({code:"SCHEMA_MISMATCH",message:q instanceof Error?q.message:"文档格式不受支持",retryable:!1,cause:q}),R("error")}else N()},W=({status:B})=>R(q=>B==="connected"?q==="ready"?"ready":"syncing":q==="error"?q:"disconnected"),K=()=>{const B=[];x.awareness.getStates().forEach((q,ue)=>{const re=q.user;re&&B.push({clientId:ue,name:re.name||z(u.current,"presence.anonymous",void 0,y.current),color:re.color||Qe[0]})}),p(B)};return w.current=K,x.on("status",W),x.on("sync",C),x.awareness.on("change",K),R(x.wsconnected?"syncing":"loading"),K(),()=>{w.current=()=>{},x.off("status",W),x.off("sync",C),x.awareness.off("change",K),x.destroy(),E?.destroy(),M.undoManager.destroy(),M.doc.destroy()}},[s,r,l,c,a,M,e,T,L,k,n]),v.useEffect(()=>{w.current()},[i,d]),{doc:M.doc,text:M.text,awareness:M.awareness,undoManager:M.undoManager,state:I,ready:D,saveState:"unavailable",collaborators:$,error:F}}async function Wr(t,e){if(e){const n=typeof e=="string"?{endpoint:e}:e,r=new FormData;r.append(n.fieldName||"file",t);const o=await fetch(n.endpoint,{method:"POST",body:r,headers:n.headers,signal:n.signal,credentials:n.credentials});if(!o.ok)throw new Error(z(n.locale,"upload.failed",{status:o.status},n.messages));const l=await o.json(),c=n.resolveUrl?await n.resolveUrl(l):l?.url;if(!c)throw new Error(z(n.locale,"upload.missingUrl",void 0,n.messages));return c}return ct(t)}function ct(t,e={}){return new Promise((n,r)=>{const o=new FileReader;o.onload=()=>n(String(o.result)),o.onerror=()=>r(new Error(z(e.locale,"upload.readFailed",void 0,e.messages))),o.readAsDataURL(t)})}function lt(t,e={}){for(let n=0;n<t.length;n++){const r=t.charCodeAt(n);if(r>=55296&&r<=56319){const o=t.charCodeAt(++n);if(!(o>=56320&&o<=57343))throw new TypeError(z(e.locale,"validation.loneSurrogate",void 0,e.messages))}else if(r>=56320&&r<=57343)throw new TypeError(z(e.locale,"validation.loneSurrogate",void 0,e.messages))}return new File([t],Kr(e.fileName||"document.md"),{type:e.mimeType||"text/markdown;charset=utf-8"})}function $r(t,e={}){const n=lt(t,e),r=URL.createObjectURL(n),o=document.createElement("a");o.href=r,o.download=n.name,o.click(),URL.revokeObjectURL(r)}function Kr(t){const e=t.replace(/[\u0000-\u001f\u007f\\/:*?"<>|]/g,"-").trim().replace(/\.markdown$/i,".md")||"document.md";return/\.md$/i.test(e)?e:`${e}.md`}const Ne=ce.StateEffect.define(),Ze=ce.StateEffect.define(),je=ce.StateEffect.define(),et=ce.StateEffect.define(),Ye=ce.StateField.define({create:()=>({remote:[],comments:[],active:null}),update:(t,e)=>{for(const n of e.effects)n.is(Ne)&&(t={...t,remote:n.value}),n.is(Ze)&&(t={...t,comments:n.value,active:n.value.some(r=>r.id===t.active&&!r.resolved&&!r.deleted)?t.active:null}),n.is(je)&&(t={...t,active:n.value});return t}});class Vr extends Q.WidgetType{constructor(e,n,r,o){super(),this.sessionId=e,this.name=n,this.color=r,this.label=o}sessionId;name;color;label;eq(e){return this.sessionId===e.sessionId&&this.name===e.name&&this.color===e.color&&this.label===e.label}toDOM(){const e=document.createElement("span");e.className="exmd-remote-caret",e.dataset.sessionId=this.sessionId,e.style.setProperty("--exmd-selection-color",this.color),e.setAttribute("aria-label",this.label);const n=e.appendChild(document.createElement("span"));return n.className="exmd-remote-label",n.textContent=this.name,e}ignoreEvent(){return!0}}function zr(t,e){const n=r=>{const o=t.doc;if(!o)return Q.Decoration.none;const l=r.state.field(Ye),c=[];if(e.showRemote()){const a=new Map(l.remote.map(s=>[s.sessionId,s]));for(const s of a.values()){if(!s.selection)continue;const i=at(o,t,s.selection);if(!i)continue;const d=/^#[0-9a-f]{6}$/i.test(s.color)?s.color:"#7357d8",u=Math.min(i.anchor,i.focus),y=Math.max(i.anchor,i.focus);y>u&&c.push(Q.Decoration.mark({class:"exmd-remote-selection",attributes:{"data-session-id":s.sessionId,style:"--exmd-selection-color:"+d}}).range(u,y)),c.push(Q.Decoration.widget({widget:new Vr(s.sessionId,s.name,d,e.cursorLabel?.(s.name)||`${s.name} 的光标`),side:1}).range(i.focus))}}for(const a of l.comments){if(a.resolved||a.deleted)continue;const s=we(o,t,a.anchor);s&&c.push(Q.Decoration.mark({class:"exmd-comment-anchor"+(a.id===l.active?" exmd-comment-active":""),attributes:{"data-comment-id":a.id}}).range(s.from,s.to))}return Q.Decoration.set(c,!0)};return[Ye,Q.ViewPlugin.fromClass(class{decorations;composing=!1;frame=0;constructor(r){this.decorations=n(r)}update(r){if(this.composing||r.view.composing){this.decorations=this.decorations.map(r.changes);return}(r.docChanged||r.viewportChanged||r.transactions.some(o=>o.effects.length))&&(this.decorations=n(r.view))}destroy(){cancelAnimationFrame(this.frame)}},{decorations:r=>r.decorations,eventHandlers:{compositionstart(){cancelAnimationFrame(this.frame),this.composing=!0},compositionend(r,o){cancelAnimationFrame(this.frame),this.frame=requestAnimationFrame(()=>{this.composing=!1,o.dispatch({effects:et.of()})})}}}),Q.EditorView.domEventHandlers({click:(r,o)=>{const l=r.target instanceof Element?r.target.closest("[data-comment-id]"):null;let c=l?.getAttribute("data-comment-id");if(c&&o.dom.contains(l)){const a=o.state.field(Ye),s=o.posAtCoords({x:r.clientX,y:r.clientY}),i=s===null?[c]:[...new Set(a.comments.filter(d=>{const u=!d.deleted&&!d.resolved&&t.doc&&we(t.doc,t,d.anchor);return u&&s>=u.from&&s<u.to}).map(d=>d.id))];i.length&&(c=i[(i.indexOf(a.active||"")+1)%i.length]),o.dispatch({effects:je.of(c)}),e.onAnchorClick(c)}return!1}})]}const Xr=v.forwardRef(function(e,n){if(e.collaboration)return v.createElement(Zt,{...e,ref:n,key:e.collaboration.doc.guid});if(!e.roomId||!e.websocketUrl)throw new Error(z(e.locale,"editor.transportRequired",void 0,e.messages));return v.createElement(Gr,{...e,ref:n,key:e.roomId+":"+e.websocketUrl})}),Gr=v.forwardRef(function(e,n){const r=Qt({roomId:e.roomId,websocketUrl:e.websocketUrl,initialValue:e.initialValue,user:e.user,persistence:e.persistence,persistenceKey:e.persistenceKey,readOnly:e.mode==="readonly",locale:e.locale,messages:e.messages});return m.jsx(Zt,{...e,collaboration:r,standalone:!0,ref:n})}),Yr={lineNumbers:!0,foldGutter:!0,highlightActiveLine:!0,highlightActiveLineGutter:!0,history:!1,historyKeymap:!1},Jr=v.memo(Nn),Zt=v.forwardRef(function({roomId:e,collaboration:n,uploadImage:r,defaultViewMode:o="split",title:l,className:c="",height:a="100vh",syncScroll:s=!0,previewDebounceMs:i,mode:d="edit",resources:u,onUploadProgress:y,onChange:w,onConnectionChange:k,components:T={},standalone:L=!1,selectionActions:M=[],selectionToolbar:I=!0,toolbarActions:R=[],locale:D,messages:U},$){const p=(g,S)=>z(D,g,S,U),F=r??(g=>ct(g,{locale:D,messages:U})),_=l??p("document.title"),b=v.useRef(D),h=v.useRef(U);b.current=D,h.current=U;const f=n,x=d==="readonly"||!f.ready||f.state==="error",E=e||"document",O=v.useRef(null),A=v.useRef(null),P=v.useRef(null),N=v.useRef(null),[C,W]=v.useState(o),[K,B]=v.useState(()=>f.text.toString()),q=Nr(K,C!=="edit",i),[ue,re]=v.useState(!1),[le,Ae]=v.useState(""),dt=v.useRef(0),Se=v.useRef(void 0),xe=v.useRef(void 0),Pe=v.useRef(new Set),Re=v.useRef(void 0),ut=v.useRef(new Set),ee=v.useRef(o==="preview"?"preview":"source"),ft=v.useRef([]),qe=v.useRef(null),[,fn]=v.useState(0),be=v.useCallback(()=>fn(g=>g+1),[]),mt=v.useRef(be),He=v.useRef(()=>{}),j=v.useRef({readOnly:x,session:f,mode:C,standalone:L,onChange:w,mounted:!0});j.current={...j.current,readOnly:x,session:f,mode:C,standalone:L,onChange:w};const te=v.useMemo(()=>Dr(f.text,{activate:()=>{ee.current="preview"},isActive:()=>ee.current==="preview"&&j.current.mode!=="edit",selectionChanged:()=>mt.current(),click:g=>He.current(g)}),[f.text]),ht=()=>{if(j.current.mode==="preview"||j.current.mode!=="edit"&&ee.current==="preview")return te.capture();const g=O.current?.view,S=g?.state.selection.main;return!S||S.empty||g?.state.doc.toString()!==f.text.toString()?null:it(f.text,S.from,S.to)},We=g=>{qe.current=g,te.setActive(g),O.current?.view?.dispatch({effects:je.of(g)})};He.current=g=>{We(g),ut.current.forEach(S=>S(g))},v.useEffect(()=>k?.(f.state),[k,f.state]),v.useEffect(()=>{x&&f.awareness.setLocalStateField("cursor",null)},[x,f.awareness]);const gt=v.useMemo(()=>Q.EditorView.updateListener.of(g=>{(g.focusChanged&&g.view.hasFocus||g.selectionSet&&!g.docChanged)&&(ee.current="source",te.clearSelection(),mt.current()),!(!g.selectionSet&&!g.focusChanged)&&(window.clearTimeout(Re.current),Re.current=window.setTimeout(()=>{const S=j.current,V=S.mounted&&!S.readOnly&&S.mode!=="preview"&&S.session.state==="ready"&&g.view.hasFocus?Xt(S.session.text,g.view.state.selection.main.anchor,g.view.state.selection.main.head):null;Pe.current.forEach(oe=>oe(V))},120))}),[te]);v.useEffect(()=>{if(!s||C!=="split")return;const g=A.current,S=P.current;if(!(!g||!S)&&q===K)return _r(()=>O.current?.view,g,S)},[C,s,q,K]),v.useEffect(()=>{const g=()=>{dt.current+=1;const S=f.text.toString();B(S),j.current.onChange?.(S)};return B(f.text.toString()),f.text.observe(g),()=>f.text.unobserve(g)},[f.text]);const pt=v.useMemo(()=>At.yCollab(f.text,L?f.awareness:null,{undoManager:f.undoManager}),[f.text,f.awareness,f.undoManager,L]),wt=v.useMemo(()=>zr(f.text,{showRemote:()=>!j.current.readOnly&&j.current.mode!=="preview"&&j.current.session.state==="ready",onAnchorClick:g=>He.current(g),cursorLabel:g=>z(b.current,"presence.cursor",{name:g},h.current)}),[f.text]),xt=v.useMemo(()=>ce.EditorState.transactionFilter.of(g=>g.docChanged&&j.current.readOnly&&!g.annotation(At.ySyncAnnotation)?[]:g),[]),bt=v.useMemo(()=>ce.Prec.highest(Q.keymap.of([{key:"Mod-z",run:()=>(j.current.readOnly||j.current.session.undoManager.undo(),!0)},{key:"Mod-Shift-z",run:()=>(j.current.readOnly||j.current.session.undoManager.redo(),!0)},{key:"Mod-y",run:()=>(j.current.readOnly||j.current.session.undoManager.redo(),!0)}])),[]),vt=v.useMemo(()=>ce.Prec.highest(Q.EditorView.domEventHandlers({beforeinput:g=>g.inputType!=="historyUndo"&&g.inputType!=="historyRedo"?!1:(g.preventDefault(),j.current.readOnly||(g.inputType==="historyUndo"?j.current.session.undoManager.undo():j.current.session.undoManager.redo()),!0)})),[]),mn=v.useMemo(()=>[ce.EditorState.lineSeparator.of(`
35
- `),_n.markdown(),Tt.syntaxHighlighting(Tt.defaultHighlightStyle),Q.EditorView.lineWrapping,vt,pt,wt,xt,bt,gt],[wt,pt,xt,vt,gt,bt]),J=()=>O.current?.view,hn=p("presence.cursor",{name:" "});v.useEffect(()=>{J()?.dispatch({effects:et.of()})},[hn]),v.useEffect(()=>{C==="preview"&&(ee.current="preview"),C==="edit"&&(ee.current="source",te.clearSelection()),x&&(xe.current?.abort(),re(!1)),(x||C==="preview"||f.state!=="ready")&&(window.clearTimeout(Re.current),J()?.dispatch({effects:Ne.of([])}),Pe.current.forEach(g=>g(null))),J()?.dispatch({effects:et.of()}),C!=="preview"&&J()?.requestMeasure()},[x,C,f.state]),v.useEffect(()=>{const g=P.current||A.current;if(!g||!M.length&&!R.length)return;const S=g.ownerDocument,V=S.defaultView;let oe=0;const ae=()=>{oe||(oe=V.requestAnimationFrame(()=>{oe=0,be()}))};return S.addEventListener("scroll",ae,!0),S.addEventListener("selectionchange",ae),V.addEventListener("resize",ae),V.visualViewport?.addEventListener("resize",ae),()=>{S.removeEventListener("scroll",ae,!0),S.removeEventListener("selectionchange",ae),V.removeEventListener("resize",ae),V.visualViewport?.removeEventListener("resize",ae),V.cancelAnimationFrame(oe)}},[M.length,R.length,be]);const gn=g=>{const S=J();S&&!x&&Fr(S,g)},pn=()=>{const g=J();g&&Me(g,p("insert.diagram"))},wn=()=>{const g=J();g&&Me(g,`
36
- $$
37
- E = mc^2
38
- $$
39
- `)},xn=g=>{const S=J();S&&Me(S,`
40
- \`\`\`${g}
41
- ${p("insert.codePlaceholder")}
42
- \`\`\`
43
- `)},bn=g=>{const S=J();if(!S)return;const V=S.state.selection.main,oe=S.state.sliceDoc(V.from,V.to)||p("format.colorPlaceholder");Me(S,`<span data-color="${g}">${oe}</span>`)},$e=v.useCallback(async g=>{if(!g||!g.type.startsWith("image/")){Ae(z(D,"notice.imageRequired",void 0,U));return}if(j.current.readOnly){Ae(z(D,"notice.readOnly",void 0,U));return}const S=J();if(!S)return;const V=S.state.selection.main,oe=X.createRelativePositionFromTypeIndex(f.text,V.from),ae=X.createRelativePositionFromTypeIndex(f.text,V.to);xe.current?.abort();const ye=new AbortController;xe.current=ye,re(!0),Ae("");try{const me=u?.uploadImage?await u.uploadImage(g,{signal:ye.signal,onProgress:Pn=>y?.(Pn)}):await F(g);if(ye.signal.aborted||j.current.readOnly||!j.current.mounted)return;const Sn=typeof me=="string"?me:me.path,Fe=f.text.doc,ke=Fe&&X.createAbsolutePositionFromRelativePosition(oe,Fe),Xe=Fe&&X.createAbsolutePositionFromRelativePosition(ae,Fe);if(!ke||!Xe||ke.type!==f.text||Xe.type!==f.text)return;const Et=`![${g.name.replace(/\.[^.]+$/,"")}](${Sn})`;S.dispatch({changes:{from:ke.index,to:Math.max(ke.index,Xe.index),insert:Et},selection:{anchor:ke.index+Et.length}})}catch(me){!ye.signal.aborted&&j.current.mounted&&Ae(me instanceof Error?me.message:z(D,"notice.uploadFailed",void 0,U))}finally{j.current.mounted&&xe.current===ye&&(re(!1),N.current&&(N.current.value=""))}},[x,D,U,y,u,f.text,F]);v.useEffect(()=>(j.current.mounted=!0,()=>{j.current.mounted=!1,xe.current?.abort(),window.clearTimeout(Re.current),Pe.current.forEach(g=>g(null))}),[]),v.useImperativeHandle($,()=>Qr(J,f,()=>j.current.readOnly||!j.current.mounted,dt,Pe.current,ut.current,()=>{ee.current="source",j.current.mode==="preview"&&W("split")},{capture:ht,render:g=>{ft.current=g,te.setComments(g),J()?.dispatch({effects:Ze.of(g)}),g.some(S=>S.id===qe.current&&!S.resolved&&!S.deleted)||We(null)},activate:We,reveal:g=>{if(j.current.mode==="preview"||ee.current==="preview"&&j.current.mode!=="edit")return te.reveal(g);const S=J(),V=we(f.doc,f.text,g);return!S||!V?!1:(S.dispatch({selection:{anchor:V.from,head:V.to},effects:Q.EditorView.scrollIntoView(V.from,{y:"center"})}),!0)}}),[f.text,f.undoManager,te]);const vn=T.Header||en,yn=T.Toolbar||zt,kn=T.Preview||Vt,En=T.Loading||tn,Mn=T.Footer||nn,Ke=()=>({view:j.current.mode==="preview"?"preview":j.current.mode==="edit"?"source":ee.current,anchor:ht()}),fe=Ke(),Ve=J();let ve=fe.view==="preview"?te.selectionRect():null;if(fe.anchor&&fe.view==="source"&&Ve){const g=Ve.coordsAtPos(Ve.state.selection.main.from);g&&(ve=new DOMRect(g.left,g.top,0,g.bottom-g.top))}const yt=I&&M.length>0&&!!(fe.anchor&&ve),kt=[...R,...yt?[]:M],Tn=kt.length?m.jsx(Ft,{actions:kt,context:fe,capture:Ke}):void 0,ze=A.current?.ownerDocument,An=v.useCallback(g=>{g.dispatch({effects:[Ze.of(ft.current),je.of(qe.current)]}),be()},[be]);return f.ready&&Se.current===void 0&&(Se.current=f.text.toString()),m.jsxs("div",{className:`exmd-editor app-shell ${c}`,style:{height:a},lang:jt(D),children:[m.jsx(vn,{title:_,roomId:E,session:f,locale:D,messages:U}),m.jsx(yn,{hostActions:Tn,readOnly:x,mode:C,onModeChange:W,onAction:gn,onUndo:()=>{j.current.readOnly||f.undoManager.undo()},onRedo:()=>{j.current.readOnly||f.undoManager.redo()},onImage:()=>{j.current.readOnly||N.current?.click()},onDiagram:pn,onFormula:wn,onCodeBlock:xn,onColor:bn,locale:D,messages:U}),yt&&ze&&ve&&jn.createPortal(m.jsx("div",{className:"exmd-selection-toolbar",role:"toolbar","aria-label":p("selection.toolbar"),style:{position:"fixed",left:Math.max(8,Math.min(ve.left,ze.documentElement.clientWidth-180)),top:Math.max(8,ve.top-42),zIndex:1e3},children:m.jsx(Ft,{actions:M,context:fe,capture:Ke})}),ze.body),m.jsx("input",{ref:N,hidden:!0,type:"file",accept:"image/*",onChange:g=>{$e(g.target.files?.[0])}}),(ue||le)&&m.jsx("div",{className:le?"notice error":"notice",children:ue?p("notice.uploading"):le}),m.jsxs("main",{className:`workspace mode-${C}`,onDragOver:g=>{x||g.preventDefault()},onDrop:g=>{if(x)return;const S=[...g.dataTransfer.files].find(V=>V.type.startsWith("image/"));S&&(g.preventDefault(),$e(S))},onPaste:g=>{if(x)return;const S=[...g.clipboardData.files].find(V=>V.type.startsWith("image/"));S&&(g.preventDefault(),$e(S))},children:[m.jsxs("section",{ref:A,className:"editor-pane",hidden:C==="preview",onPointerDown:()=>{ee.current="source",te.clearSelection()},onMouseDownCapture:g=>{const S=O.current?.view;S&&Or(S,g.currentTarget,g.nativeEvent)&&(g.preventDefault(),g.stopPropagation())},"aria-label":p("editor.pane"),children:[m.jsxs("div",{className:"pane-label",children:[m.jsx("span",{children:"MARKDOWN"}),m.jsx("span",{children:p("editor.characters",{count:K.length})})]}),Se.current!==void 0?m.jsx(Jr,{ref:O,onCreateEditor:An,value:Se.current,extensions:mn,editable:!x,readOnly:x,basicSetup:Yr}):m.jsx(En,{state:f.state,errorMessage:f.error?vr(f.error,D,U):void 0,locale:D,messages:U})]}),C!=="edit"&&m.jsxs("section",{ref:P,className:"preview-pane","aria-busy":q!==K,onPointerDown:()=>{ee.current="preview"},"aria-label":p("preview.pane"),children:[m.jsxs("div",{className:"pane-label",children:[m.jsx("span",{children:p("preview.label")}),m.jsx("span",{children:p(q!==K?"preview.updating":s&&C==="split"?"preview.syncScroll":"preview.live")})]}),m.jsx(kn,{value:q,resolveImageUrl:u?.resolveUrl,interaction:te,locale:D,messages:U})]})]}),m.jsx(Mn,{readOnly:x,locale:D,messages:U})]})});function en({title:t,roomId:e,session:n,locale:r,messages:o}){const l=(s,i)=>z(r,s,i,o),c=n.state==="ready"?m.jsxs(m.Fragment,{children:[m.jsx(Z.Check,{})," ",l("status.ready")]}):n.state==="error"?m.jsxs(m.Fragment,{children:[m.jsx(Z.TriangleAlert,{})," ",l("status.error")]}):n.state==="disconnected"?m.jsxs(m.Fragment,{children:[m.jsx(Z.CloudOff,{})," ",n.ready?l("status.offlineEditing"):l("status.offline")]}):m.jsxs(m.Fragment,{children:[m.jsx(Z.LoaderCircle,{className:"spin"})," ",n.state==="syncing"?l("status.syncing"):l("status.loading")]}),a=l("presence.online",{count:n.collaborators.length});return m.jsxs("header",{className:"topbar",children:[m.jsxs("div",{className:"brand",children:[m.jsx("span",{className:"brand-mark",children:"墨"}),m.jsxs("div",{children:[m.jsx("strong",{children:t}),m.jsx("small",{children:l("header.room",{roomId:e})})]})]}),m.jsx("div",{className:`sync-state ${n.state}`,children:c}),m.jsxs("div",{className:"presence","aria-label":a,children:[m.jsx("div",{className:"avatars",children:n.collaborators.slice(0,4).map(s=>m.jsx("span",{title:s.name,style:{background:s.color},children:s.name.slice(0,1)},s.clientId))}),m.jsx("span",{children:a})]})]})}function tn({errorMessage:t,locale:e,messages:n}){return m.jsx("div",{className:"collaboration-loading",children:t||z(e,"loading.document",void 0,n)})}function nn({readOnly:t,locale:e,messages:n}){const r=o=>z(e,o,void 0,n);return m.jsxs("footer",{children:[m.jsx("span",{children:r("footer.formats")}),m.jsx("span",{children:r(t?"footer.readOnly":"footer.dropImages")})]})}function Qr(t,e,n,r,o,l,c,a){const s=(i,d={})=>Zr(e.text.toString(),i,d,r.current);return{focus:()=>t()?.focus(),getMarkdown:()=>e.text.toString(),replaceMarkdown:(i,d={})=>{const u=t();if(!u||n())return!1;const y=e.text.toString();return d.expectedMarkdown!==void 0&&d.expectedMarkdown!==y||u.state.doc.toString()!==y?!1:(i===y||(e.undoManager.stopCapturing(),u.dispatch({changes:{from:0,to:u.state.doc.length,insert:i},selection:{anchor:0}}),e.undoManager.stopCapturing()),!0)},getEditorView:t,insertText:i=>{const d=t();return!d||n()?!1:(Me(d,i),!0)},find:s,reveal:i=>{const d=t();return!d||i.revision!==r.current||i.from<0||i.to>d.state.doc.length?!1:(c(),d.dispatch({selection:{anchor:i.from,head:i.to},effects:Q.EditorView.scrollIntoView(i.from,{y:"center"})}),d.focus(),!0)},replace:(i,d)=>{const u=t();return!u||n()||i.revision!==r.current||u.state.sliceDoc(i.from,i.to)!==i.text?!1:(e.undoManager.stopCapturing(),u.dispatch({changes:{from:i.from,to:i.to,insert:d}}),e.undoManager.stopCapturing(),!0)},replaceAll:(i,d,u={})=>{const y=t();if(!y||n())return 0;const w=s(i,u);return w.length?(e.undoManager.stopCapturing(),y.dispatch({changes:w.map(k=>({from:k.from,to:k.to,insert:d}))}),e.undoManager.stopCapturing(),w.length):0},undo:()=>n()||!e.undoManager.canUndo()?!1:(e.undoManager.undo(),!0),redo:()=>n()||!e.undoManager.canRedo()?!1:(e.undoManager.redo(),!0),queryFormatState:()=>{const d=t()?.state.selection.main;return{selection:{from:d?.from||0,to:d?.to||0},canUndo:!n()&&e.undoManager.canUndo(),canRedo:!n()&&e.undoManager.canRedo()}},onSelectionChange:i=>(o.add(i),()=>o.delete(i)),renderRemoteSelections:i=>{const d=t();!d||n()||d.dispatch({effects:Ne.of(i)})},clearRemoteSelections:()=>{t()?.dispatch({effects:Ne.of([])})},renderAnchors:a.render,setActiveAnchor:a.activate,clearAnchors:()=>{a.render([]),a.activate(null)},onAnchorClick:i=>(l.add(i),()=>l.delete(i)),captureAnchor:a.capture,resolveAnchor:i=>we(e.doc,e.text,i),revealAnchor:a.reveal}}function Zr(t,e,n,r){if(!e)return[];const o=n.caseSensitive?t:t.toLocaleLowerCase(),l=n.caseSensitive?e:e.toLocaleLowerCase(),c=[];let a=0;for(;a<=o.length-l.length;){const s=o.indexOf(l,a);if(s<0)break;const i=s+e.length;c.push({id:`${r}:${s}:${i}`,from:s,to:i,text:t.slice(s,i),revision:r}),a=Math.max(i,s+1)}return c}const tt="text/markdown;charset=utf-8",rn=512*1024;function on(t,e){return{code:"RESOURCE_REFERENCES_PRESERVED",message:z(t,"markdown.resourcePreserved",void 0,e)}}function eo(t){const e=new Set;for(const n of t.matchAll(/\r\n|\r|\n/g))e.add(n[0]===`\r
44
- `?"crlf":n[0]==="\r"?"cr":"lf");return e.size>1?"mixed":e.values().next().value||"none"}async function to(t,e={}){const n=e.maxBytes??rn,r=(d,u)=>z(e.locale,d,u,e.messages);if(!Number.isSafeInteger(n)||n<0)throw new RangeError(r("validation.nonNegativeInteger",{name:"maxBytes"}));const o=(d,u)=>({ok:!1,error:{code:d,message:u},warnings:[]});if(!/\.(md|markdown)$/i.test(t.name))return o("UNSUPPORTED_EXTENSION",r("markdown.unsupportedExtension"));if(t.size>n)return o("FILE_TOO_LARGE",r("markdown.fileTooLarge",{maxBytes:n}));let l;try{l=new Uint8Array(await t.arrayBuffer())}catch{return o("READ_FAILED",r("markdown.readFailed"))}if(l.byteLength>n)return o("FILE_TOO_LARGE",r("markdown.fileTooLarge",{maxBytes:n}));let c;const a=l[0]===239&&l[1]===187&&l[2]===191;try{c=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(a?l.subarray(3):l)}catch{return o("INVALID_UTF8",r("markdown.invalidUtf8"))}if(c.includes("\0"))return o("BINARY_CONTENT",r("markdown.binary"));const s=eo(c),i=[on(e.locale,e.messages)];return a&&i.unshift({code:"UTF8_BOM_REMOVED",message:r("markdown.bomRemoved")}),s==="mixed"&&i.push({code:"MIXED_LINE_ENDINGS",message:r("markdown.mixedLineEndings")}),{ok:!0,markdown:c,fileName:t.name,byteLength:l.byteLength,encoding:"utf-8",hadBom:a,lineEndings:s,warnings:i}}function no(t,e={}){const n=lt(t,{fileName:e.fileName,mimeType:tt,locale:e.locale,messages:e.messages});return{blob:n,fileName:n.name,mimeType:tt,warnings:[on(e.locale,e.messages)]}}const nt="application/pdf",an=25*1024*1024,sn=100,cn=4e7,ln=3e4;class G extends Error{code;cause;constructor(e,n,r){super(n),this.name="PdfFileError",this.code=e,this.cause=r}}function ie(t,e){if(t?.aborted)throw new G("ABORTED",e("pdf.aborted"))}function Le(t,e,n,r){const o=t??e;if(!Number.isSafeInteger(o)||o<=0)throw new RangeError(r("validation.positiveInteger",{name:n}));return o}function Y(t,e){t.some(n=>n.code===e.code&&n.page===e.page&&n.path===e.path)||t.push(e)}function dn(t){if(/^#/u.test(t))return!0;try{const e=new URL(t);return e.protocol==="http:"||e.protocol==="https:"||e.protocol==="mailto:"}catch{return!1}}function ro(t){if(typeof t=="string")return dn(t)?t:void 0}async function oo(t,e,n,r){ie(n,r);try{if((t instanceof ArrayBuffer||ArrayBuffer.isView(t)?t.byteLength:t.size)>e)throw new G("FILE_TOO_LARGE",r("pdf.fileTooLarge",{maxBytes:e}));const l=t instanceof ArrayBuffer?new Uint8Array(t):ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(await t.arrayBuffer());if(ie(n,r),l.byteLength>e)throw new G("FILE_TOO_LARGE",r("pdf.fileTooLarge",{maxBytes:e}));return l}catch(o){throw o instanceof G?o:new G("READ_FAILED",r("pdf.readFailed"),o)}}function pe(t){const e=Array.isArray(t.transform)?t.transform:[1,0,0,1,0,0],n=Number(e[4])||0,r=Number(e[5])||0,o=Math.abs(Number(t.width)||0),l=Math.abs(Number(t.height)||Math.abs(Number(e[3])||10));return[n,r-l*.25,n+o,r+l]}function un(t,e){const n=Math.min(e[0],e[2]),r=Math.min(e[1],e[3]),o=Math.max(e[0],e[2]),l=Math.max(e[1],e[3]);return t[0]<=o&&t[2]>=n&&t[1]<=l&&t[3]>=r}function ao(t){const e=t.filter(r=>typeof r.str=="string"&&r.str.length>0).map(r=>({item:r,box:pe(r)})).sort((r,o)=>o.box[1]-r.box[1]||r.box[0]-o.box[0]),n=[];for(const r of e){const o=(r.box[1]+r.box[3])/2,l=Math.max(2,(r.box[3]-r.box[1])*.65);let c=n.find(a=>Math.abs(a.y-o)<=l);c||(c={y:o,items:[],text:""},n.push(c)),c.items.push(r.item)}for(const r of n)r.items.sort((o,l)=>pe(o)[0]-pe(l)[0]),r.text=r.items.map(o=>o.str).join("").replace(/[ \t]+/gu," ").trim();return n.sort((r,o)=>o.y-r.y)}function io(t,e,n){const r=t.items.filter(s=>un(pe(s),e)).map(s=>s.str).join("").trim();if(!r)return;const o=r.replace(/[\[\]]/gu,""),l=n.replace(/[()\\]/gu,"\\$&"),c=`[${o}](${l})`,a=t.text.indexOf(r);a>=0&&!t.text.includes(`](${l})`)&&(t.text=t.text.slice(0,a)+c+t.text.slice(a+r.length))}function so(t){let e=4294967295;for(const n of t){e^=n;for(let r=0;r<8;r++)e=e>>>1^(e&1?3988292384:0)}return(e^4294967295)>>>0}function Je(t,e){const n=new Uint8Array(12+e.length),r=new DataView(n.buffer);r.setUint32(0,e.length);for(let o=0;o<4;o++)n[4+o]=t.charCodeAt(o);return n.set(e,8),r.setUint32(8+e.length,so(n.subarray(4,8+e.length))),n}function co(t){const e=[new Uint8Array([120,1])];let n=0;for(;n<t.length||n===0;){const a=Math.min(65535,t.length-n),s=n+a>=t.length,i=new Uint8Array(5+a);i[0]=s?1:0,i[1]=a&255,i[2]=a>>>8;const d=~a&65535;if(i[3]=d&255,i[4]=d>>>8,i.set(t.subarray(n,n+a),5),e.push(i),n+=a,s)break}let r=1,o=0;for(const a of t)r=(r+a)%65521,o=(o+r)%65521;e.push(new Uint8Array([o>>>8&255,o&255,r>>>8&255,r&255]));const l=new Uint8Array(e.reduce((a,s)=>a+s.length,0));let c=0;for(const a of e)l.set(a,c),c+=a.length;return l}function lo(t){const e=Number(t?.width),n=Number(t?.height),r=t?.data instanceof Uint8Array?t.data:ArrayBuffer.isView(t?.data)?new Uint8Array(t.data.buffer,t.data.byteOffset,t.data.byteLength):void 0;if(!Number.isInteger(e)||!Number.isInteger(n)||e<=0||n<=0||!r)return;const o=t.kind===de.ImageKind.GRAYSCALE_1BPP?1:t.kind===de.ImageKind.RGB_24BPP?3:4;if(o===1&&r.length<e*n||o>1&&r.length<e*n*o)return;const l=new Uint8Array(n*(e*4+1));for(let k=0;k<n;k++){l[k*(e*4+1)]=0;for(let T=0;T<e;T++){const L=k*e*o+T*o,M=k*(e*4+1)+1+T*4,I=r[L];l[M]=I,l[M+1]=o===1?I:r[L+1],l[M+2]=o===1?I:r[L+2],l[M+3]=o===4?r[L+3]:255}}const c=new Uint8Array(13);new DataView(c.buffer).setUint32(0,e),new DataView(c.buffer).setUint32(4,n),c[8]=8,c[9]=6;const a=new Uint8Array([137,80,78,71,13,10,26,10]),s=co(l),i=Je("IHDR",c),d=Je("IDAT",s),u=Je("IEND",new Uint8Array),y=new Uint8Array(a.length+i.length+d.length+u.length);let w=0;return y.set(a,w),w+=a.length,y.set(i,w),w+=i.length,y.set(d,w),w+=d.length,y.set(u,w),y}async function uo(t,e){if(typeof OffscreenCanvas<"u"){const n=new OffscreenCanvas(t,e);return{canvas:n,context:n.getContext("2d")}}if(typeof document<"u"){const n=document.createElement("canvas");return n.width=t,n.height=e,{canvas:n,context:n.getContext("2d")}}try{const o=(await import(["@napi-rs","canvas"].join("/"))).createCanvas(t,e);return{canvas:o,context:o.getContext("2d")}}catch{return}}function fo(t,e,n,r){if(t instanceof G)return t;const o=String(t?.message||t||"");if(/password|encrypted|encryptedpdf/iu.test(o))return new G("PASSWORD_REQUIRED",r("pdf.passwordRequired"),t);const l=o.replace(/\s+/gu," ").trim().slice(0,180);return new G(e,l?r("pdf.errorDetail",{message:n,detail:l}):n,t)}async function mo(t,e={}){const n=Bt(e.locale,e.messages),r=Le(e.maxBytes,an,"maxBytes",n),o=Le(e.maxPages,sn,"maxPages",n),l=Le(e.maxImagePixels,cn,"maxImagePixels",n),c=Le(e.timeoutMs,ln,"timeoutMs",n),a=await oo(t,r,e.signal,n),s=[];let i,d,u;try{const y=new Promise((R,D)=>{i=setTimeout(()=>D(new G("TIMEOUT",n("pdf.timeout",{timeoutMs:c}))),c)});d=de.getDocument({data:a,disableAutoFetch:!0,disableStream:!0,isOffscreenCanvasSupported:!1,isImageDecoderSupported:!1,useSystemFonts:!1,verbosity:0}),d.onPassword=(R,D)=>{(D===de.PasswordResponses.NEED_PASSWORD||D===de.PasswordResponses.INCORRECT_PASSWORD)&&(u=new G("PASSWORD_REQUIRED",n("pdf.passwordRequired")),d.destroy().catch(()=>{}))};const w=await Ee(d.promise,y,e.signal,n);if(w.numPages>o)throw new G("PAGE_LIMIT_EXCEEDED",n("pdf.pageLimit",{maxPages:o}));const k=[],T=[];for(let R=1;R<=w.numPages;R++){ie(e.signal,n);const D=await Ee(w.getPage(R),y,e.signal,n),U=await Ee(D.getTextContent({normalizeWhitespace:!1,disableCombineTextItems:!1}),y,e.signal,n),$=ao(U.items),p=await Ee(D.getAnnotations({intent:"display"}),y,e.signal,n);for(const h of p){const f=h.url??h.unsafeUrl,x=ro(f)??(typeof h.dest=="string"&&h.dest.startsWith("#")?h.dest:void 0);if(!x){(f||h.dest)&&Y(s,{code:f?"UNSAFE_URL_SKIPPED":"EXTERNAL_URL_SKIPPED",message:n("pdf.unsafeLink"),page:R});continue}const E=$.find(O=>O.items.some(A=>un(pe(A),h.rect||[])));E&&io(E,h.rect||[],x)}const F=$.map(h=>h.text).filter(Boolean),_=$.flatMap(h=>h.items.map(f=>Math.round(pe(f)[0]/12)));new Set(_).size>2&&$.length>4&&Y(s,{code:"MULTI_COLUMN_LAYOUT",message:n("pdf.multiColumn"),page:R});const b=[];try{const h=await Ee(D.getOperatorList({intent:"display"}),y,e.signal,n),f=[];let x,E=0;const O=(A,P)=>{try{const N=Number(A?.width)||0,C=Number(A?.height)||0;if(N*C>l)throw new G("IMAGE_PIXEL_LIMIT",n("pdf.imagePixelLimit",{maxImagePixels:l}));const W=lo(A);if(!W)throw new Error(n("pdf.pngFailed"));b.push({key:`pdf-resource/${R}-${P}.png`,bytes:W,filename:`page-${R}-image-${P}.png`,mimeType:"image/png"})}catch(N){N instanceof G&&(x=N),Y(s,{code:"IMAGE_EXTRACT_FAILED",message:n("pdf.imageSkipped"),page:R})}};for(let A=0;A<h.fnArray.length;A++){const P=h.fnArray[A],N=h.argsArray[A];if(!(P===de.OPS.paintImageXObject||P===de.OPS.paintInlineImageXObject||P===de.OPS.paintImageMaskXObject)||!N?.[0])continue;E++;const W=E;if(typeof N[0]=="string"){const K=N[0];f.push(new Promise(B=>{D.objs.get(K,q=>{O(q,W),B()})}))}else O(N[0],W)}if(f.length){const A=D.getViewport({scale:1}),P=await uo(Math.max(1,Math.ceil(A.width)),Math.max(1,Math.ceil(A.height)));if(P?.context){if(await D.render({canvasContext:P.context,canvas:P.canvas,viewport:A,annotationMode:0}).promise,await Promise.all(f),x)throw x}else Y(s,{code:"IMAGE_EXTRACT_FAILED",message:n("pdf.canvasUnavailable"),page:R})}if(x)throw x}catch(h){if(h instanceof G)throw h;Y(s,{code:"IMAGE_EXTRACT_FAILED",message:n("pdf.imageParseFailed"),page:R})}if(b.sort((h,f)=>h.key.localeCompare(f.key,void 0,{numeric:!0})),T.push(...b),!F.length&&!b.length&&Y(s,{code:"NO_TEXT_EXTRACTED",message:n("pdf.noTextPage"),page:R}),b.length){F.length&&F.push("");for(const h of b)F.push(`![${h.alt||n("pdf.imageAlt")}](${h.key})`)}k.push(F.join(`
45
- `)),F.some(h=>h.includes("|"))&&Y(s,{code:"COMPLEX_TABLE",message:n("pdf.complexTableImport"),page:R}),D.cleanup?.()}const M=(await w.getMetadata().catch(()=>{}))?.info||{},I=M.Title||M.Author?{title:M.Title||void 0,author:M.Author||void 0}:void 0;return k.some(Boolean)||Y(s,{code:"NO_TEXT_EXTRACTED",message:n("pdf.noText")}),await w.destroy(),{ok:!0,markdown:k.join(`
46
-
47
- `),resources:T,metadata:I,warnings:s}}catch(y){try{await d?.destroy?.()}catch{}throw u||fo(y,"INVALID_PDF",n("pdf.invalid"),n)}finally{i&&clearTimeout(i)}}async function Ee(t,e,n,r){if(ie(n,r),!n)return Promise.race([t,e]);let o;const l=new Promise((c,a)=>{o=()=>a(new G("ABORTED",r("pdf.aborted"))),n.addEventListener("abort",o,{once:!0})});try{return await Promise.race([t,e,l])}finally{o&&n.removeEventListener("abort",o)}}async function Ct(t,e,n){if(ie(e,n),!e)return t;let r;const o=new Promise((l,c)=>{r=()=>c(new G("ABORTED",n("pdf.aborted"))),e.addEventListener("abort",r,{once:!0})});try{return await Promise.race([t,o])}finally{r&&e.removeEventListener("abort",r)}}function he(t,e,n){const r=[],o=/(!?)\[([^\]]*)\]\(([^\s)]+)(?:\s+["']([^"']*)["'])?\)|(`+)([\s\S]*?)\5|(\*\*|__)([\s\S]*?)\7|(~~)([\s\S]*?)\9|(\*|_)([^\n]*?)\11|(\$\$?)([^$]+)\12/gu;let l=0;for(const a of t.matchAll(o)){const s=a.index??0;if(s>l&&r.push({kind:"text",text:t.slice(l,s)}),a[1]==="!")r.push({kind:"image",text:a[2],alt:a[2],path:a[3]});else if(a[2]!==void 0){const i=a[3];dn(i)?r.push({kind:"link",text:a[2],href:i}):(r.push({kind:"text",text:a[2]}),e.push({code:"UNSAFE_URL_SKIPPED",message:n("pdf.unsafeLinkText"),path:i}))}else a[6]!==void 0?r.push({kind:"code",text:a[6]}):a[8]!==void 0?r.push({kind:"bold",text:a[8]}):a[10]!==void 0?r.push({kind:"strike",text:a[10]}):a[12]!==void 0?r.push({kind:"italic",text:a[12]}):a[14]!==void 0&&(r.push({kind:"math",text:a[14]}),Y(e,{code:"MATH_DEGRADED",message:n("pdf.mathDegraded")}));l=s+a[0].length}l<t.length&&r.push({kind:"text",text:t.slice(l)});const c=a=>a.replace(/\\([\\`*{}\[\]()#+.!_>|~-])/gu,"$1");for(const a of r)a.text=c(a.text);return r.length?r:[{kind:"text",text:c(t)}]}function ho(t,e,n){const r=t.replace(/<!--([\s\S]*?)-->/gu,"").replace(/\r\n?/gu,`
48
- `).split(`
49
- `),o=[],l=s=>!!(r[s]?.includes("|")&&r[s+1]&&/^\s*\|?\s*:?-{3,}:?\s*(?:\|\s*:?-{3,}:?\s*)+\|?\s*$/u.test(r[s+1])),c=s=>{const i=r[s];return!!(i&&(l(s)||/^\s*(```+|~~~+)/u.test(i)||/^\s{0,3}#{1,6}\s+/u.test(i)||/^\s*(---+|\*\*\*+|___+)\s*$/u.test(i)||/^\s*!\[[^\]]*\]\(/u.test(i)||/^\s*([-+*]|\d+[.)])\s+/u.test(i)||/^\s*>\s?/u.test(i)))};let a=0;for(;a<r.length;){const s=r[a];if(!s.trim()){a++;continue}const i=s.match(/^\s*(```+|~~~+)[ \t]*(.*?)\s*$/u);if(i){const k=[],T=i[1];for(a++;a<r.length&&!new RegExp(`^\\s*${T[0]}{${T.length},}\\s*$`,"u").test(r[a]);)k.push(r[a++]);a<r.length&&a++;const L=i[2]?.trim().split(/\s+|\|/u)[0]||void 0;o.push({kind:"code",text:k.join(`
50
- `),language:L});continue}const d=s.match(/^\s{0,3}(#{1,6})\s+(.+?)\s*#*\s*$/u);if(d){o.push({kind:"heading",level:d[1].length,text:d[2]}),a++;continue}if(/^\s*(---+|\*\*\*+|___+)\s*$/u.test(s)){o.push({kind:"rule"}),a++;continue}const u=s.match(/^\s*!\[([^\]]*)\]\(([^\s)]+)(?:\s+["']([^"']*)["'])?\)\s*$/u);if(u){o.push({kind:"image",alt:u[1],path:u[2]}),a++;continue}const y=s.match(/^\s*([-+*]|\d+[.)])\s+(.+)$/u);if(y){const k=/^\d/u.test(y[1]),T=[];for(;a<r.length;){const L=r[a].match(/^\s*([-+*]|\d+[.)])\s+(.+)$/u);if(!L||/^\d/u.test(L[1])!==k)break;T.push(L[2]),a++}o.push({kind:"list",ordered:k,items:T});continue}if(l(a)){const k=[],T=L=>{const M=L.trim().replace(/^\||\|$/gu,""),I=[];let R="",D=!1,U=0;for(const $ of M){if(D){R+=$,D=!1;continue}if($==="\\"){D=!0,R+=$;continue}if($==="`"){U=U?0:1,R+=$;continue}if($==="|"&&!U){I.push(R.trim()),R="";continue}R+=$}return D&&(R+="\\"),I.push(R.trim()),I.map($=>$.replace(/\\\|/gu,"|"))};for(k.push(T(s)),a+=2;a<r.length&&r[a].includes("|")&&r[a].trim();)k.push(T(r[a++]));o.push({kind:"table",rows:k});continue}if(/^\s*>\s?/u.test(s)){const k=[];for(;a<r.length&&/^\s*>\s?/u.test(r[a]);)k.push(r[a++].replace(/^\s*>\s?/u,""));o.push({kind:"quote",text:k.join(`
51
- `)});continue}const w=[s.trim()];for(a++;a<r.length&&r[a].trim()&&!c(a);)w.push(r[a++].trim());o.push({kind:"paragraph",text:w.join(" ")})}return o.some(s=>s.kind==="table")&&Y(e,{code:"COMPLEX_TABLE",message:n("pdf.complexTableExport")}),o}function Dt(t){return t instanceof Uint8Array?Promise.resolve(t):t.arrayBuffer().then(e=>new Uint8Array(e))}function go(t){const e=(t||"document.pdf").trim()||"document.pdf";return/\.pdf$/iu.test(e)?e:`${e}.pdf`}function po(t){return typeof t=="number"?{top:t,right:t,bottom:t,left:t}:{top:t?.top??56.7,right:t?.right??56.7,bottom:t?.bottom??56.7,left:t?.left??56.7}}function ge(t,e){return t.kind==="code"?e.code:t.kind==="bold"?e.bold:t.kind==="italic"?e.italic:(t.kind==="strike",e.normal)}function se(t,e,n,r,o){try{return e.widthOfTextAtSize(t,n),t}catch{return Y(r,{code:"FONT_FALLBACK",message:o("pdf.fontFallback")}),Array.from(t,l=>{try{return e.widthOfTextAtSize(l,n),l}catch{return"?"}}).join("")}}async function Ot(t,e,n,r){const o=n==="image/jpeg"||n==="image/jpg"||/\.jpe?g$/iu.test(r)||e[0]===255&&e[1]===216;try{return o?await t.embedJpg(e):await t.embedPng(e)}catch{return}}async function wo(t,e={}){const n=Bt(e.locale,e.messages);if(typeof t!="string")throw new TypeError(n("validation.markdownString"));ie(e.signal,n);const r=[],o=await H.PDFDocument.create(),l=e.pageSize||[595.28,841.89],c=po(e.margin);if([...l,c.top,c.right,c.bottom,c.left].some(p=>!Number.isFinite(p)||p<=0))throw new RangeError(n("pdf.pageGeometry"));const a={};if(e.fontBytes){o.registerFontkit(wr);const p=e.fontBytes instanceof ArrayBuffer?new Uint8Array(e.fontBytes):e.fontBytes,F=await o.embedFont(p,{subset:e.fontSubset??!0});a.normal=a.bold=a.italic=a.code=F}else a.normal=await o.embedFont(H.StandardFonts.Helvetica),a.bold=await o.embedFont(H.StandardFonts.HelveticaBold),a.italic=await o.embedFont(H.StandardFonts.HelveticaOblique),a.code=await o.embedFont(H.StandardFonts.Courier),/[^\u0000-\u00ff]/u.test(t)&&Y(r,{code:"FONT_FALLBACK",message:n("pdf.fontFallbackCjk")});const s=ho(t,r,n);let i=o.addPage(l),d=l[1]-c.top;const u=l[0]-c.left-c.right,y=p=>p*1.45,w=p=>{d-p<c.bottom&&(i=o.addPage(l),d=l[1]-c.top)},k=(p,F,_=a.normal,b=0,h=H.rgb(0,0,0))=>{const f=se(p,_,F,r,n);w(y(F)),i.drawText(f,{x:c.left+b,y:d-F,size:F,font:_,color:h}),d-=y(F)},T=(p,F,_=0)=>{let b=c.left+_,h=!0;const f=l[0]-c.right,x=(E,O)=>{const A=ge(E,a),P=se(O,A,F,r,n),N=A.widthOfTextAtSize(P,F);if(b+N>f&&b>c.left+_&&(d-=y(F),w(y(F)),b=c.left+_),i.drawText(P,{x:b,y:d-F,size:F,font:A,color:E.kind==="link"?H.rgb(.05,.25,.7):H.rgb(0,0,0)}),E.kind==="link"&&E.href){const C=i.doc.context.obj({Type:"Annot",Subtype:"Link",Rect:[b,d-F*.15,b+N,d+F*1.05],Border:[0,0,0],A:{Type:"Action",S:"URI",URI:H.PDFString.of(E.href)}});i.node.addAnnot(i.doc.context.register(C))}E.kind==="strike"&&i.drawLine({start:{x:b,y:d-F*.45},end:{x:b+N,y:d-F*.45},thickness:.7,color:H.rgb(0,0,0)}),b+=N};for(const E of p){if(ie(e.signal,n),E.kind==="image"){x({kind:"text",text:E.alt||"image"},`[${E.alt||"image"}]`);continue}const O=E.text.split(/(\s+)/u);for(const A of O)A&&x(E,A);h=!1}(!h||p.length)&&(d-=y(F))},L=(p,F,_)=>{const b=[[]];let h=0;const f=()=>{b.push([]),h=0};for(const x of p){const E=x.text.split(/(\s+)/u).filter(Boolean);for(const O of E){if(/^\s+$/u.test(O)){if(b.at(-1)?.length){const C=ge(x,a).widthOfTextAtSize(" ",F);h+C<=_&&(b.at(-1).push({...x,text:" "}),h+=C)}continue}let A=O;for(;A;){const P=ge(x,a),N=se(A,P,F,r,n),C=P.widthOfTextAtSize(N,F);if(h>0&&h+C>_){f();continue}if(C<=_||Array.from(A).length===1){b.at(-1).push({...x,text:A}),h+=C,A="";continue}let W="",K=0;for(const B of Array.from(A)){const q=P.widthOfTextAtSize(se(B,P,F,r,n),F);if(W&&K+q>_)break;W+=B,K+=q}W||(W=Array.from(A)[0]),b.at(-1).push({...x,text:W}),h+=K||P.widthOfTextAtSize(W,F),A=A.slice(W.length),A&&f()}}}return b.filter(x=>x.length)},M=(p,F,_,b)=>{for(const h of p){const f=ge(h,a),x=se(h.text,f,F,r,n),E=f.widthOfTextAtSize(x,F);if(i.drawText(x,{x:_,y:b,size:F,font:f,color:h.kind==="link"?H.rgb(.05,.25,.7):H.rgb(0,0,0)}),h.kind==="link"&&h.href){const O=i.doc.context.obj({Type:"Annot",Subtype:"Link",Rect:[_,b-F*.15,_+E,b+F*1.05],Border:[0,0,0],A:{Type:"Action",S:"URI",URI:H.PDFString.of(h.href)}});i.node.addAnnot(i.doc.context.register(O))}_+=E}},I=p=>p?p.startsWith("comment")||p.startsWith("quote")?H.rgb(.416,.451,.49):p.startsWith("keyword")||p.startsWith("selector-tag")||p.startsWith("subst")?H.rgb(.843,.227,.286):p.startsWith("string")||p.startsWith("doctag")||p.startsWith("regexp")?H.rgb(.012,.184,.384):p.startsWith("title")||p.startsWith("section")||p.startsWith("selector-id")?H.rgb(.435,.259,.757):p.startsWith("number")||p.startsWith("literal")||p.startsWith("variable")||p.startsWith("symbol")||p.startsWith("bullet")?H.rgb(0,.361,.773):p.startsWith("type")||p.startsWith("class")||p.startsWith("built_in")?H.rgb(.89,.384,.035):p.startsWith("attr")||p.startsWith("attribute")||p.startsWith("name")?H.rgb(.133,.533,.227):p.startsWith("meta")?H.rgb(.451,.361,.059):H.rgb(.15,.17,.2):H.rgb(.15,.17,.2),R=(p,F,_,b)=>{if(!p.length)return[[{text:" "}]];const h=[[]];let f=0;const x=(E,O)=>{const A=h.at(-1),P=A.at(-1);P&&P.scope===O?P.text+=E:A.push({text:E,scope:O})};for(const E of p)for(const O of Array.from(E.text)){const A=F.widthOfTextAtSize(se(O,F,_,r,n),_);f>0&&f+A>b&&(h.push([]),f=0),x(O,E.scope),f+=A}return h},D=p=>{const h=H.rgb(.965,.968,.972),f=H.rgb(.78,.8,.84),x=A=>{w(12),i.drawRectangle({x:c.left,y:d-12,width:u,height:12,color:h}),i.drawRectangle({x:c.left,y:d-12,width:2,height:12,color:f});let P=c.left+8;for(const N of A){const C=se(N.text,a.code,8.5,r,n);i.drawText(C,{x:P,y:d-9.5,size:8.5,font:a.code,color:I(N.scope)}),P+=a.code.widthOfTextAtSize(C,8.5)}d-=12};w(12),i.drawRectangle({x:c.left,y:d-12,width:u,height:12,color:h}),i.drawRectangle({x:c.left,y:d-12,width:2,height:12,color:f}),p.language&&i.drawText(se(p.language,a.code,7,r,n),{x:c.left+8,y:d-8.5,size:7,font:a.code,color:H.rgb(.38,.4,.45)}),d-=12;const E=u-16,O=Wt(p.text||"",p.language);for(const A of O.lines)for(const P of R(A,a.code,8.5,E))x(P);w(6),i.drawRectangle({x:c.left,y:d-6,width:u,height:6,color:h}),i.drawRectangle({x:c.left,y:d-6,width:2,height:6,color:f}),d-=12};for(const p of s){if(ie(e.signal,n),p.kind==="rule"){w(12),i.drawLine({start:{x:c.left,y:d-6},end:{x:l[0]-c.right,y:d-6},thickness:1,color:H.rgb(.65,.65,.65)}),d-=18;continue}if(p.kind==="heading"){const b=[0,24,20,16,14,12,11][p.level||1];T(he(p.text||"",r,n),b),d-=5;continue}if(p.kind==="code"){D(p);continue}if(p.kind==="list"){for(let b=0;b<(p.items||[]).length;b++){const h=p.ordered?`${b+1}. `:"• ";T([{kind:"text",text:h},...he(p.items[b],r,n)],11,12)}d-=4;continue}if(p.kind==="quote"){T(he(p.text||"",r,n),11,14),d-=4;continue}if(p.kind==="table"){const b=p.rows||[],h=Math.max(0,...b.map(E=>E.length)),f=9,x=5;if(b.length&&h){const E=Array.from({length:h},(P,N)=>{const C=Math.max(...b.map(W=>{const K=W[N]||"";return he(K,r,n).reduce((B,q)=>B+ge(q,a).widthOfTextAtSize(se(q.text,ge(q,a),f,r,n),f),0)}),24);return Math.min(260,C+x*2)}),O=E.reduce((P,N)=>P+N,0),A=O>u?E.map(P=>P*u/O):E.map(P=>P+(u-O)/h);for(let P=0;P<b.length;P++){const N=b[P],C=Array.from({length:h},(B,q)=>L(he(N[q]||"",r,n),f,Math.max(20,A[q]-x*2))),W=Math.max(1,...C.map(B=>B.length))*12+x*2;w(W);let K=c.left;for(let B=0;B<h;B++){const q=A[B],ue=P===0?H.rgb(.95,.95,.94):H.rgb(1,1,1);i.drawRectangle({x:K,y:d-W,width:q,height:W,color:ue,borderColor:H.rgb(.78,.78,.76),borderWidth:.5});const re=C[B];for(let le=0;le<re.length;le++)M(re[le],f,K+x,d-x-f-le*12);K+=q}d-=W}}d-=4;continue}if(p.kind==="image"){if(!e.resolveResource){Y(r,{code:"RESOURCE_UNRESOLVED",message:n("pdf.imageUnresolved"),path:p.path}),k(`[${p.alt||"image"}]`,11);continue}try{const b=await Ct(e.resolveResource({path:p.path||"",alt:p.alt}),e.signal,n);ie(e.signal,n);const h=await Dt(b.bytes),f=await Ot(o,h,"",p.path||"");if(!f)throw new Error("unsupported image");const x=f.scaleToFit(u,240);w(x.height+10),i.drawImage(f,{x:c.left,y:d-x.height,width:x.width,height:x.height}),d-=x.height+10}catch(b){if(Y(r,{code:"RESOURCE_RESOLUTION_FAILED",message:n("pdf.imageFailed"),path:p.path}),k(`[${p.alt||"image"}]`,11),b instanceof G)throw b}continue}const F=he(p.text||"",r,n),_=[];for(const b of F)if(b.kind==="image"){if(!e.resolveResource){Y(r,{code:"RESOURCE_UNRESOLVED",message:n("pdf.inlineImageUnresolved"),path:b.path});continue}try{const h=await Ct(e.resolveResource({path:b.path||"",alt:b.alt}),e.signal,n);ie(e.signal,n);const f=await Ot(o,await Dt(h.bytes),"",b.path||"");f?_.push(f):Y(r,{code:"RESOURCE_RESOLUTION_FAILED",message:n("pdf.inlineImageUnsupported"),path:b.path})}catch(h){if(h instanceof G)throw h;Y(r,{code:"RESOURCE_RESOLUTION_FAILED",message:n("pdf.inlineImageFailed"),path:b.path})}}T(F,11);for(const b of _){const h=b.scaleToFit(Math.min(u,180),100);w(h.height+8),i.drawImage(b,{x:c.left,y:d-h.height,width:h.width,height:h.height}),d-=h.height+8}d-=4}o.setTitle("Markdown PDF");const U=await o.save(),$=U.buffer.slice(U.byteOffset,U.byteOffset+U.byteLength);return{blob:new Blob([$],{type:nt}),fileName:go(e.fileName),mimeType:nt,warnings:r}}function xo(t){Oe(t.doc);const e=Be(t.doc),n=!t.awareness,r=!t.undoManager,o=t.awareness||new Nt.Awareness(t.doc),l=t.undoManager||new X.UndoManager(e);return{doc:t.doc,text:e,awareness:o,undoManager:l,state:t.state,saveState:t.saveState,ready:t.ready,collaborators:t.collaborators||[],error:t.error,epochId:t.epochId,dispose:()=>{r&&l.destroy(),n&&o.destroy()}}}function bo(t,e){return{...t,...e}}function vo(t,e){const n=(r,o,l,c)=>{const a=Array.from(c.changedParentTypes.keys()).some(s=>Object.is(s,t.text));!c.local||o===Te.bootstrap||o===Te.remote||!a||e({update:r,origin:o,transaction:c})};return t.doc.on("update",n),()=>t.doc.off("update",n)}function yo(t,e){X.applyUpdate(t,e,Te.remote)}const ko=Object.freeze({protocolVersion:Gt,codec:_e,schemaVersion:Ue,textRoot:"markdown",find:{literal:!0,caseSensitive:!0,regex:!1},permanentTextAnchors:!0,remoteCarets:!0,commentDecorations:!0,previewTextAnchors:!0,previewCommentDecorations:!0,hostSelectionActions:!0,anchorKind:"markdown-text-range",anchorBoundary:"exclude-both"});exports.COLLABORATION_PROTOCOL_VERSION=Gt;exports.CodeBlock=$t;exports.CollaborativeMarkdownEditor=Xr;exports.DEFAULT_MARKDOWN=qr;exports.DEFAULT_MARKDOWN_IMPORT_MAX_BYTES=rn;exports.DEFAULT_PDF_IMPORT_MAX_BYTES=an;exports.DEFAULT_PDF_IMPORT_MAX_IMAGE_PIXELS=cn;exports.DEFAULT_PDF_IMPORT_MAX_PAGES=sn;exports.DEFAULT_PDF_IMPORT_TIMEOUT_MS=ln;exports.DefaultEditorFooter=nn;exports.DefaultEditorHeader=en;exports.DefaultEditorLoading=tn;exports.MARKDOWN_CODEC=_e;exports.MARKDOWN_FILE_MIME=tt;exports.MARKDOWN_HOST_CAPABILITIES=ko;exports.MARKDOWN_SCHEMA_VERSION=Ue;exports.MarkdownPreview=Vt;exports.MermaidDiagram=qt;exports.PDF_FILE_MIME=nt;exports.PdfFileError=G;exports.TRANSACTION_ORIGINS=Te;exports.Toolbar=zt;exports.applyRemoteMarkdownUpdate=yo;exports.assertSupportedMarkdownDocument=Oe;exports.createHostMarkdownSession=xo;exports.createMarkdownFile=lt;exports.createMarkdownTextAnchor=it;exports.createMarkdownTextSelection=Xt;exports.downloadMarkdown=$r;exports.editorLanguageTag=jt;exports.encodeMarkdownCheckpoint=Br;exports.exportMarkdownFile=no;exports.exportPdfFile=wo;exports.getMarkdownText=Be;exports.imageToDataUrl=ct;exports.importMarkdownFile=to;exports.importPdfFile=mo;exports.initializeMarkdownDocument=Jt;exports.observeLocalMarkdownUpdates=vo;exports.readMarkdownMetadata=st;exports.resolveEditorLocale=rt;exports.resolveMarkdownTextAnchor=we;exports.resolveMarkdownTextSelection=Ir;exports.translate=z;exports.updateHostMarkdownSession=bo;exports.uploadImageToEndpoint=Wr;exports.useCollaboration=Qt;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./chunks/index-DQLDZhUI.cjs");exports.COLLABORATION_PROTOCOL_VERSION=e.COLLABORATION_PROTOCOL_VERSION;exports.CodeBlock=e.CodeBlock;exports.CollaborativeMarkdownEditor=e.CollaborativeMarkdownEditor;exports.DEFAULT_MARKDOWN=e.DEFAULT_MARKDOWN;exports.DEFAULT_MARKDOWN_IMPORT_MAX_BYTES=e.DEFAULT_MARKDOWN_IMPORT_MAX_BYTES;exports.DEFAULT_PDF_IMPORT_MAX_BYTES=e.DEFAULT_PDF_IMPORT_MAX_BYTES;exports.DEFAULT_PDF_IMPORT_MAX_IMAGE_PIXELS=e.DEFAULT_PDF_IMPORT_MAX_IMAGE_PIXELS;exports.DEFAULT_PDF_IMPORT_MAX_PAGES=e.DEFAULT_PDF_IMPORT_MAX_PAGES;exports.DEFAULT_PDF_IMPORT_TIMEOUT_MS=e.DEFAULT_PDF_IMPORT_TIMEOUT_MS;exports.DefaultEditorFooter=e.DefaultEditorFooter;exports.DefaultEditorHeader=e.DefaultEditorHeader;exports.DefaultEditorLoading=e.DefaultEditorLoading;exports.MARKDOWN_CODEC=e.MARKDOWN_CODEC;exports.MARKDOWN_FILE_MIME=e.MARKDOWN_FILE_MIME;exports.MARKDOWN_HOST_CAPABILITIES=e.MARKDOWN_HOST_CAPABILITIES;exports.MARKDOWN_SCHEMA_VERSION=e.MARKDOWN_SCHEMA_VERSION;exports.MarkdownPreview=e.MarkdownPreview;exports.MermaidDiagram=e.MermaidDiagram;exports.PDF_FILE_MIME=e.PDF_FILE_MIME;exports.PdfFileError=e.PdfFileError;exports.TRANSACTION_ORIGINS=e.TRANSACTION_ORIGINS;exports.Toolbar=e.Toolbar;exports.applyRemoteMarkdownUpdate=e.applyRemoteMarkdownUpdate;exports.assertSupportedMarkdownDocument=e.assertSupportedMarkdownDocument;exports.createHostMarkdownSession=e.createHostMarkdownSession;exports.createMarkdownFile=e.createMarkdownFile;exports.createMarkdownTextAnchor=e.createMarkdownTextAnchor;exports.createMarkdownTextSelection=e.createMarkdownTextSelection;exports.downloadMarkdown=e.downloadMarkdown;exports.editorLanguageTag=e.editorLanguageTag;exports.encodeMarkdownCheckpoint=e.encodeMarkdownCheckpoint;exports.exportMarkdownFile=e.exportMarkdownFile;exports.exportPdfFile=e.exportPdfFile;exports.getMarkdownText=e.getMarkdownText;exports.imageToDataUrl=e.imageToDataUrl;exports.importMarkdownFile=e.importMarkdownFile;exports.importPdfFile=e.importPdfFile;exports.initializeMarkdownDocument=e.initializeMarkdownDocument;exports.observeLocalMarkdownUpdates=e.observeLocalMarkdownUpdates;exports.readMarkdownMetadata=e.readMarkdownMetadata;exports.resolveEditorLocale=e.resolveEditorLocale;exports.resolveMarkdownTextAnchor=e.resolveMarkdownTextAnchor;exports.resolveMarkdownTextSelection=e.resolveMarkdownTextSelection;exports.translate=e.translate;exports.updateHostMarkdownSession=e.updateHostMarkdownSession;exports.uploadImageToEndpoint=e.uploadImageToEndpoint;exports.useCollaboration=e.useCollaboration;