finch-markdown-editor 0.2.6 → 0.2.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/codemirror.js +31 -31
- package/dist/panel.js +15 -15
- package/package.json +1 -1
package/dist/panel.js
CHANGED
|
@@ -7,40 +7,40 @@
|
|
|
7
7
|
|
|
8
8
|
{text}
|
|
9
9
|
|
|
10
|
-
Give a drop-in replacement snippet first; once I confirm, write it back to the source file ({path}) as a targeted local replacement, not a full resend of the document.`,"annotate.reminder":"Only propose the rewrite \u2014 don't write to the source file before I confirm. Reply in natural language (e.g. \u201CI'll put it into the file once you confirm\u201D); never name the tool or its actions. [MANDATORY, not optional] Whenever this turn proposes a rewrite and is waiting on my confirmation, calling Session action=suggest with 1\u20133 one-tap confirmations (e.g. \u201CUse this one\u201D, \u201CUse the shorter version\u201D, \u201CTry another tone\u201D) is part of completing that same turn \u2014 writing the proposal text is only half the job. Do not treat the turn as done, and do not skip the call, just because the proposal text itself was already sent.","newdoc.needChat":"Use \u201CNew Document\u201D from the Finch chat instead.","newdoc.label":"New Markdown Document","newdoc.promptText":"I want to create a new Markdown document. First work out the title, content, and a not-yet-existing absolute save path from my request \u2014 ask me first if anything is missing. Once confirmed, write the full body to that path and open the new document in the editor.","newdoc.reminder":"Only create a new file; never overwrite an existing one. Reply in natural language and never name the tool or its actions. [MANDATORY, not optional] Whenever this turn ends still waiting on me to confirm a title, an angle, or a save location, it must call Session action=suggest with 1\u20133 one-tap options before the turn ends \u2014 asking the question in plain text is not enough on its own; skipping the call leaves the question unfinished.","newdoc.added":"Added the new-document prompt to the composer.","aiStyle.label":"Design a layout based on {file}","aiStyle.note":"One-click AI layout","aiStyle.baseNoteCustom":"The current base style is kami (your custom CSS layers on top of it)","aiStyle.baseNoteOther":"The current base style is {style}","aiStyle.pathMissing":"(No local file linked)","aiStyle.promptText":'Please design a custom layout CSS for this WeChat article. {baseNote}, and your CSS will layer on top of the base style. Requirements: write plain CSS rules only, with selectors scoped to tags/structure under #bm-md (e.g. #bm-md h1, #bm-md p, #bm-md blockquote, #bm-md pre code, #bm-md a, #bm-md strong, #bm-md table); don\u2019t use classes (bm.md\u2019s output has no classes, only inline styles), and use !important where needed to override the base style. You can draw on bm.md\u2019s built-in style language: kami (warm paper feel), bauhaus (geometric color-blocking), blueprint (technical grid), botanical (fresh green), newsprint (editorial serif), retro (nostalgic), sketch (hand-drawn), terminal (monospace dark). Article path: {path}. Once it\u2019s ready, call set_style directly (pass path="{path}", css, and a short label, no slot \u2014 passing path lets it find the right preview panel for this document even if I\u2019ve switched away) \u2014 don\u2019t ask me which slot to use first; the panel will pop up a lightweight \u201Csave as custom style\u201D button so I can decide after seeing the result.',"aiStyle.reminder":"Don\u2019t ask which slot to use before applying \u2014 just design it and call set_style (without slot) to apply it to the preview; whether to save it is for me to decide from the panel. Reply in natural language and never name the tool or its actions.","aiStyle.requested":"Asked AI to design a custom layout.","aiStyle.applied":"AI designed a layout and applied it to the preview.","aiStyle.saveToSlot":"Save as style {n}","aiStyle.appViewDesigning":"AI is designing a layout\u2026","aiStyle.appViewDone":"Layout design finished.","aiStyle.appViewFailed":"Layout design did not finish.","status.saved":"Saved.","status.savedWithNewChanges":"Saved \u2014 but the editor already has newer changes.","status.saveFailed":"Save failed: {err}","status.saving":"Saving\u2026","status.noSourceFile":"Not linked to a local file: click \u201COpen\u201D in the toolbar again to link it and enable saving.","status.pickerTimeout":'The file picker took too long to respond and switched to the in-browser picker \u2014 please click "Open" again.',"status.externalUpdateSkipped":"Detected an external file update; not loaded yet to avoid overwriting unsaved changes.","status.draftRestored":'Restored your last unsaved edits (differs from the file on disk). To discard, click "Open" and pick this file again, then choose "Discard".',"status.draftConflict":"A local unsaved draft exists, but the file was changed and saved elsewhere; loaded the latest file content \u2014 the draft is kept, not discarded.","status.sourceMissing":"The original file was moved or deleted; your content is still here \u2014 saving will recreate the file at its original path.","status.externalUpdateApplied":"Detected a file update and refreshed.","status.openingPicker":"Opening the file picker\u2026","status.opening":"Opening\u2026","status.opened":"Opened {file}.","status.contentUpdated":"Content updated.","status.contentUpdatedLine":"Updated line {line}.","status.contentUpdatedLines":"Updated lines {from}\u2013{to}.","status.contentUpdatedSpots":"Updated {count} spots, {lines} lines in total.","status.pasteImageTimeout":"Paste image timed out","status.pasteImageFailed":"Paste image failed: {msg}","status.clipboardPrepareTimeout":"Preparing WeChat images timed out","status.pleaseOpenArticle":"Open an article first.","status.copiedRich":"Rich HTML copied \u2014 paste it directly into the WeChat editor.","status.copiedPlainOnly":"Only plain text was copied; formatting didn't come through \u2014 please try again.","status.copyFailed":"Copy failed \u2014 please try again.","status.richCopyFailed":"Rich-text copy failed: {err}","status.clipboardUnsupported":"Copying images isn\u2019t supported here \u2014 use \u201CExport Image\u201D instead.","status.generatingImage":"Generating image\u2026","status.previewNotReady":"Preview isn't ready yet","status.imageCopied":"Image copied to the clipboard.","status.copyImageFailed":"Copy image failed: {err} (try \u201CExport Image\u201D instead)","status.exportImageFailedGeneric":"Export image failed: preview isn't ready yet.","status.exportImageFailed":"Export image failed: {err}","status.generatingPdf":"Generating PDF\u2026","status.exportPdfFailedGeneric":"Export PDF failed: preview isn't ready yet.","status.exportPdfFailed":"Export PDF failed: {err}","status.exported":"Exported: {path}","status.annotateOn":"Annotate is on \u2014 select text to ask AI to revise it.","status.annotateOff":"Annotate is off.","status.comfortWrite":"Comfortable mode is on \u2014 roomier line spacing.","status.comfortRead":"Compact mode is on.","status.focusOn":"Focus mode is on \u2014 inactive lines are dimmed.","status.focusOff":"Focus mode is off.","status.saveFailedNoReturn":"Save failed \u2014 staying on this document.","status.rendererAboutPrefix":"Renderer: local bmmd CLI (","status.rendererAboutSuffix":", LGPL-3.0).","status.appliedStyleSlot":"Applied \u201C{label}\u201D.","status.needCustomStyleFirst":"Apply a custom/AI-designed style first before saving it to a slot.","status.savedToSlot":"Saved to slot {slot}: {label}","status.serializeFailed":"Failed to serialize the preview content: {err}","status.imageConversionFailed":"The preview couldn't be converted to an image (it may contain external images that can't be read cross-origin)","status.imageGenFailed":"Failed to generate image data","status.clipboardPrepareFailedDefault":"Failed to prepare WeChat images","status.pasteImageFailedDefault":"Paste image failed","status.savedAppliedToSlot":"{labelPrefix}Saved and applied to custom style {slot}."}};function n(e,t){var a=it?st.zh:st.en,r=Object.prototype.hasOwnProperty.call(a,e)?a[e]:Object.prototype.hasOwnProperty.call(st.en,e)?st.en[e]:e;if(t)for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&(r=r.split("{"+o+"}").join(String(t[o])));return r}function Dt(e){var t=e||document;document.documentElement.lang=it?"zh-CN":"en",document.title=n("meta.title"),Array.prototype.forEach.call(t.querySelectorAll("[data-i18n]"),function(a){a.textContent=n(a.getAttribute("data-i18n"))}),Array.prototype.forEach.call(t.querySelectorAll("[data-i18n-title]"),function(a){a.title=n(a.getAttribute("data-i18n-title"))}),Array.prototype.forEach.call(t.querySelectorAll("[data-i18n-tooltip]"),function(a){var r=n(a.getAttribute("data-i18n-tooltip"));a.setAttribute("data-tooltip",r),a.setAttribute("aria-label",r)}),Array.prototype.forEach.call(t.querySelectorAll("[data-i18n-aria]"),function(a){a.setAttribute("aria-label",n(a.getAttribute("data-i18n-aria")))})}var Ft=document.getElementById("empty"),ha=document.getElementById("emptyNew"),ya=document.getElementById("emptyOpen"),Tt=document.getElementById("homeRecent"),le=document.getElementById("homeGrid"),lt=document.getElementById("homeHint"),Pt=[],ba=document.getElementById("homeTagline"),Mr=document.getElementById("editPane"),Ot=document.getElementById("previewPane"),ue=document.getElementById("previewResizer"),Se=document.getElementById("editor"),w=document.getElementById("article"),M=document.getElementById("status"),I=document.getElementById("popup"),_=document.getElementById("popupInput"),wa=document.getElementById("popupSend"),Sa=document.getElementById("popupShortcut"),Pe=document.getElementById("actions"),Ir=document.getElementById("actCopyWx"),Lr=document.getElementById("actCopyImg"),Ar=document.getElementById("actSaveImg"),Cr=document.getElementById("actSavePdf"),ke=document.getElementById("actAiStyle"),ka=document.getElementById("actToggle"),ce=document.getElementById("confirmOverlay"),xa=document.getElementById("confirmMessage"),Rt=document.getElementById("confirmCancel"),Bt=document.getElementById("confirmDiscard"),Oe=document.getElementById("confirmSave"),Ea=document.getElementById("appToolbar"),Ma=document.getElementById("appHome"),Ia=document.getElementById("appLibrary"),ut=document.getElementById("appOpen"),re=document.getElementById("appSave"),Re=document.getElementById("appPreview"),ct=document.getElementById("appStyle"),dt=document.getElementById("appStyleMenu"),Be=document.getElementById("appFocus"),Nt=document.getElementById("appFont"),pt=document.getElementById("appFontMenu"),Dr=document.getElementById("appMore"),ft=document.getElementById("appMoreMenu"),qt=document.getElementById("libraryDrawer"),mt=document.getElementById("libraryBackdrop"),La=document.getElementById("libraryClose"),vt=document.getElementById("libraryReorder"),Aa=document.getElementById("libraryReorderFooter"),Ca=document.getElementById("libraryReorderDone"),C=document.getElementById("libraryGroups"),Da="md-editor-library-groups-v1",de=[],xe={},pe=null,Ne=null,ne=!1,qe=[],j=null,Ht=!1,v=!1,Fa=!1,Ta=!1,N=null,fe=null,V=!0,Fr=!1,gt=0,He=!1,te=!0,k="edit",L="kami",O="",Ee="",q=[null,null,null],Me={songti:"Songti SC, STSong, SimSun, Noto Serif CJK SC, serif",rounded:"PingFang SC, Microsoft YaHei, Noto Sans CJK SC, sans-serif"},H=14,K="rounded",R=!1,B=!1;try{var ht=Number(localStorage.getItem("md-editor-font-size"));(ht===14||ht===16||ht===18)&&(H=ht);var Wt=localStorage.getItem("md-editor-font-family");Me[Wt]?K=Wt:Wt&&localStorage.removeItem("md-editor-font-family"),R=localStorage.getItem("md-editor-comfort-writing")==="1",B=localStorage.getItem("md-editor-focus-mode")==="1";var We=JSON.parse(localStorage.getItem(Da)||"{}");Array.isArray(We.order)&&(de=We.order.filter(function(e){return typeof e=="string"})),We.collapsed&&typeof We.collapsed=="object"&&(xe=We.collapsed)}catch{}te=!B;var g="",ze="",W="",f="",T=null,z="",Ue=!1,Pa=0,_e=!1,Oa=0,zt={},Ie={},Tr=0,me={},Pr=0,ve={},je=0,J=null,yt=0,Le=0,Ut=!1,h={text:"",mode:"replace"},E=0;function l(e,t){E&&(clearTimeout(E),E=0),M.textContent=e||"",M.className="status"+(t?" error":""),e&&(E=setTimeout(function(){E=0,M.textContent="",M.className="status"},5e3))}function ge(e,t,a,r){if(E&&(clearTimeout(E),E=0),M.replaceChildren(document.createTextNode(e||"")),M.className="status"+(t?" error":""),a){var o=document.createElement("button");o.type="button",o.className="status-inline-btn",o.textContent=n("appview.openSession"),o.addEventListener("click",function(){i&&i.navigation&&i.navigation.openSession&&i.navigation.openSession(a)}),M.appendChild(o)}r&&(E=setTimeout(function(){E=0,M.replaceChildren(),M.className="status"},r))}function Or(){E&&(clearTimeout(E),E=0),M.replaceChildren(document.createTextNode(n("status.rendererAboutPrefix")));var e=document.createElement("a");e.href="https://bm.md/",e.textContent="bm.md",e.title="https://bm.md/",e.addEventListener("click",function(t){t.preventDefault(),i&&i.postMessage&&i.postMessage({type:"openLink",url:"https://bm.md/"})}),M.append(e,document.createTextNode(n("status.rendererAboutSuffix"))),M.className="status",E=setTimeout(function(){E=0,M.textContent="",M.className="status"},5e3)}function A(){return!!g||!!f}ha&&ha.addEventListener("click",async function(){if(!i||!i.composer){l(n("newdoc.needChat"),!0);return}try{await i.composer.addContexts([{type:"annotation",label:n("newdoc.label"),promptText:n("newdoc.promptText"),reminder:n("newdoc.reminder")}]),l(n("newdoc.added"))}catch(e){l(String(e),!0)}}),ya&&ya.addEventListener("click",function(){ia()});var Ve="",_t="",jt="",bt=!1,Ra=!1,Ge="",he="";function y(e){return String(e).replace(/[&<>"]/g,function(t){return t==="&"?"&":t==="<"?"<":t===">"?">":"""})}function Ba(){ba&&(ba.textContent=Ge?n("home.tagline.withAssistant",{name:Ge}):n("home.tagline.default"))}function wt(){_&&(_.placeholder=h.mode==="continue"?n("popup.placeholderContinue",{name:Ge||"Finch"}):n("popup.placeholder",{name:Ge||"Finch"}))}function Rr(e){return e?he&&e===he?"~":he&&(e.indexOf(he+"/")===0||e.indexOf(he+"\\")===0)?"~"+e.slice(he.length):e:""}function Br(e){var t=46;if(!e||e.length<=t)return e;var a=e.indexOf("/")===-1&&e.indexOf("\\")!==-1?"\\":"/",r=e.slice(-(t-1)),o=r.indexOf(a);return o>0&&o<10&&(r=r.slice(o)),"\u2026"+r}function Nr(){kt(Pt)}function Na(e){var t=new Date(e);if(!e||isNaN(t.getTime()))return"";var a=new Date,r=function(c){return c<10?"0"+c:String(c)},o=r(t.getHours())+":"+r(t.getMinutes()),s=t.toDateString()===a.toDateString();if(s)return n("home.today",{clock:o});var u=new Date(a.getTime()-864e5);return t.toDateString()===u.toDateString()?n("home.yesterday",{clock:o}):t.getFullYear()===a.getFullYear()?r(t.getMonth()+1)+"-"+r(t.getDate()):t.getFullYear()+"-"+r(t.getMonth()+1)+"-"+r(t.getDate())}function St(){!i||!i.postMessage||!bt||(Ra=!0,i.postMessage({type:"requestRecentDocuments",cwd:Ve,sessionId:_t,spaceId:jt}))}function qr(e){e=e||{};var t=e.relativePath||e.fileName||"";return'<button class="doc-card" type="button" data-path="'+y(e.path||"")+'" title="'+y(e.path||"")+'"><span class="doc-reveal" data-reveal-path="'+y(e.path||"")+'" role="button" tabindex="0" title="'+y(n("home.revealInFileManager"))+'" aria-label="'+y(n("home.revealInFileManager"))+'"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m6 14 1.45-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.55 6a2 2 0 0 1-1.94 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"/></svg></span><div class="doc-preview">'+y(e.preview||n("home.emptyDoc"))+'</div><div class="doc-foot"><div class="doc-title">'+y(e.title||e.fileName||n("home.untitled"))+'</div><div class="doc-sub"><span class="doc-path" data-full-path="'+y(t)+'">'+y(t)+'</span><span class="doc-time">'+y(Na(e.modifiedAt))+"</span></div></div></button>"}function kt(e){if(!(!le||!Tt||!lt)){var t=Array.isArray(e)?e:[];if(Pt=t,t.length===0){Tt.hidden=!0,lt.hidden=!1,lt.textContent=n(Ve?"home.hintScoped":"home.hintDefault");return}var a=qa(t);le.innerHTML=a.map(function(r){var o=r.documents.map(qr).join(""),s=r.scopePath?'<button type="button" class="home-group-cwd" data-cwd-path="'+y(r.scopePath)+'" title="'+y(n("home.cwdTitle",{path:r.scopePath}))+'">'+y(Br(Rr(r.scopePath)))+"</button>":"",u='<div class="home-group-title"><span class="home-group-label">'+y(r.label)+'<span class="home-group-count">'+r.documents.length+"</span></span>"+s+"</div>";return'<div class="home-group">'+u+'<div class="home-grid">'+o+"</div></div>"}).join(""),Tt.hidden=!1,lt.hidden=!0,requestAnimationFrame(function(){Hr(le)})}}function Hr(e){for(var t="\u2026",a=e.querySelectorAll("[data-full-path]"),r=0;r<a.length;r++){var o=a[r],s=o.getAttribute("data-full-path")||"";if(o.textContent=s,!(!s||o.scrollWidth<=o.clientWidth+1)){for(var u=0,c=s.length,d=0;u<=c;){var m=u+c>>1;o.textContent=m>0?t+s.slice(s.length-m):t,o.scrollWidth<=o.clientWidth+1?(d=m,u=m+1):c=m-1}o.textContent=d>0?t+s.slice(s.length-d):t}}}function Vt(){var e={order:de,collapsed:xe};try{localStorage.setItem(Da,JSON.stringify(e))}catch{}i&&i.postMessage&&i.postMessage({type:"saveLibraryGroups",libraryGroups:e})}function qa(e){var t={};return(Array.isArray(e)?e:[]).forEach(function(a){var r=a.scopeKind||"external",o=r==="workspace"?n("appview.libraryWorkspace"):r==="external"?n("appview.libraryOther"):a.scopeLabel||a.spaceName||n("appview.libraryOther"),s=r==="space"?"space:"+(a.spaceId||o):r==="workspace"?"workspace":"external";t[s]||(t[s]={id:s,kind:r,label:o,scopePath:"",documents:[]}),r!=="external"&&!t[s].scopePath&&a.scopePath&&(t[s].scopePath=a.scopePath),t[s].documents.push(a)}),Object.keys(t).map(function(a){return t[a]}).sort(function(a,r){if(a.kind==="external"||r.kind==="external")return a.kind===r.kind?0:a.kind==="external"?1:-1;var o=de.indexOf(a.id),s=de.indexOf(r.id);if(o>=0||s>=0)return(o<0?9999:o)-(s<0?9999:s);var u={space:0,workspace:1},c=u[a.kind]-u[r.kind];return c||a.label.localeCompare(r.label)})}function Gt(e){if(C){qe=Array.isArray(e)?e:[];var t=qa(qe);if(ne){Wr(t);return}C.innerHTML=t.map(function(a){var r=a.documents.map(function(u){var c=u.relativePath||u.fileName||"";return'<button class="library-row" type="button" data-path="'+y(u.path||"")+'"><span class="library-row-main"><strong>'+y(u.title||u.fileName||n("home.untitled"))+'</strong><span class="library-row-meta"><span class="library-row-path" title="'+y(c)+'">'+y(c)+"</span><time>"+y(Na(u.modifiedAt))+"</time></span></span></button>"}).join(""),o=a.kind!=="external",s=!xe[a.id];return'<details class="library-group" data-library-group-id="'+y(a.id)+'"'+(o?' data-draggable="true"':"")+(s?" open":"")+'><summary><span class="library-group-title">'+y(a.label)+'</span><span class="library-group-count">'+a.documents.length+'</span></summary><div class="library-items">'+r+"</div></details>"}).join("")||'<p class="home-hint">'+y(n("home.hintDefault"))+"</p>"}}function Wr(e){C.innerHTML=e.map(function(t){var a=t.kind!=="external";return'<div class="library-group library-group-reorder" data-library-group-id="'+y(t.id)+'"'+(a?' data-draggable="true"':"")+'><span class="library-reorder-handle" aria-hidden="true">'+(a?"\u22EE\u22EE":"")+'</span><span class="library-group-title">'+y(t.label)+'</span><span class="library-group-count">'+t.documents.length+"</span></div>"}).join("")||'<p class="home-hint">'+y(n("home.hintDefault"))+"</p>"}function Yt(e){ne=!!e,vt&&vt.classList.toggle("active",ne),Aa&&(Aa.hidden=!ne),Gt(qe)}function xt(e){!qt||!mt||(qt.classList.toggle("open",!!e),qt.setAttribute("aria-hidden",e?"false":"true"),mt.hidden=!e,e?St():ne&&Yt(!1))}function zr(){if(!(!pe||!C)){pe.classList.remove("dragging"),Array.prototype.forEach.call(C.querySelectorAll(".library-group.drag-over"),function(t){t.classList.remove("drag-over")}),de=Array.prototype.map.call(C.querySelectorAll('.library-group[data-draggable="true"]'),function(t){return t.getAttribute("data-library-group-id")}).filter(Boolean),kt(Pt);var e=Ne||{};Array.prototype.forEach.call(C.querySelectorAll(".library-group"),function(t){var a=t.getAttribute("data-library-group-id");a in e&&(t.open=!!e[a])}),pe=null,setTimeout(function(){Ne=null,Vt()},0)}}function Ur(){j&&j.ghost&&j.ghost.parentNode&&j.ghost.parentNode.removeChild(j.ghost)}function Ha(e,t){var a=j;!a||!a.ghost||(a.ghost.style.left=e-a.offsetX+"px",a.ghost.style.top=t-a.offsetY+"px")}function _r(e){var t=j;if(!(!t||t.active)){t.active=!0,pe=e,Ne={},ne||Array.prototype.forEach.call(C.querySelectorAll(".library-group"),function(o){var s=o.getAttribute("data-library-group-id");s&&(Ne[s]=!!o.open),o.open=!1}),e.classList.add("dragging");var a=e.getBoundingClientRect(),r=e.cloneNode(!0);r.classList.add("library-drag-ghost"),r.classList.remove("dragging"),r.style.width=a.width+"px",t.ghost=r,t.offsetX=t.startX-a.left,t.offsetY=t.startY-a.top,document.body.appendChild(r),Ha(t.startX,t.startY)}}function jr(e,t){if(pe){var a=document.elementFromPoint(e,t),r=a&&a.closest?a.closest('.library-group[data-draggable="true"]'):null;if(Array.prototype.forEach.call(C.querySelectorAll(".library-group.drag-over"),function(s){s.classList.remove("drag-over")}),!(!r||r===pe)){r.classList.add("drag-over");var o=t>r.getBoundingClientRect().top+r.offsetHeight/2;C.insertBefore(pe,o?r.nextSibling:r)}}}function Wa(){var e=j;e&&(e.active&&(Ur(),zr(),Ht=!0,setTimeout(function(){Ht=!1},0)),j=null)}Ia&&Ia.addEventListener("click",function(){xt(!0)}),La&&La.addEventListener("click",function(){xt(!1)}),mt&&mt.addEventListener("click",function(){xt(!1)}),vt&&vt.addEventListener("click",function(){Yt(!ne)}),Ca&&Ca.addEventListener("click",function(){Yt(!1)}),C&&C.addEventListener("click",function(e){var t=e.target&&e.target.closest?e.target.closest(".library-row"):null,a=t&&t.getAttribute("data-path");!a||!i||!i.postMessage||(xt(!1),Ye=!0,l(n("status.opening")),Xt(a))}),C&&(C.addEventListener("toggle",function(e){var t=e.target;if(!(!t||!t.matches||!t.matches(".library-group"))&&!Ne){var a=t.getAttribute("data-library-group-id");a&&(xe[a]=!t.open,Vt())}},!0),C.addEventListener("click",function(e){if(Ht){var t=e.target&&e.target.closest?e.target.closest(".library-group summary"):null;t&&(e.preventDefault(),e.stopPropagation())}},!0),C.addEventListener("pointerdown",function(e){if(e.button===0&&ne){var t=e.target&&e.target.closest?e.target.closest('.library-group[data-draggable="true"]'):null;t&&(j={group:t,startX:e.clientX,startY:e.clientY,active:!1,ghost:null,offsetX:0,offsetY:0})}}),window.addEventListener("pointermove",function(e){var t=j;if(t){if(!t.active){if(Math.abs(e.clientX-t.startX)<4&&Math.abs(e.clientY-t.startY)<4)return;_r(t.group)}e.preventDefault(),Ha(e.clientX,e.clientY),jr(e.clientX,e.clientY)}}),window.addEventListener("pointerup",function(){Wa()}),window.addEventListener("pointercancel",function(){Wa()}));var Ye=!1,Et="";function Xt(e){!e||!i||!i.postMessage||(Et=e,i.postMessage({type:"loadPath",path:e}))}le&&le.addEventListener("click",function(e){if(!(!i||!i.postMessage)){var t=e.target&&e.target.closest?e.target.closest(".home-group-cwd"):null;if(t){var a=t.getAttribute("data-cwd-path")||"";a&&i.postMessage({type:"openPath",path:a});return}var r=e.target&&e.target.closest?e.target.closest(".doc-reveal"):null;if(r){e.preventDefault(),e.stopPropagation();var o=r.getAttribute("data-reveal-path")||"";o&&i.postMessage({type:"openPath",path:o});return}var s=e.target&&e.target.closest?e.target.closest(".doc-card"):null;if(s){var u=s.getAttribute("data-path")||"";u&&(Ye=!0,l(n("status.opening")),Xt(u))}}}),le&&le.addEventListener("keydown",function(e){if(!(e.key!=="Enter"&&e.key!==" ")){var t=e.target&&e.target.closest?e.target.closest(".doc-reveal"):null;if(!(!t||!i||!i.postMessage)){e.preventDefault(),e.stopPropagation();var a=t.getAttribute("data-reveal-path")||"";a&&i.postMessage({type:"openPath",path:a})}}});function Xe(){Ft.hidden=A(),document.body.classList.toggle("has-document",A()),Pe&&(Pe.hidden=!z),!Ft.hidden&&bt&&St()}function Ae(){Mr.classList.toggle("active",v?A():k==="edit"),Ot.classList.toggle("active",v?A():k==="preview"),(v||k==="edit")&&p&&requestAnimationFrame(function(){p.layout()})}function za(e){v||!i||!i.panel||!i.panel.setTitle||i.panel.setTitle(e||n("home.title")).catch(function(){})}function Vr(e){return e?"document:"+encodeURIComponent(e):""}function Ua(e){if(!e||e.indexOf("document:")!==0)return"";try{var t=decodeURIComponent(e.slice(9));return/^(?:\/|[A-Za-z]:[\\/])/.test(t)?t:""}catch{return""}}var Ce="";function _a(e){!e||e===f||!i||!i.postMessage||(Ce=e,Xt(e))}function ye(){if(!(!v||!i||!i.appView||!i.appView.breadcrumb)){var e=A()&&f?[{id:Vr(f),title:W||n("common.markdownDocDefault"),icon:"file-text"}]:[];i.appView.breadcrumb.set(e).catch(function(){})}}function Gr(){Ta||!i||!i.appView||!i.appView.breadcrumb||(Ta=!0,i.appView.breadcrumb.onNavigate(function(e){if(!e.id){A()&&nt().then(ye);return}var t=Ua(e.id);t?_a(t):i.appView.breadcrumb.set([]).catch(function(){})}),i.appView.breadcrumb.onRestore(function(e){var t=Array.isArray(e.levels)?e.levels:[];if(!t.length){A()&&nt().then(ye);return}var a=t.length===1&&Ua(t[0].id);if(!a){i.appView.breadcrumb.set([]).catch(function(){}),A()&&nt().then(ye);return}_a(a)}))}function Yr(){var e=[{id:"style:kami",label:"Kami"},{id:"style:bauhaus",label:"Bauhaus"},{id:"style:blueprint",label:"Blueprint"},{id:"style:botanical",label:"Botanical"},{id:"style:newsprint",label:"Newsprint"},{id:"style:retro",label:"Retro"},{id:"style:sketch",label:"Sketch"},{id:"style:terminal",label:"Terminal"},{id:"style-sep",label:"",separator:!0}],t=L==="custom"&&!!O&&!q.some(function(s){return s&&s.css===O});if(t){for(var a=0;a<3;a++)e.push({id:"style:slot-save:"+a,label:n("aiStyle.saveToSlot",{n:a+1})});e.push({id:"style-save-sep",label:"",separator:!0})}for(var r=0;r<3;r++){var o=q[r];e.push(o?{id:"style:slot-use:"+r,label:n("toolbar.style.customSlot",{n:r+1,label:o.label})}:{id:"style:slot-use:"+r,label:n("toolbar.style.customSlotEmpty",{n:r+1}),disabled:!0})}return e}function Xr(){var e="ext:markdown-editor-icons/save",t=n("toolbar.save.label"),a=n("toolbar.save.tooltipDefault");P?(t=n("toolbar.save.label"),a=n("toolbar.save.tooltipDirty")):Fe&&(e="ext:markdown-editor-icons/save-check",t=n("toolbar.save.labelSaved"),a=n("toolbar.save.tooltipSaved"));var r=A();return[{id:"home",icon:"house",tooltip:n("toolbar.home.tooltip")},{id:"open",icon:"ext:markdown-editor-icons/folder-open",tooltip:f||W||n("toolbar.open.tooltipDefault"),disabled:Y},{id:"save",icon:e,label:t,tooltip:a,disabled:!P},{type:"separator"},{id:"mode",icon:_e?"ext:markdown-editor-icons/hourglass":"ext:markdown-editor-icons/swatch-book",label:n("toolbar.mode.label"),tooltip:n(r?_e?"toolbar.mode.tooltipRendering":k==="edit"?"toolbar.mode.tooltipToPreview":"toolbar.mode.tooltipToEdit":"toolbar.needDoc"),checked:k==="preview",disabled:!r},{type:"menu",id:"style",icon:"palette",tooltip:n(k==="preview"?"toolbar.style.tooltip":"toolbar.style.tooltipNeedsPreview"),disabled:k!=="preview",items:Yr()},{type:"spacer"},{id:"focus",icon:"ext:markdown-editor-icons/feather",tooltip:n(r?B?"toolbar.focus.tooltipOn":"toolbar.focus.tooltipOff":"toolbar.needDoc"),checked:B,disabled:!r||k==="preview"},{type:"menu",id:"font-size",icon:"ext:markdown-editor-icons/type",tooltip:n(r?k==="preview"?"toolbar.fontSize.tooltipPreview":"toolbar.fontSize.tooltipEdit":"toolbar.needDoc"),disabled:!r||k==="preview",items:[{id:"comfort:read",label:n("toolbar.comfort.read"),checked:!R},{id:"comfort:write",label:n("toolbar.comfort.write"),checked:R},{id:"font-comfort-sep",label:"",separator:!0},{id:"font-size:14",label:n("toolbar.fontSize.small"),checked:H===14},{id:"font-size:16",label:n("toolbar.fontSize.medium"),checked:H===16},{id:"font-size:18",label:n("toolbar.fontSize.large"),checked:H===18},{id:"font-sep",label:"",separator:!0},{id:"font-family:rounded",label:n("toolbar.fontFamily.default"),checked:K==="rounded"},{id:"font-family:songti",label:n("toolbar.fontFamily.serif"),checked:K==="songti"}]},{type:"menu",id:"more",icon:"settings",items:[{id:"reload",label:n("toolbar.more.reload"),disabled:k!=="preview"},{id:"reveal",label:n("toolbar.more.reveal"),disabled:!r},{id:"recentSession",label:n("toolbar.more.recentSession"),disabled:!fe},{id:"more-sep",label:"",separator:!0},{id:"about",label:n("toolbar.more.about")}]}]}function D(e,t,a,r){return'<button type="button" data-app-action="'+e+'"'+(a?' class="checked"':"")+(r?" disabled":"")+"><span>"+t+"</span>"+(a?"<span>\u2713</span>":"")+"</button>"}function ja(){if(dt){var e=["kami","bauhaus","blueprint","botanical","newsprint","retro","sketch","terminal"],t=e.map(function(s){return D("style:"+s,s[0].toUpperCase()+s.slice(1),L===s)}).join("")+"<hr>",a=L==="custom"&&!!O&&!q.some(function(s){return s&&s.css===O});a&&(t+=[0,1,2].map(function(s){return D("style:slot-save:"+s,n("aiStyle.saveToSlot",{n:s+1}),!1)}).join("")+"<hr>");for(var r=0;r<3;r++){var o=q[r];t+=o?D("style:slot-use:"+r,n("toolbar.style.customSlot",{n:r+1,label:o.label}),L==="custom"&&O===o.css):D("style:slot-use:"+r,n("toolbar.style.customSlotEmpty",{n:r+1}),!1)}dt.innerHTML=t}pt&&(pt.innerHTML=D("comfort:read",n("toolbar.comfort.read"),!R)+D("comfort:write",n("toolbar.comfort.write"),R)+"<hr>"+D("font-size:14",n("toolbar.fontSize.small"),H===14)+D("font-size:16",n("toolbar.fontSize.medium"),H===16)+D("font-size:18",n("toolbar.fontSize.large"),H===18)+"<hr>"+D("font-family:rounded",n("toolbar.fontFamily.default"),K==="rounded")+D("font-family:songti",n("toolbar.fontFamily.serif"),K==="songti")),ft&&(ft.innerHTML=D("reload",n("toolbar.more.reload"),!1)+D("reveal",n("toolbar.more.reveal"),!1)+D("recentSession",n("toolbar.more.recentSession"),!1,!fe)+"<hr>"+D("about",n("toolbar.more.about"),!1))}function Kr(){if(v){var e=A();if(re){re.disabled=!P,re.classList.toggle("dirty",P);var t=Fe?"toolbar.save.tooltipSaved":P?"toolbar.save.tooltipDirty":"toolbar.save.tooltipDefault";re.setAttribute("data-tooltip",n(t));var a=re.querySelector(".ic-save"),r=re.querySelector(".ic-save-check");a&&(a.hidden=Fe),r&&(r.hidden=!Fe)}Be&&(Be.disabled=!e,Be.classList.toggle("checked",B)),Re&&(Re.disabled=!e,Re.classList.toggle("checked",V)),ut&&(ut.disabled=Y),ct&&(ct.disabled=!e||!V,ct.setAttribute("data-tooltip",n(V?"toolbar.style.tooltip":"toolbar.style.tooltipNeedsPreview"))),Nt&&(Nt.disabled=!e),ja()}}function b(){v?Kr():i&&i.postMessage({type:"setToolbar",toolbar:Xr()})}function Ke(e){if(F(),v){k="edit",Ae(),G(),b();return}k=e,Ae(),b(),k==="preview"&&G()}function Jr(e){return!i||!i.postMessage?Promise.reject(new Error("No host bridge.")):new Promise(function(t,a){var r=new FileReader;r.onload=function(){var o=typeof r.result=="string"?r.result:"",s=o.indexOf(","),u=s>=0?o.slice(s+1):"";if(!u){a(new Error("Could not read pasted image."));return}var c=++Tr;me[c]={resolve:t,reject:a},setTimeout(function(){me[c]&&(delete me[c],a(new Error(n("status.pasteImageTimeout"))))},15e3),i.postMessage({type:"pasteImage",data:u,mimeType:e.type,requestId:c})},r.onerror=function(){a(new Error("Could not read pasted image."))},r.readAsDataURL(e)})}var p=window.MarkdownCodeMirror.create({parent:Se,value:g,onChange:function(e){g=e,F(),Xe(),Te(!0),sr(),on()},onOpenLink:function(e){i&&i.postMessage&&i.postMessage({type:"openLink",url:e})},onOpenImage:function(e){if(!(!i||!i.postMessage)){try{var t=new URL(e);if(t.protocol==="finch-file:"&&t.hostname==="local"){var a=t.searchParams.get("path");if(a){i.postMessage({type:"openImage",path:a});return}}}catch{}i.postMessage({type:"openImage",url:e})}},onPasteImage:Jr,onAiHintTrigger:kn,onAiWorkingCancel:function(){!v||!N||!f||!i||!i.postMessage||i.postMessage({type:"cancelRewrite",path:f,sessionId:N.sessionId,turnId:N.turnId})}});p.setFontSize(H),p.setFontFamily(Me[K]),p.setComfortWriting(R),p.setFocusMode(B),p.scrollDOM.addEventListener("scroll",F);function $r(){return L==="custom"?O:""}var Va="user-content-mdl-",Kt=0,Jt={side:"",value:-1,at:0},Je={editor:!1,preview:!1},De=[];function Zr(e){if(!v)return e;for(var t=e.split(`
|
|
11
|
-
`),a=[],r=!1,o=0;o<t.length;o++){var s=t[o],
|
|
12
|
-
`)}function $t(){if(
|
|
10
|
+
Give a drop-in replacement snippet first; once I confirm, write it back to the source file ({path}) as a targeted local replacement, not a full resend of the document.`,"annotate.reminder":"Only propose the rewrite \u2014 don't write to the source file before I confirm. Reply in natural language (e.g. \u201CI'll put it into the file once you confirm\u201D); never name the tool or its actions. [MANDATORY, not optional] Whenever this turn proposes a rewrite and is waiting on my confirmation, calling Session action=suggest with 1\u20133 one-tap confirmations (e.g. \u201CUse this one\u201D, \u201CUse the shorter version\u201D, \u201CTry another tone\u201D) is part of completing that same turn \u2014 writing the proposal text is only half the job. Do not treat the turn as done, and do not skip the call, just because the proposal text itself was already sent.","newdoc.needChat":"Use \u201CNew Document\u201D from the Finch chat instead.","newdoc.label":"New Markdown Document","newdoc.promptText":"I want to create a new Markdown document. First work out the title, content, and a not-yet-existing absolute save path from my request \u2014 ask me first if anything is missing. Once confirmed, write the full body to that path and open the new document in the editor.","newdoc.reminder":"Only create a new file; never overwrite an existing one. Reply in natural language and never name the tool or its actions. [MANDATORY, not optional] Whenever this turn ends still waiting on me to confirm a title, an angle, or a save location, it must call Session action=suggest with 1\u20133 one-tap options before the turn ends \u2014 asking the question in plain text is not enough on its own; skipping the call leaves the question unfinished.","newdoc.added":"Added the new-document prompt to the composer.","aiStyle.label":"Design a layout based on {file}","aiStyle.note":"One-click AI layout","aiStyle.baseNoteCustom":"The current base style is kami (your custom CSS layers on top of it)","aiStyle.baseNoteOther":"The current base style is {style}","aiStyle.pathMissing":"(No local file linked)","aiStyle.promptText":'Please design a custom layout CSS for this WeChat article. {baseNote}, and your CSS will layer on top of the base style. Requirements: write plain CSS rules only, with selectors scoped to tags/structure under #bm-md (e.g. #bm-md h1, #bm-md p, #bm-md blockquote, #bm-md pre code, #bm-md a, #bm-md strong, #bm-md table); don\u2019t use classes (bm.md\u2019s output has no classes, only inline styles), and use !important where needed to override the base style. You can draw on bm.md\u2019s built-in style language: kami (warm paper feel), bauhaus (geometric color-blocking), blueprint (technical grid), botanical (fresh green), newsprint (editorial serif), retro (nostalgic), sketch (hand-drawn), terminal (monospace dark). Article path: {path}. Once it\u2019s ready, call set_style directly (pass path="{path}", css, and a short label, no slot \u2014 passing path lets it find the right preview panel for this document even if I\u2019ve switched away) \u2014 don\u2019t ask me which slot to use first; the panel will pop up a lightweight \u201Csave as custom style\u201D button so I can decide after seeing the result.',"aiStyle.reminder":"Don\u2019t ask which slot to use before applying \u2014 just design it and call set_style (without slot) to apply it to the preview; whether to save it is for me to decide from the panel. Reply in natural language and never name the tool or its actions.","aiStyle.requested":"Asked AI to design a custom layout.","aiStyle.applied":"AI designed a layout and applied it to the preview.","aiStyle.saveToSlot":"Save as style {n}","aiStyle.appViewDesigning":"AI is designing a layout\u2026","aiStyle.appViewDone":"Layout design finished.","aiStyle.appViewFailed":"Layout design did not finish.","status.saved":"Saved.","status.savedWithNewChanges":"Saved \u2014 but the editor already has newer changes.","status.saveFailed":"Save failed: {err}","status.saving":"Saving\u2026","status.noSourceFile":"Not linked to a local file: click \u201COpen\u201D in the toolbar again to link it and enable saving.","status.pickerTimeout":'The file picker took too long to respond and switched to the in-browser picker \u2014 please click "Open" again.',"status.externalUpdateSkipped":"Detected an external file update; not loaded yet to avoid overwriting unsaved changes.","status.draftRestored":'Restored your last unsaved edits (differs from the file on disk). To discard, click "Open" and pick this file again, then choose "Discard".',"status.draftConflict":"A local unsaved draft exists, but the file was changed and saved elsewhere; loaded the latest file content \u2014 the draft is kept, not discarded.","status.sourceMissing":"The original file was moved or deleted; your content is still here \u2014 saving will recreate the file at its original path.","status.externalUpdateApplied":"Detected a file update and refreshed.","status.openingPicker":"Opening the file picker\u2026","status.opening":"Opening\u2026","status.opened":"Opened {file}.","status.contentUpdated":"Content updated.","status.contentUpdatedLine":"Updated line {line}.","status.contentUpdatedLines":"Updated lines {from}\u2013{to}.","status.contentUpdatedSpots":"Updated {count} spots, {lines} lines in total.","status.pasteImageTimeout":"Paste image timed out","status.pasteImageFailed":"Paste image failed: {msg}","status.clipboardPrepareTimeout":"Preparing WeChat images timed out","status.pleaseOpenArticle":"Open an article first.","status.copiedRich":"Rich HTML copied \u2014 paste it directly into the WeChat editor.","status.copiedPlainOnly":"Only plain text was copied; formatting didn't come through \u2014 please try again.","status.copyFailed":"Copy failed \u2014 please try again.","status.richCopyFailed":"Rich-text copy failed: {err}","status.clipboardUnsupported":"Copying images isn\u2019t supported here \u2014 use \u201CExport Image\u201D instead.","status.generatingImage":"Generating image\u2026","status.previewNotReady":"Preview isn't ready yet","status.imageCopied":"Image copied to the clipboard.","status.copyImageFailed":"Copy image failed: {err} (try \u201CExport Image\u201D instead)","status.exportImageFailedGeneric":"Export image failed: preview isn't ready yet.","status.exportImageFailed":"Export image failed: {err}","status.generatingPdf":"Generating PDF\u2026","status.exportPdfFailedGeneric":"Export PDF failed: preview isn't ready yet.","status.exportPdfFailed":"Export PDF failed: {err}","status.exported":"Exported: {path}","status.annotateOn":"Annotate is on \u2014 select text to ask AI to revise it.","status.annotateOff":"Annotate is off.","status.comfortWrite":"Comfortable mode is on \u2014 roomier line spacing.","status.comfortRead":"Compact mode is on.","status.focusOn":"Focus mode is on \u2014 inactive lines are dimmed.","status.focusOff":"Focus mode is off.","status.saveFailedNoReturn":"Save failed \u2014 staying on this document.","status.rendererAboutPrefix":"Renderer: local bmmd CLI (","status.rendererAboutSuffix":", LGPL-3.0).","status.appliedStyleSlot":"Applied \u201C{label}\u201D.","status.needCustomStyleFirst":"Apply a custom/AI-designed style first before saving it to a slot.","status.savedToSlot":"Saved to slot {slot}: {label}","status.serializeFailed":"Failed to serialize the preview content: {err}","status.imageConversionFailed":"The preview couldn't be converted to an image (it may contain external images that can't be read cross-origin)","status.imageGenFailed":"Failed to generate image data","status.clipboardPrepareFailedDefault":"Failed to prepare WeChat images","status.pasteImageFailedDefault":"Paste image failed","status.savedAppliedToSlot":"{labelPrefix}Saved and applied to custom style {slot}."}};function n(e,t){var a=it?st.zh:st.en,r=Object.prototype.hasOwnProperty.call(a,e)?a[e]:Object.prototype.hasOwnProperty.call(st.en,e)?st.en[e]:e;if(t)for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&(r=r.split("{"+o+"}").join(String(t[o])));return r}function Dt(e){var t=e||document;document.documentElement.lang=it?"zh-CN":"en",document.title=n("meta.title"),Array.prototype.forEach.call(t.querySelectorAll("[data-i18n]"),function(a){a.textContent=n(a.getAttribute("data-i18n"))}),Array.prototype.forEach.call(t.querySelectorAll("[data-i18n-title]"),function(a){a.title=n(a.getAttribute("data-i18n-title"))}),Array.prototype.forEach.call(t.querySelectorAll("[data-i18n-tooltip]"),function(a){var r=n(a.getAttribute("data-i18n-tooltip"));a.setAttribute("data-tooltip",r),a.setAttribute("aria-label",r)}),Array.prototype.forEach.call(t.querySelectorAll("[data-i18n-aria]"),function(a){a.setAttribute("aria-label",n(a.getAttribute("data-i18n-aria")))})}var Ft=document.getElementById("empty"),ha=document.getElementById("emptyNew"),ya=document.getElementById("emptyOpen"),Tt=document.getElementById("homeRecent"),le=document.getElementById("homeGrid"),lt=document.getElementById("homeHint"),Pt=[],ba=document.getElementById("homeTagline"),Ir=document.getElementById("editPane"),Ot=document.getElementById("previewPane"),ce=document.getElementById("previewResizer"),Se=document.getElementById("editor"),y=document.getElementById("article"),M=document.getElementById("status"),I=document.getElementById("popup"),_=document.getElementById("popupInput"),wa=document.getElementById("popupSend"),Sa=document.getElementById("popupShortcut"),Oe=document.getElementById("actions"),Lr=document.getElementById("actCopyWx"),Cr=document.getElementById("actCopyImg"),Ar=document.getElementById("actSaveImg"),Dr=document.getElementById("actSavePdf"),ke=document.getElementById("actAiStyle"),ka=document.getElementById("actToggle"),ue=document.getElementById("confirmOverlay"),xa=document.getElementById("confirmMessage"),Rt=document.getElementById("confirmCancel"),Bt=document.getElementById("confirmDiscard"),Re=document.getElementById("confirmSave"),Ea=document.getElementById("appToolbar"),Ma=document.getElementById("appHome"),Ia=document.getElementById("appLibrary"),ct=document.getElementById("appOpen"),re=document.getElementById("appSave"),Be=document.getElementById("appPreview"),ut=document.getElementById("appStyle"),dt=document.getElementById("appStyleMenu"),Ne=document.getElementById("appFocus"),Nt=document.getElementById("appFont"),pt=document.getElementById("appFontMenu"),Fr=document.getElementById("appMore"),ft=document.getElementById("appMoreMenu"),qt=document.getElementById("libraryDrawer"),mt=document.getElementById("libraryBackdrop"),La=document.getElementById("libraryClose"),vt=document.getElementById("libraryReorder"),Ca=document.getElementById("libraryReorderFooter"),Aa=document.getElementById("libraryReorderDone"),A=document.getElementById("libraryGroups"),Da="md-editor-library-groups-v1",de=[],xe={},pe=null,qe=null,ne=!1,He=[],j=null,Ht=!1,g=!1,Fa=!1,Ta=!1,H=null,fe=null,G=!0,Tr=!1,gt=0,We=!1,te=!0,x="edit",L="kami",O="",Ee="",W=[null,null,null],Me={songti:"Songti SC, STSong, SimSun, Noto Serif CJK SC, serif",rounded:"PingFang SC, Microsoft YaHei, Noto Sans CJK SC, sans-serif"},z=14,J="rounded",R=!1,B=!1;try{var ht=Number(localStorage.getItem("md-editor-font-size"));(ht===14||ht===16||ht===18)&&(z=ht);var Wt=localStorage.getItem("md-editor-font-family");Me[Wt]?J=Wt:Wt&&localStorage.removeItem("md-editor-font-family"),R=localStorage.getItem("md-editor-comfort-writing")==="1",B=localStorage.getItem("md-editor-focus-mode")==="1";var ze=JSON.parse(localStorage.getItem(Da)||"{}");Array.isArray(ze.order)&&(de=ze.order.filter(function(e){return typeof e=="string"})),ze.collapsed&&typeof ze.collapsed=="object"&&(xe=ze.collapsed)}catch{}te=!B;var h="",Ue="",U="",m="",T=null,N="",Ie=!1,Pa=0,Ve=!1,Oa=0,zt={},Le={},Pr=0,me={},Or=0,ve={},_e=0,$=null,yt=0,Ce=0,Ut=!1,w={text:"",mode:"replace"},E=0;function c(e,t){E&&(clearTimeout(E),E=0),M.textContent=e||"",M.className="status"+(t?" error":""),e&&(E=setTimeout(function(){E=0,M.textContent="",M.className="status"},5e3))}function ge(e,t,a,r){if(E&&(clearTimeout(E),E=0),M.replaceChildren(document.createTextNode(e||"")),M.className="status"+(t?" error":""),a){var o=document.createElement("button");o.type="button",o.className="status-inline-btn",o.textContent=n("appview.openSession"),o.addEventListener("click",function(){i&&i.navigation&&i.navigation.openSession&&i.navigation.openSession(a)}),M.appendChild(o)}r&&(E=setTimeout(function(){E=0,M.replaceChildren(),M.className="status"},r))}function Rr(){E&&(clearTimeout(E),E=0),M.replaceChildren(document.createTextNode(n("status.rendererAboutPrefix")));var e=document.createElement("a");e.href="https://bm.md/",e.textContent="bm.md",e.title="https://bm.md/",e.addEventListener("click",function(t){t.preventDefault(),i&&i.postMessage&&i.postMessage({type:"openLink",url:"https://bm.md/"})}),M.append(e,document.createTextNode(n("status.rendererAboutSuffix"))),M.className="status",E=setTimeout(function(){E=0,M.textContent="",M.className="status"},5e3)}function C(){return!!h||!!m}ha&&ha.addEventListener("click",async function(){if(!i||!i.composer){c(n("newdoc.needChat"),!0);return}try{await i.composer.addContexts([{type:"annotation",label:n("newdoc.label"),promptText:n("newdoc.promptText"),reminder:n("newdoc.reminder")}]),c(n("newdoc.added"))}catch(e){c(String(e),!0)}}),ya&&ya.addEventListener("click",function(){ia()});var je="",Vt="",_t="",bt=!1,Ra=!1,Ge="",he="";function S(e){return String(e).replace(/[&<>"]/g,function(t){return t==="&"?"&":t==="<"?"<":t===">"?">":"""})}function Ba(){ba&&(ba.textContent=Ge?n("home.tagline.withAssistant",{name:Ge}):n("home.tagline.default"))}function wt(){_&&(_.placeholder=w.mode==="continue"?n("popup.placeholderContinue",{name:Ge||"Finch"}):n("popup.placeholder",{name:Ge||"Finch"}))}function Br(e){return e?he&&e===he?"~":he&&(e.indexOf(he+"/")===0||e.indexOf(he+"\\")===0)?"~"+e.slice(he.length):e:""}function Nr(e){var t=46;if(!e||e.length<=t)return e;var a=e.indexOf("/")===-1&&e.indexOf("\\")!==-1?"\\":"/",r=e.slice(-(t-1)),o=r.indexOf(a);return o>0&&o<10&&(r=r.slice(o)),"\u2026"+r}function qr(){kt(Pt)}function Na(e){var t=new Date(e);if(!e||isNaN(t.getTime()))return"";var a=new Date,r=function(u){return u<10?"0"+u:String(u)},o=r(t.getHours())+":"+r(t.getMinutes()),s=t.toDateString()===a.toDateString();if(s)return n("home.today",{clock:o});var l=new Date(a.getTime()-864e5);return t.toDateString()===l.toDateString()?n("home.yesterday",{clock:o}):t.getFullYear()===a.getFullYear()?r(t.getMonth()+1)+"-"+r(t.getDate()):t.getFullYear()+"-"+r(t.getMonth()+1)+"-"+r(t.getDate())}function St(){!i||!i.postMessage||!bt||(Ra=!0,i.postMessage({type:"requestRecentDocuments",cwd:je,sessionId:Vt,spaceId:_t}))}function Hr(e){e=e||{};var t=e.relativePath||e.fileName||"";return'<button class="doc-card" type="button" data-path="'+S(e.path||"")+'" title="'+S(e.path||"")+'"><span class="doc-reveal" data-reveal-path="'+S(e.path||"")+'" role="button" tabindex="0" title="'+S(n("home.revealInFileManager"))+'" aria-label="'+S(n("home.revealInFileManager"))+'"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m6 14 1.45-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.55 6a2 2 0 0 1-1.94 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"/></svg></span><div class="doc-preview">'+S(e.preview||n("home.emptyDoc"))+'</div><div class="doc-foot"><div class="doc-title">'+S(e.title||e.fileName||n("home.untitled"))+'</div><div class="doc-sub"><span class="doc-path" data-full-path="'+S(t)+'">'+S(t)+'</span><span class="doc-time">'+S(Na(e.modifiedAt))+"</span></div></div></button>"}function kt(e){if(!(!le||!Tt||!lt)){var t=Array.isArray(e)?e:[];if(Pt=t,t.length===0){Tt.hidden=!0,lt.hidden=!1,lt.textContent=n(je?"home.hintScoped":"home.hintDefault");return}var a=qa(t);le.innerHTML=a.map(function(r){var o=r.documents.map(Hr).join(""),s=r.scopePath?'<button type="button" class="home-group-cwd" data-cwd-path="'+S(r.scopePath)+'" title="'+S(n("home.cwdTitle",{path:r.scopePath}))+'">'+S(Nr(Br(r.scopePath)))+"</button>":"",l='<div class="home-group-title"><span class="home-group-label">'+S(r.label)+'<span class="home-group-count">'+r.documents.length+"</span></span>"+s+"</div>";return'<div class="home-group">'+l+'<div class="home-grid">'+o+"</div></div>"}).join(""),Tt.hidden=!1,lt.hidden=!0,requestAnimationFrame(function(){Wr(le)})}}function Wr(e){for(var t="\u2026",a=e.querySelectorAll("[data-full-path]"),r=0;r<a.length;r++){var o=a[r],s=o.getAttribute("data-full-path")||"";if(o.textContent=s,!(!s||o.scrollWidth<=o.clientWidth+1)){for(var l=0,u=s.length,d=0;l<=u;){var f=l+u>>1;o.textContent=f>0?t+s.slice(s.length-f):t,o.scrollWidth<=o.clientWidth+1?(d=f,l=f+1):u=f-1}o.textContent=d>0?t+s.slice(s.length-d):t}}}function jt(){var e={order:de,collapsed:xe};try{localStorage.setItem(Da,JSON.stringify(e))}catch{}i&&i.postMessage&&i.postMessage({type:"saveLibraryGroups",libraryGroups:e})}function qa(e){var t={};return(Array.isArray(e)?e:[]).forEach(function(a){var r=a.scopeKind||"external",o=r==="workspace"?n("appview.libraryWorkspace"):r==="external"?n("appview.libraryOther"):a.scopeLabel||a.spaceName||n("appview.libraryOther"),s=r==="space"?"space:"+(a.spaceId||o):r==="workspace"?"workspace":"external";t[s]||(t[s]={id:s,kind:r,label:o,scopePath:"",documents:[]}),r!=="external"&&!t[s].scopePath&&a.scopePath&&(t[s].scopePath=a.scopePath),t[s].documents.push(a)}),Object.keys(t).map(function(a){return t[a]}).sort(function(a,r){if(a.kind==="external"||r.kind==="external")return a.kind===r.kind?0:a.kind==="external"?1:-1;var o=de.indexOf(a.id),s=de.indexOf(r.id);if(o>=0||s>=0)return(o<0?9999:o)-(s<0?9999:s);var l={space:0,workspace:1},u=l[a.kind]-l[r.kind];return u||a.label.localeCompare(r.label)})}function Gt(e){if(A){He=Array.isArray(e)?e:[];var t=qa(He);if(ne){zr(t);return}A.innerHTML=t.map(function(a){var r=a.documents.map(function(l){var u=l.relativePath||l.fileName||"";return'<button class="library-row" type="button" data-path="'+S(l.path||"")+'"><span class="library-row-main"><strong>'+S(l.title||l.fileName||n("home.untitled"))+'</strong><span class="library-row-meta"><span class="library-row-path" title="'+S(u)+'">'+S(u)+"</span><time>"+S(Na(l.modifiedAt))+"</time></span></span></button>"}).join(""),o=a.kind!=="external",s=!xe[a.id];return'<details class="library-group" data-library-group-id="'+S(a.id)+'"'+(o?' data-draggable="true"':"")+(s?" open":"")+'><summary><span class="library-group-title">'+S(a.label)+'</span><span class="library-group-count">'+a.documents.length+'</span></summary><div class="library-items">'+r+"</div></details>"}).join("")||'<p class="home-hint">'+S(n("home.hintDefault"))+"</p>"}}function zr(e){A.innerHTML=e.map(function(t){var a=t.kind!=="external";return'<div class="library-group library-group-reorder" data-library-group-id="'+S(t.id)+'"'+(a?' data-draggable="true"':"")+'><span class="library-reorder-handle" aria-hidden="true">'+(a?"\u22EE\u22EE":"")+'</span><span class="library-group-title">'+S(t.label)+'</span><span class="library-group-count">'+t.documents.length+"</span></div>"}).join("")||'<p class="home-hint">'+S(n("home.hintDefault"))+"</p>"}function Xt(e){ne=!!e,vt&&vt.classList.toggle("active",ne),Ca&&(Ca.hidden=!ne),Gt(He)}function xt(e){!qt||!mt||(qt.classList.toggle("open",!!e),qt.setAttribute("aria-hidden",e?"false":"true"),mt.hidden=!e,e?St():ne&&Xt(!1))}function Ur(){if(!(!pe||!A)){pe.classList.remove("dragging"),Array.prototype.forEach.call(A.querySelectorAll(".library-group.drag-over"),function(t){t.classList.remove("drag-over")}),de=Array.prototype.map.call(A.querySelectorAll('.library-group[data-draggable="true"]'),function(t){return t.getAttribute("data-library-group-id")}).filter(Boolean),kt(Pt);var e=qe||{};Array.prototype.forEach.call(A.querySelectorAll(".library-group"),function(t){var a=t.getAttribute("data-library-group-id");a in e&&(t.open=!!e[a])}),pe=null,setTimeout(function(){qe=null,jt()},0)}}function Vr(){j&&j.ghost&&j.ghost.parentNode&&j.ghost.parentNode.removeChild(j.ghost)}function Ha(e,t){var a=j;!a||!a.ghost||(a.ghost.style.left=e-a.offsetX+"px",a.ghost.style.top=t-a.offsetY+"px")}function _r(e){var t=j;if(!(!t||t.active)){t.active=!0,pe=e,qe={},ne||Array.prototype.forEach.call(A.querySelectorAll(".library-group"),function(o){var s=o.getAttribute("data-library-group-id");s&&(qe[s]=!!o.open),o.open=!1}),e.classList.add("dragging");var a=e.getBoundingClientRect(),r=e.cloneNode(!0);r.classList.add("library-drag-ghost"),r.classList.remove("dragging"),r.style.width=a.width+"px",t.ghost=r,t.offsetX=t.startX-a.left,t.offsetY=t.startY-a.top,document.body.appendChild(r),Ha(t.startX,t.startY)}}function jr(e,t){if(pe){var a=document.elementFromPoint(e,t),r=a&&a.closest?a.closest('.library-group[data-draggable="true"]'):null;if(Array.prototype.forEach.call(A.querySelectorAll(".library-group.drag-over"),function(s){s.classList.remove("drag-over")}),!(!r||r===pe)){r.classList.add("drag-over");var o=t>r.getBoundingClientRect().top+r.offsetHeight/2;A.insertBefore(pe,o?r.nextSibling:r)}}}function Wa(){var e=j;e&&(e.active&&(Vr(),Ur(),Ht=!0,setTimeout(function(){Ht=!1},0)),j=null)}Ia&&Ia.addEventListener("click",function(){xt(!0)}),La&&La.addEventListener("click",function(){xt(!1)}),mt&&mt.addEventListener("click",function(){xt(!1)}),vt&&vt.addEventListener("click",function(){Xt(!ne)}),Aa&&Aa.addEventListener("click",function(){Xt(!1)}),A&&A.addEventListener("click",function(e){var t=e.target&&e.target.closest?e.target.closest(".library-row"):null,a=t&&t.getAttribute("data-path");!a||!i||!i.postMessage||(xt(!1),Xe=!0,c(n("status.opening")),Yt(a))}),A&&(A.addEventListener("toggle",function(e){var t=e.target;if(!(!t||!t.matches||!t.matches(".library-group"))&&!qe){var a=t.getAttribute("data-library-group-id");a&&(xe[a]=!t.open,jt())}},!0),A.addEventListener("click",function(e){if(Ht){var t=e.target&&e.target.closest?e.target.closest(".library-group summary"):null;t&&(e.preventDefault(),e.stopPropagation())}},!0),A.addEventListener("pointerdown",function(e){if(e.button===0&&ne){var t=e.target&&e.target.closest?e.target.closest('.library-group[data-draggable="true"]'):null;t&&(j={group:t,startX:e.clientX,startY:e.clientY,active:!1,ghost:null,offsetX:0,offsetY:0})}}),window.addEventListener("pointermove",function(e){var t=j;if(t){if(!t.active){if(Math.abs(e.clientX-t.startX)<4&&Math.abs(e.clientY-t.startY)<4)return;_r(t.group)}e.preventDefault(),Ha(e.clientX,e.clientY),jr(e.clientX,e.clientY)}}),window.addEventListener("pointerup",function(){Wa()}),window.addEventListener("pointercancel",function(){Wa()}));var Xe=!1,Et="";function Yt(e){!e||!i||!i.postMessage||(Et=e,i.postMessage({type:"loadPath",path:e}))}le&&le.addEventListener("click",function(e){if(!(!i||!i.postMessage)){var t=e.target&&e.target.closest?e.target.closest(".home-group-cwd"):null;if(t){var a=t.getAttribute("data-cwd-path")||"";a&&i.postMessage({type:"openPath",path:a});return}var r=e.target&&e.target.closest?e.target.closest(".doc-reveal"):null;if(r){e.preventDefault(),e.stopPropagation();var o=r.getAttribute("data-reveal-path")||"";o&&i.postMessage({type:"openPath",path:o});return}var s=e.target&&e.target.closest?e.target.closest(".doc-card"):null;if(s){var l=s.getAttribute("data-path")||"";l&&(Xe=!0,c(n("status.opening")),Yt(l))}}}),le&&le.addEventListener("keydown",function(e){if(!(e.key!=="Enter"&&e.key!==" ")){var t=e.target&&e.target.closest?e.target.closest(".doc-reveal"):null;if(!(!t||!i||!i.postMessage)){e.preventDefault(),e.stopPropagation();var a=t.getAttribute("data-reveal-path")||"";a&&i.postMessage({type:"openPath",path:a})}}});function Ye(){Ft.hidden=C(),document.body.classList.toggle("has-document",C()),Oe&&(Oe.hidden=!N),!Ft.hidden&&bt&&St()}function Ae(){Ir.classList.toggle("active",g?C():x==="edit"),Ot.classList.toggle("active",g?C():x==="preview"),(g||x==="edit")&&p&&requestAnimationFrame(function(){p.layout()})}function za(e){g||!i||!i.panel||!i.panel.setTitle||i.panel.setTitle(e||n("home.title")).catch(function(){})}function Gr(e){return e?"document:"+encodeURIComponent(e):""}function Ua(e){if(!e||e.indexOf("document:")!==0)return"";try{var t=decodeURIComponent(e.slice(9));return/^(?:\/|[A-Za-z]:[\\/])/.test(t)?t:""}catch{return""}}var De="";function Va(e){!e||e===m||!i||!i.postMessage||(De=e,Yt(e))}function ye(){if(!(!g||!i||!i.appView||!i.appView.breadcrumb)){var e=C()&&m?[{id:Gr(m),title:U||n("common.markdownDocDefault"),icon:"file-text"}]:[];i.appView.breadcrumb.set(e).catch(function(){})}}function Xr(){Ta||!i||!i.appView||!i.appView.breadcrumb||(Ta=!0,i.appView.breadcrumb.onNavigate(function(e){if(!e.id){C()&&nt().then(ye);return}var t=Ua(e.id);t?Va(t):i.appView.breadcrumb.set([]).catch(function(){})}),i.appView.breadcrumb.onRestore(function(e){var t=Array.isArray(e.levels)?e.levels:[];if(!t.length){C()&&nt().then(ye);return}var a=t.length===1&&Ua(t[0].id);if(!a){i.appView.breadcrumb.set([]).catch(function(){}),C()&&nt().then(ye);return}Va(a)}))}function Yr(){var e=[{id:"style:kami",label:"Kami"},{id:"style:bauhaus",label:"Bauhaus"},{id:"style:blueprint",label:"Blueprint"},{id:"style:botanical",label:"Botanical"},{id:"style:newsprint",label:"Newsprint"},{id:"style:retro",label:"Retro"},{id:"style:sketch",label:"Sketch"},{id:"style:terminal",label:"Terminal"},{id:"style-sep",label:"",separator:!0}],t=L==="custom"&&!!O&&!W.some(function(s){return s&&s.css===O});if(t){for(var a=0;a<3;a++)e.push({id:"style:slot-save:"+a,label:n("aiStyle.saveToSlot",{n:a+1})});e.push({id:"style-save-sep",label:"",separator:!0})}for(var r=0;r<3;r++){var o=W[r];e.push(o?{id:"style:slot-use:"+r,label:n("toolbar.style.customSlot",{n:r+1,label:o.label})}:{id:"style:slot-use:"+r,label:n("toolbar.style.customSlotEmpty",{n:r+1}),disabled:!0})}return e}function Kr(){var e="ext:markdown-editor-icons/save",t=n("toolbar.save.label"),a=n("toolbar.save.tooltipDefault");P?(t=n("toolbar.save.label"),a=n("toolbar.save.tooltipDirty")):Te&&(e="ext:markdown-editor-icons/save-check",t=n("toolbar.save.labelSaved"),a=n("toolbar.save.tooltipSaved"));var r=C();return[{id:"home",icon:"house",tooltip:n("toolbar.home.tooltip")},{id:"open",icon:"ext:markdown-editor-icons/folder-open",tooltip:m||U||n("toolbar.open.tooltipDefault"),disabled:Y},{id:"save",icon:e,label:t,tooltip:a,disabled:!P},{type:"separator"},{id:"mode",icon:Ve?"ext:markdown-editor-icons/hourglass":"ext:markdown-editor-icons/swatch-book",label:n("toolbar.mode.label"),tooltip:n(r?Ve?"toolbar.mode.tooltipRendering":x==="edit"?"toolbar.mode.tooltipToPreview":"toolbar.mode.tooltipToEdit":"toolbar.needDoc"),checked:x==="preview",disabled:!r},{type:"menu",id:"style",icon:"palette",tooltip:n(x==="preview"?"toolbar.style.tooltip":"toolbar.style.tooltipNeedsPreview"),disabled:x!=="preview",items:Yr()},{type:"spacer"},{id:"focus",icon:"ext:markdown-editor-icons/feather",tooltip:n(r?B?"toolbar.focus.tooltipOn":"toolbar.focus.tooltipOff":"toolbar.needDoc"),checked:B,disabled:!r||x==="preview"},{type:"menu",id:"font-size",icon:"ext:markdown-editor-icons/type",tooltip:n(r?x==="preview"?"toolbar.fontSize.tooltipPreview":"toolbar.fontSize.tooltipEdit":"toolbar.needDoc"),disabled:!r||x==="preview",items:[{id:"comfort:read",label:n("toolbar.comfort.read"),checked:!R},{id:"comfort:write",label:n("toolbar.comfort.write"),checked:R},{id:"font-comfort-sep",label:"",separator:!0},{id:"font-size:14",label:n("toolbar.fontSize.small"),checked:z===14},{id:"font-size:16",label:n("toolbar.fontSize.medium"),checked:z===16},{id:"font-size:18",label:n("toolbar.fontSize.large"),checked:z===18},{id:"font-sep",label:"",separator:!0},{id:"font-family:rounded",label:n("toolbar.fontFamily.default"),checked:J==="rounded"},{id:"font-family:songti",label:n("toolbar.fontFamily.serif"),checked:J==="songti"}]},{type:"menu",id:"more",icon:"settings",items:[{id:"reload",label:n("toolbar.more.reload"),disabled:x!=="preview"},{id:"reveal",label:n("toolbar.more.reveal"),disabled:!r},{id:"recentSession",label:n("toolbar.more.recentSession"),disabled:!fe},{id:"more-sep",label:"",separator:!0},{id:"about",label:n("toolbar.more.about")}]}]}function D(e,t,a,r){return'<button type="button" data-app-action="'+e+'"'+(a?' class="checked"':"")+(r?" disabled":"")+"><span>"+t+"</span>"+(a?"<span>\u2713</span>":"")+"</button>"}function _a(){if(dt){var e=["kami","bauhaus","blueprint","botanical","newsprint","retro","sketch","terminal"],t=e.map(function(s){return D("style:"+s,s[0].toUpperCase()+s.slice(1),L===s)}).join("")+"<hr>",a=L==="custom"&&!!O&&!W.some(function(s){return s&&s.css===O});a&&(t+=[0,1,2].map(function(s){return D("style:slot-save:"+s,n("aiStyle.saveToSlot",{n:s+1}),!1)}).join("")+"<hr>");for(var r=0;r<3;r++){var o=W[r];t+=o?D("style:slot-use:"+r,n("toolbar.style.customSlot",{n:r+1,label:o.label}),L==="custom"&&O===o.css):D("style:slot-use:"+r,n("toolbar.style.customSlotEmpty",{n:r+1}),!1)}dt.innerHTML=t}pt&&(pt.innerHTML=D("comfort:read",n("toolbar.comfort.read"),!R)+D("comfort:write",n("toolbar.comfort.write"),R)+"<hr>"+D("font-size:14",n("toolbar.fontSize.small"),z===14)+D("font-size:16",n("toolbar.fontSize.medium"),z===16)+D("font-size:18",n("toolbar.fontSize.large"),z===18)+"<hr>"+D("font-family:rounded",n("toolbar.fontFamily.default"),J==="rounded")+D("font-family:songti",n("toolbar.fontFamily.serif"),J==="songti")),ft&&(ft.innerHTML=D("reload",n("toolbar.more.reload"),!1)+D("reveal",n("toolbar.more.reveal"),!1)+D("recentSession",n("toolbar.more.recentSession"),!1,!fe)+"<hr>"+D("about",n("toolbar.more.about"),!1))}function Jr(){if(g){var e=C();if(re){re.disabled=!P,re.classList.toggle("dirty",P);var t=Te?"toolbar.save.tooltipSaved":P?"toolbar.save.tooltipDirty":"toolbar.save.tooltipDefault";re.setAttribute("data-tooltip",n(t));var a=re.querySelector(".ic-save"),r=re.querySelector(".ic-save-check");a&&(a.hidden=Te),r&&(r.hidden=!Te)}Ne&&(Ne.disabled=!e,Ne.classList.toggle("checked",B)),Be&&(Be.disabled=!e,Be.classList.toggle("checked",G)),ct&&(ct.disabled=Y),ut&&(ut.disabled=!e||!G,ut.setAttribute("data-tooltip",n(G?"toolbar.style.tooltip":"toolbar.style.tooltipNeedsPreview"))),Nt&&(Nt.disabled=!e),_a()}}function k(){g?Jr():i&&i.postMessage({type:"setToolbar",toolbar:Kr()})}function Ke(e){if(F(),g){x="edit",Ae(),X(),k();return}x=e,Ae(),k(),x==="preview"&&X()}function $r(e){return!i||!i.postMessage?Promise.reject(new Error("No host bridge.")):new Promise(function(t,a){var r=new FileReader;r.onload=function(){var o=typeof r.result=="string"?r.result:"",s=o.indexOf(","),l=s>=0?o.slice(s+1):"";if(!l){a(new Error("Could not read pasted image."));return}var u=++Pr;me[u]={resolve:t,reject:a},setTimeout(function(){me[u]&&(delete me[u],a(new Error(n("status.pasteImageTimeout"))))},15e3),i.postMessage({type:"pasteImage",data:l,mimeType:e.type,requestId:u})},r.onerror=function(){a(new Error("Could not read pasted image."))},r.readAsDataURL(e)})}var p=window.MarkdownCodeMirror.create({parent:Se,value:h,onChange:function(e){h=e,F(),Ye(),Pe(!0),lr(),sn()},onOpenLink:function(e){i&&i.postMessage&&i.postMessage({type:"openLink",url:e})},onOpenImage:function(e){if(!(!i||!i.postMessage)){try{var t=new URL(e);if(t.protocol==="finch-file:"&&t.hostname==="local"){var a=t.searchParams.get("path");if(a){i.postMessage({type:"openImage",path:a});return}}}catch{}i.postMessage({type:"openImage",url:e})}},onPasteImage:$r,onAiHintTrigger:En,onAiWorkingCancel:function(){!g||!H||!m||!i||!i.postMessage||i.postMessage({type:"cancelRewrite",path:m,sessionId:H.sessionId,turnId:H.turnId})}});p.setFontSize(z),p.setFontFamily(Me[J]),p.setComfortWriting(R),p.setFocusMode(B),p.scrollDOM.addEventListener("scroll",F);function Zr(){return L==="custom"?O:""}var ja="user-content-mdl-",Kt=0,Jt={side:"",value:-1,at:0},Je={editor:!1,preview:!1},Fe=[];function Qr(e){if(!g)return e;for(var t=e.split(`
|
|
11
|
+
`),a=[],r=!1,o=0;o<t.length;o++){var s=t[o],l=/^[ \t]*(?:```|~~~)/.test(s),u=o+1;if(l){r=!r,a.push(s);continue}var d=s.trim(),f=r||d===""||/\\\s*$/.test(s)||/^<[a-zA-Z!]/.test(d)||/^!\[[^\]]*\]\([^)]*\)\s*$/.test(d)||/^\s*\|/.test(s)&&/[|]\s*$/.test(s),b=!f&&/[|]/.test(s)&&o+1<t.length&&/^[ \t]*\|?[\s:|-]+\|?[ \t]*$/.test(t[o+1])&&/-/.test(t[o+1]);if(b){a.push(s);for(var v=o+1;v<t.length&&/[|]/.test(t[v]);)a.push(t[v]),v++;o=v-1;continue}a.push(f?s:s+'<a id="mdl-'+u+'"></a>')}return a.join(`
|
|
12
|
+
`)}function $t(){if(Fe=[],Z=null,!(!g||!Ie)){var e=y.contentDocument;if(e){var t=e.querySelector("#bm-md");if(t){for(var a=e.querySelectorAll('a[id^="'+ja+'"]'),r=0;r<a.length;r++){var o=a[r].id,s=Number(o.slice(ja.length));!Number.isFinite(s)||s<1||t.contains(a[r])&&Fe.push({line:s,el:a[r]})}Fe.sort(function(l,u){return l.line-u.line}),Z=null}}}}function Ga(){var e=y.contentDocument;return e&&e.scrollingElement?e.scrollingElement.scrollTop:0}function en(e){var t=y.contentDocument;if(!(!t||!t.scrollingElement)){var a=t.scrollingElement,r=Math.max(0,Math.min(e,a.scrollHeight-a.clientHeight));Math.abs(a.scrollTop-r)<1||(Jt={side:"preview",value:r,at:Date.now()},a.scrollTop=r)}}function tn(e){if(!e)return 0;var t=y.contentDocument,a=t&&t.scrollingElement;return e.getBoundingClientRect().bottom+(a?a.scrollTop:0)}var Z=null;function an(){if(Z=null,!Fe.length||!p||!p.scrollDOM)return null;var e=y.contentDocument,t=e&&e.scrollingElement;if(!t)return null;var a=Math.max(0,p.scrollDOM.scrollHeight-p.scrollDOM.clientHeight),r=Math.max(0,t.scrollHeight-t.clientHeight);if(a<=0||r<=0)return null;for(var o=[0],s=[0],l=0;l<Fe.length;l++){var u=Fe[l],d=p.lineBottom(u.line);if(d!=null){var f=tn(u.el);if(!(!(d>o[o.length-1]+1)||!(f>s[s.length-1]+1))){if(d>=a||f>=r)break;o.push(d),s.push(f)}}}return o.push(a),s.push(r),Z={e:o,p:s,eMax:a,pMax:r,pHeight:t.scrollHeight,eHeight:p.scrollDOM.scrollHeight},Z}function rn(){var e=y.contentDocument,t=e&&e.scrollingElement;return!t||!p||!p.scrollDOM?null:!Z||Z.pHeight!==t.scrollHeight||Z.eHeight!==p.scrollDOM.scrollHeight?an():Z}function Xa(e,t,a){var r=e.length;if(!r)return a;if(a<=e[0])return t[0];if(a>=e[r-1])return t[r-1];for(var o=0,s=r-1;o<s-1;){var l=o+s>>1;e[l]<=a?o=l:s=l}var u=e[s]-e[o]||1;return t[o]+(a-e[o])/u*(t[s]-t[o])}function Ya(e){Je[e]=!0,!Kt&&(Kt=requestAnimationFrame(function(){Kt=0,nn()}))}function Ka(e){var t=Jt;if(t.side!==e||Date.now()-t.at>300)return!1;var a=e==="editor"?p.scrollDOM.scrollTop:Ga();return!(Math.abs(t.value-a)>2)}function nn(){var e=Je.editor,t=Je.preview;if(Je.editor=!1,Je.preview=!1,!(!g||!C()||!G)){var a=rn();if(a){if(e)en(Xa(a.e,a.p,p.scrollDOM.scrollTop));else if(t){var r=Xa(a.p,a.e,Ga());Jt={side:"editor",value:r,at:Date.now()},Math.abs(p.scrollDOM.scrollTop-r)>=1&&(p.scrollDOM.scrollTop=r)}}}}function on(){Ka("editor")||!g||!C()||!G||Ya("editor")}function Ja(){Ka("preview")||!g||!C()||!G||Ya("preview")}function sn(){g&&(gt&&clearTimeout(gt),gt=setTimeout(function(){gt=0,X()},420))}function X(){if(!(!h||!i)){var e=++Pa;Ve=!0,k(),i.postMessage({type:"renderBm",markdown:Qr(h),markdownStyle:L==="custom"?"kami":L,customCss:Zr(),requestId:e})}}function ln(){var e=y.contentDocument,t=e&&e.scrollingElement;return t?{top:t.scrollTop}:null}function cn(e){var t=y.contentDocument,a=t&&t.scrollingElement;!e||!a||(a.scrollTop=Math.min(e.top,Math.max(0,a.scrollHeight-a.clientHeight)))}function un(){try{return getComputedStyle(y).backgroundColor||""}catch{return""}}function dn(e,t,a){var r=Math.min(3,Math.max(2,(window.devicePixelRatio||1)*2)),o;try{o=new XMLSerializer().serializeToString(e)}catch(l){return Promise.reject(l)}var s="data:image/svg+xml;charset=utf-8,"+encodeURIComponent(o);return new Promise(function(l,u){var d=new Image;d.decoding="sync",d.onload=function(){try{var f=document.createElement("canvas");f.width=Math.max(1,Math.round(t*r)),f.height=Math.max(1,Math.round(a*r));var b=f.getContext("2d");b.scale(r,r);var v="";try{v=getComputedStyle(e).backgroundColor}catch{v=""}v&&v!=="rgba(0, 0, 0, 0)"&&v!=="transparent"&&(b.fillStyle=v,b.fillRect(0,0,t,a)),b.drawImage(d,0,0,t,a),l(f.toDataURL("image/png"))}catch(q){u(q)}},d.onerror=function(){u(new Error("svg rasterize failed"))},d.src=s})}function $a(){if(!(!Ie||!y.contentDocument||!y.contentDocument.body)){var e=y.contentDocument,t=Array.prototype.slice.call(e.querySelectorAll("figure.figure-mermaid > svg, figure.figure-infographic > svg"));t.length&&Promise.all(t.map(function(a){var r=a.closest("figure"),o=a.getBoundingClientRect(),s=Math.ceil(o.width)||a.viewBox&&a.viewBox.baseVal&&a.viewBox.baseVal.width||600,l=Math.ceil(o.height)||a.viewBox&&a.viewBox.baseVal&&a.viewBox.baseVal.height||400;return dn(a,s,l).then(function(u){var d=e.createElement("img");d.src=u,d.alt=r&&r.classList.contains("figure-infographic")?"Infographic":"Mermaid diagram",d.style.display="block",d.style.width="100%",d.style.height="auto",a.replaceWith(d)}).catch(function(){})})).then(function(){e.body&&(N=e.body.innerHTML)})}}function Za(e){var t=ln(),a=y.contentDocument;N=e;var r=un();if(Ie&&a&&a.body){a.body.innerHTML=N,r&&(a.body.style.background=r),cn(t),er(),$t(),$a();return}y.srcdoc='<!doctype html><meta charset="utf-8"><base target="_blank"><style>html,body{margin:0!important;padding:0!important;min-height:100%}body{background:'+(r||"transparent")+"}#bm-md{min-height:100dvh}</style><body>"+N}function Qa(e,t,a){return{start:e.slice(0,t).split(`
|
|
13
13
|
`).length,end:e.slice(0,a).split(`
|
|
14
|
-
`).length}}function
|
|
15
|
-
`;if(s){var u=/^[ \t]*(?:```|~~~)[^\n]*/.exec(e.slice(o));if(u){o+=u[0].length;continue}var c=/^[ \t]*(?:#{1,6}|>+|[-+*]|\d+[.)])[ \t]+/.exec(e.slice(o));if(c){o+=c[0].length;continue}}var d=/^!?\[([^\]]*)\]\((?:\\.|[^)])*\)/.exec(e.slice(o));if(d){for(var m=o+d[0].indexOf("[")+1,x=0;x<d[1].length;x++)/[*_~`]/.test(d[1][x])||r(d[1][x],m+x);o+=d[0].length;continue}var S=/^<[^>]+>/.exec(e.slice(o));if(S){o+=S[0].length;continue}if(e[o]==="\\"&&o+1<e.length){r(e[o+1],o+1),o+=2;continue}if(/[*_~`]/.test(e[o])){o++;continue}r(e[o],o),o++}return cn(t,a)}function pn(e,t){var a=e.indexOf(t);if(a>=0)return{start:a,end:a+t.length};var r=dn(e),o=t.replace(/\s+/g," ").trim(),s=r.text.indexOf(o);if(s>=0)return{start:r.map[s],end:r.map[s+o.length-1]+1};if(o.length>=12){var u=o.slice(0,6),c=o.slice(-6),d=r.text.indexOf(u),m=r.text.indexOf(c,Math.max(0,d+u.length));if(d>=0&&m>=d)return{start:r.map[d],end:r.map[m+c.length-1]+1}}return null}function fn(e){return String(e||"").split(/[\\/]/).pop()||""}function Qa(){var e=w.contentDocument;if(!e||e.__bound)return;e.__bound=!0;function t(){if(te){var a=w.contentWindow,r=a.getSelection(),o=r.toString().trim();if(!(!o||!r.rangeCount)){var s=r.getRangeAt(0),u=Array.from(s.getClientRects()),c=w.getBoundingClientRect(),d=u.map(function(U){return{top:c.top+U.top,left:c.left+U.left,width:U.width,height:U.height}}),m=u[0]||s.getBoundingClientRect(),x=u[u.length-1]||m,S=pn(g,o),Q=S?Za(g,S.start,S.end):null;tr(o,{startTop:c.top+m.top,startLeft:c.left+m.left,endBottom:c.top+x.bottom,endLeft:c.left+x.left},d,Q,"preview")}}}e.addEventListener("mouseup",t),e.addEventListener("mousedown",function(){be(),F()}),e.addEventListener("keyup",t),e.addEventListener("keydown",function(a){(a.metaKey||a.ctrlKey)&&(a.key==="p"||a.key==="P")&&(a.preventDefault(),Ke("edit"))}),e.addEventListener("scroll",function(){be(),F()},!0),w.contentWindow.addEventListener("scroll",function(){be(),F()})}w.onload=function(){Ue=!0,Qa(),$t()};function er(){p&&p.scrollDOM&&!p.scrollDOM.__scrollSyncBound&&(p.scrollDOM.__scrollSyncBound=!0,p.scrollDOM.addEventListener("scroll",nn,{passive:!0}));var e=w.contentDocument;if(e&&!e.__scrollSyncBound){e.__scrollSyncBound=!0;var t=e.scrollingElement||e.documentElement;t&&t.addEventListener("scroll",Ja,{passive:!0}),e.defaultView&&e.defaultView.addEventListener("scroll",Ja,{passive:!0})}}er(),window.addEventListener("resize",function(){$=null}),w.addEventListener("load",function(){requestAnimationFrame(function(){Ue=!0,$t(),er()})});var Mt=0,Zt=[];function tr(e,t,a,r,o){be(),Mt=setTimeout(function(){ar(e,t,a,r,o)},300)}function be(){Mt&&(clearTimeout(Mt),Mt=0)}function ar(e,t,a,r,o,s){h.text=e,h.lines=r||null,h.origin=o||"",h.mode=s||"replace",wt(),I.classList.remove("hidden"),I.classList.toggle("popup-bar",!!(t&&t.width)),_.value="",vn(a),requestAnimationFrame(function(){mn(t),t&&t.focus&&_.focus()})}function mn(e){var t=8,a=10,r=e||{},o=v?t+48:t;if(I.style.width=r.width?r.width+"px":"",r.width){I.style.left=Math.max(t,r.startLeft||0)+"px",I.style.top=Math.max(o,Math.min(r.startTop||0,window.innerHeight-(I.offsetHeight||44)-t))+"px";return}var s=I.offsetWidth||300,u=I.offsetHeight||44,c=(r.startTop||0)-a-u,d=c>=o,m=d?c:(r.endBottom||0)+a,x=d?r.startLeft||0:r.endLeft!=null?r.endLeft:r.startLeft||0;I.style.left=Math.max(t,Math.min(x,window.innerWidth-s-t))+"px",I.style.top=Math.max(o,Math.min(m,window.innerHeight-u-t))+"px"}function vn(e){rr(),(e||[]).forEach(function(t){var a=document.createElement("div");a.className="fake-sel",a.style.top=t.top+"px",a.style.left=t.left+"px",a.style.width=t.width+"px",a.style.height=t.height+"px",document.body.appendChild(a),Zt.push(a)})}function rr(){Zt.forEach(function(e){e.remove()}),Zt=[]}var gn=navigator.platform||navigator.userAgent||"",Qt=/Mac|iPhone|iPod|iPad/.test(gn);function hn(e){return String(e.key).toLowerCase()!=="e"||e.shiftKey?!1:Qt?e.metaKey&&e.ctrlKey&&!e.altKey:e.ctrlKey&&e.altKey&&!e.metaKey}(function(){if(Sa){var t=Qt?["\u2318","\u2303","E"]:["Ctrl","Alt","E"],a=Qt?"":"+";Sa.innerHTML=t.map(function(r){return"<kbd>"+r+"</kbd>"}).join(a?'<span class="popup-shortcut-sep">'+a+"</span>":"")}})();function F(e){var t=e===!0&&h.origin==="editor"&&k==="edit";be(),I.classList.add("hidden"),I.classList.remove("popup-bar"),I.classList.remove("focused"),I.style.width="",h.text="",h.lines=null,h.origin="",h.mode="replace",rr(),t&&requestAnimationFrame(function(){p.focus()})}wa.onclick=or;var nr=0;_.addEventListener("compositionend",function(){nr=Date.now()});function yn(e){return e.isComposing||e.keyCode===229?!0:Date.now()-nr<100}_.addEventListener("keydown",function(e){if(e.key==="Enter"){if(yn(e))return;or()}e.key==="Escape"&&F(!0)}),_.addEventListener("focus",function(){I.classList.add("focused")}),_.addEventListener("blur",function(){requestAnimationFrame(function(){document.activeElement!==wa&&I.classList.remove("focused")})}),document.addEventListener("keydown",function(e){e.key==="Escape"&&!I.classList.contains("hidden")&&F(!0)}),document.addEventListener("keydown",function(e){hn(e)&&(I.classList.contains("hidden")||(e.preventDefault(),_.focus(),_.select()))}),document.addEventListener("mousedown",function(e){I.contains(e.target)||(be(),F())}),window.addEventListener("resize",F);function bn(){if(!h.lines)return n("annotate.lineUnknown");var e=h.lines.start,t=h.lines.end;return e===t?n("annotate.lineSingle",{a:e}):n("annotate.lineRange",{a:e,b:t})}function wn(){return h.lines?h.lines.start+"-"+h.lines.end:n("annotate.lineCompactUnknown")}async function or(){var e=_.value.trim(),t=h.mode==="continue",a=h.mode==="annotate-line";if(!(!h.text&&!t&&!a||!i)){if(P&&f){var r=await da();if(!r){l(n("status.saveFailedNoReturn"),!0);return}}if(v){if(!f||!i.postMessage){l(n("status.noSourceFile"),!0);return}i.postMessage({type:"requestRewrite",path:f,selectedText:h.text,requirement:e,startLine:h.lines&&h.lines.start,endLine:h.lines&&h.lines.end,rewriteMode:t?"continue":"replace"}),F(!0),l(n(t?"appview.continuing":"appview.rewriting"));return}if(!i.composer||!h.text&&!a){F(!0);return}try{await i.composer.addContexts([{type:"annotation",label:(W||"Markdown")+":"+wn(),note:e||void 0,promptText:n("annotate.promptText",{lineLabel:bn(),requirement:e?n("annotate.requirementWith",{comment:e}):n("annotate.requirementDefault"),text:h.text||n("annotate.emptyLine"),path:f||n("annotate.pathMissing")}),reminder:n("annotate.reminder")}]),F(!0),l(n("annotate.added"))}catch(o){l(String(o),!0)}}}function Sn(){var e=p.getSelection();if(!e)return!1;var t=e.text.trim();if(!t)return!1;var a=Za(p.getValue(),e.start,e.end);return tr(t,{startTop:e.startRect.top,startLeft:e.startRect.left,endBottom:e.rect.bottom,endLeft:e.rect.left},null,a,"editor"),!0}function ir(){te&&Sn()}function kn(e){if(!A()||!e)return!1;be();var t=Se.querySelector(".cm-line")||Se.querySelector(".cm-content"),a=(t||Se).getBoundingClientRect();return ar("",{startTop:e.rect.top,startLeft:a.left,width:Math.max(240,a.width),focus:!0},null,{start:e.line,end:e.line},"editor",v?"continue":"annotate-line"),!0}Se.addEventListener("mouseup",ir),Se.addEventListener("keyup",function(e){e.shiftKey&&ir()});var P=!1,$e=0,oe=null,ea=!1,Fe=!1,ta="",aa=null;function xn(e){ta=e,aa=g,i.postMessage({type:"saveDraft",path:e,markdown:g,base:T})}function sr(){!f||!i||!i.postMessage||ta===f&&aa===g||xn(f)}function ra(){ta="",aa=null}function na(e){ra(),e&&i&&i.postMessage&&i.postMessage({type:"discardDraft",path:e})}function Te(e,t){P=e,je&&(clearTimeout(je),je=0),Fe=!P&&!!t,b(),!P&&t&&(je=setTimeout(function(){je=0,P||(Fe=!1,b())},3e3))}async function lr(e){if(oe)return cr(),l("\u8BF7\u5148\u5904\u7406 AI \u5199\u56DE\u4E0E\u672C\u5730\u7F16\u8F91\u7684\u51B2\u7A81\u3002",!0),!1;if(J&&J.createWritable)try{var t=await J.createWritable();return await t.write(e),await t.close(),yt=(await J.getFile()).lastModified,T=e,Te(g!==e,g===e),l(n(g===e?"status.saved":"status.savedWithNewChanges")),ra(),!0}catch(r){return l(n("status.saveFailed",{err:String(r)}),!0),!1}if(f){var a=++Oa;return l(n("status.saving")),zt[a]=e,i.postMessage({type:"saveMarkdown",path:f,markdown:e,requestId:a}),new Promise(function(r){Ie[a]=r})}return l(n("status.noSourceFile"),!0),!1}document.addEventListener("keydown",function(e){var t=e.metaKey||e.ctrlKey;if(t&&(e.key==="s"||e.key==="S")){e.preventDefault(),ca();return}t&&(e.key==="p"||e.key==="P")&&(e.preventDefault(),Ke(k==="edit"?"preview":"edit"))});function ur(){Le&&(clearInterval(Le),Le=0),J=null}var oa=null;function Ze(e,t,a,r,o,s){if(!r&&P&&T!==null&&e!==T)return oe={markdown:e,name:t,path:a,diskBaseline:o},l(n("status.externalUpdateSkipped"),!0),cr(),!1;var u=T!==null&&(!a||!f||a===f);return u||(te=!0),g=e,ze=t,a&&(f=a),W=fn(a||f)||t||"Markdown",T=typeof o=="string"?o:g,oa=u?p.applyExternalValue(g):null,oa||p.setValue(g),Te(!1),za(W),s||ye(),Xe(),Ae(),(v||k==="preview")&&G(),!0}async function cr(){if(!(ea||!oe||!P)){var e=oe,t=T;if(g===t){oe=null,Ze(e.markdown,e.name,e.path,!0,e.diskBaseline);return}if(e.markdown===t){oe=null;return}ea=!0;var a=await jn();if(ea=!1,oe===e){if(a==="later"){l("AI \u5199\u56DE\u5DF2\u4FDD\u7559\u5728\u78C1\u76D8\uFF1B\u53EF\u7EE7\u7EED\u7F16\u8F91\u540E\u518D\u5904\u7406\u3002");return}if(oe=null,a==="remote"){na(f),Ze(e.markdown,e.name,e.path,!0,e.diskBaseline);return}a==="local"&&(T=typeof e.diskBaseline=="string"?e.diskBaseline:e.markdown,sr(),l("\u5DF2\u4FDD\u7559\u672C\u5730\u7F16\u8F91\uFF1BAI \u5199\u56DE\u7248\u672C\u4ECD\u5728\u78C1\u76D8\u4E0A\u3002"))}}}async function dr(e){ze=e.name,yt=e.lastModified,typeof e.path=="string"&&e.path?(f=e.path,i&&i.postMessage({type:"watchPath",path:f})):f="",Ze(await e.text(),ze,f,!0)}function En(){J&&(Le&&clearInterval(Le),Le=setInterval(async function(){if(!(Ut||!J)){Ut=!0;try{var e=await J.getFile();if(e.lastModified!==yt){yt=e.lastModified;var t=await e.text();t!==T&&Ze(t,ze,f)&&l(n("status.externalUpdateApplied"))}}catch{}Ut=!1}},800))}var Y=!1,Qe=0;function et(){Qe&&(clearTimeout(Qe),Qe=0)}function Mn(){et(),Qe=setTimeout(function(){Qe=0,Y&&(Y=!1,He=!1,b(),l(n("status.pickerTimeout"),!0))},2e4)}async function ia(){if(P){var e=await wr(n("confirm.message",{file:W||n("common.markdownDocDefault")}));if(e==="cancel")return;if(e==="save"){var t=await da();if(!t){l(n("status.saveFailedNoReturn"),!0);return}}else e==="discard"&&na(f)}if(ur(),He&&i&&i.postMessage){if(Y){et(),He=!1,Y=!1,b(),await pr();return}Y=!0,Mn(),b(),l(n("status.openingPicker")),i.postMessage({type:"requestOpen"});return}await pr()}async function pr(){if("showOpenFilePicker"in window)try{var e=await window.showOpenFilePicker({types:[{description:"Markdown",accept:{"text/markdown":[".md",".markdown"]}}],multiple:!1});J=e[0],await dr(await J.getFile()),En();return}catch(a){if(a&&a.name==="AbortError")return}var t=document.createElement("input");t.type="file",t.accept=".md,.markdown,text/markdown",t.onchange=function(){var a=t.files&&t.files[0];a&&dr(a).catch(function(r){l(String(r),!0)})},t.click()}function In(){window.focus(),document.body.tabIndex=-1;try{document.body.focus({preventScroll:!0})}catch{document.body.focus()}}async function Ln(e){for(var t=0;t<e;t++){if(In(),await new Promise(function(a){requestAnimationFrame(function(){requestAnimationFrame(a)})}),document.hasFocus())return!0;await new Promise(function(a){setTimeout(a,40)})}return document.hasFocus()}function fr(e){var t=Array.from(new Set(e.match(/finch-file:\/\/local\?path=[^\s)"']+/g)||[]));return!t.length||!i||!i.postMessage?Promise.resolve(e):new Promise(function(a,r){var o=++Pr;ve[o]={resolve:a,reject:r,sourceHtml:e},setTimeout(function(){ve[o]&&(delete ve[o],r(new Error(n("status.clipboardPrepareTimeout"))))},15e3),i.postMessage({type:"readClipboardImages",urls:t,requestId:o})})}function An(e){var t=new DOMParser().parseFromString(e,"text/html");function a(r){return r&&r.tagName==="P"&&!r.textContent.trim()&&!r.querySelector("img,video,iframe,table")}return Array.from(t.querySelectorAll("figure.figure-image")).forEach(function(r){var o=r.previousElementSibling,s=r.nextElementSibling;a(o)&&o.remove(),a(s)&&s.remove()}),t.body.innerHTML}async function mr(e,t){if(document.hasFocus()||await Ln(5),window.ClipboardItem&&navigator.clipboard&&navigator.clipboard.write)try{return await navigator.clipboard.write([new ClipboardItem({"text/html":Promise.resolve(e).then(function(r){return new Blob([r],{type:"text/html"})}),"text/plain":new Blob([t],{type:"text/plain"})})]),"rich"}catch{}var a=await Promise.resolve(e);return Cn(a)?"rich":Dn(t)?"plain":"none"}function Cn(e){var t=document.createElement("div");t.contentEditable="true",t.style.position="fixed",t.style.left="-9999px",t.style.top="0",t.innerHTML=e,document.body.appendChild(t);var a=document.createRange();a.selectNodeContents(t);var r=window.getSelection();r.removeAllRanges(),r.addRange(a);var o=!1;try{o=document.execCommand("copy")}catch{o=!1}return r.removeAllRanges(),t.remove(),o}function Dn(e){var t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.left="-9999px",t.style.top="0",document.body.appendChild(t),t.focus(),t.select();var a=!1;try{a=document.execCommand("copy")}catch{a=!1}return t.remove(),a}async function Fn(){if(!z){l(n("status.pleaseOpenArticle"),!0);return}try{var e=w.contentDocument&&w.contentDocument.body?w.contentDocument.body.innerText:z.replace(/<[^>]+>/g,""),t=await mr(fr(z),e);t==="none"&&(await new Promise(function(a){setTimeout(a,200)}),t=await mr(fr(z),e)),t==="rich"?l(n("status.copiedRich")):l(n(t==="plain"?"status.copiedPlainOnly":"status.copyFailed"),!0)}catch(a){l(n("status.richCopyFailed",{err:String(a)}),!0)}finally{k==="edit"&&requestAnimationFrame(function(){p.focus()})}}function Tn(){if(!Ue||!w.contentDocument)return null;var e=w.contentDocument.querySelector("#bm-md");if(!e)return null;var t=e.getBoundingClientRect();return{root:e,width:Math.ceil(t.width||e.scrollWidth),height:Math.ceil(t.height||e.scrollHeight)}}function sa(){var e=Tn();if(!e||!e.width||!e.height)return Promise.resolve(null);var t=2,a=e.root.cloneNode(!0);a.style.minHeight=e.height+"px",a.style.margin="0",a.style.boxSizing="border-box";var r;try{r=new XMLSerializer().serializeToString(a)}catch(u){return Promise.reject(new Error(n("status.serializeFailed",{err:String(u)})))}var o='<svg xmlns="http://www.w3.org/2000/svg" width="'+e.width+'" height="'+e.height+'"><foreignObject x="0" y="0" width="'+e.width+'" height="'+e.height+'">'+r+"</foreignObject></svg>",s="data:image/svg+xml;charset=utf-8,"+encodeURIComponent(o);return new Promise(function(u,c){var d=new Image;d.decoding="sync",d.onload=function(){try{var m=document.createElement("canvas");m.width=Math.round(e.width*t),m.height=Math.round(e.height*t);var x=m.getContext("2d");x.scale(t,t);var S="";try{S=w.contentWindow.getComputedStyle(e.root).backgroundColor}catch{S=""}S&&S!=="rgba(0, 0, 0, 0)"&&S!=="transparent"&&(x.fillStyle=S,x.fillRect(0,0,e.width,e.height)),x.drawImage(d,0,0,e.width,e.height),u({canvas:m,cssWidth:e.width,cssHeight:e.height})}catch(Q){c(Q)}},d.onerror=function(){c(new Error(n("status.imageConversionFailed")))},d.src=s})}function la(e,t,a){return new Promise(function(r,o){e.toBlob(function(s){s?r(s):o(new Error(n("status.imageGenFailed")))},t,a)})}function vr(e){for(var t="",a=32768,r=0;r<e.length;r+=a)t+=String.fromCharCode.apply(null,e.subarray(r,r+a));return btoa(t)}async function Pn(){if(!z){l(n("status.pleaseOpenArticle"),!0);return}if(!window.ClipboardItem||!navigator.clipboard||!navigator.clipboard.write){l(n("status.clipboardUnsupported"),!0);return}l(n("status.generatingImage"));var e=sa().then(function(a){if(!a)throw new Error(n("status.previewNotReady"));return la(a.canvas,"image/png")});try{await navigator.clipboard.write([new ClipboardItem({"image/png":e})]),l(n("status.imageCopied"));return}catch{try{var t=await e;await navigator.clipboard.write([new ClipboardItem({"image/png":t})]),l(n("status.imageCopied"));return}catch(r){l(n("status.copyImageFailed",{err:r&&r.message?r.message:String(r)}),!0)}}}async function On(){if(!z){l(n("status.pleaseOpenArticle"),!0);return}try{l(n("status.generatingImage"));var e=await sa();if(!e){l(n("status.exportImageFailedGeneric"),!0);return}var t=await la(e.canvas,"image/png"),a=await t.arrayBuffer(),r=vr(new Uint8Array(a));i&&i.postMessage&&i.postMessage({type:"exportFile",data:r,ext:"png",path:f,fileName:W,markdown:g})}catch(o){l(n("status.exportImageFailed",{err:String(o)}),!0)}}function Rn(e){for(var t=String(e);t.length<10;)t="0"+t;return t}function Z(e){for(var t=new Uint8Array(e.length),a=0;a<e.length;a++)t[a]=e.charCodeAt(a)&255;return t}function ua(e){for(var t=0,a=0;a<e.length;a++)t+=e[a].length;for(var r=new Uint8Array(t),o=0,a=0;a<e.length;a++)r.set(e[a],o),o+=e[a].length;return r}function Bn(e,t,a,r,o){var s=Z(`%PDF-1.4
|
|
14
|
+
`).length}}function pn(e,t){for(var a="",r=[],o=0;o<e.length;o++)/\s/.test(e[o])?a&&a[a.length-1]!==" "&&(a+=" ",r.push(t[o])):(a+=e[o],r.push(t[o]));return a.endsWith(" ")&&(a=a.slice(0,-1),r.pop()),{text:a,map:r}}function fn(e){var t="",a=[];function r(q,V){t+=q,a.push(V)}for(var o=0;o<e.length;){var s=o===0||e[o-1]===`
|
|
15
|
+
`;if(s){var l=/^[ \t]*(?:```|~~~)[^\n]*/.exec(e.slice(o));if(l){o+=l[0].length;continue}var u=/^[ \t]*(?:#{1,6}|>+|[-+*]|\d+[.)])[ \t]+/.exec(e.slice(o));if(u){o+=u[0].length;continue}}var d=/^!?\[([^\]]*)\]\((?:\\.|[^)])*\)/.exec(e.slice(o));if(d){for(var f=o+d[0].indexOf("[")+1,b=0;b<d[1].length;b++)/[*_~`]/.test(d[1][b])||r(d[1][b],f+b);o+=d[0].length;continue}var v=/^<[^>]+>/.exec(e.slice(o));if(v){o+=v[0].length;continue}if(e[o]==="\\"&&o+1<e.length){r(e[o+1],o+1),o+=2;continue}if(/[*_~`]/.test(e[o])){o++;continue}r(e[o],o),o++}return pn(t,a)}function mn(e,t){var a=e.indexOf(t);if(a>=0)return{start:a,end:a+t.length};var r=fn(e),o=t.replace(/\s+/g," ").trim(),s=r.text.indexOf(o);if(s>=0)return{start:r.map[s],end:r.map[s+o.length-1]+1};if(o.length>=12){var l=o.slice(0,6),u=o.slice(-6),d=r.text.indexOf(l),f=r.text.indexOf(u,Math.max(0,d+l.length));if(d>=0&&f>=d)return{start:r.map[d],end:r.map[f+u.length-1]+1}}return null}function vn(e){return String(e||"").split(/[\\/]/).pop()||""}function er(){var e=y.contentDocument;if(!e||e.__bound)return;e.__bound=!0;function t(){if(te){var a=y.contentWindow,r=a.getSelection(),o=r.toString().trim();if(!(!o||!r.rangeCount)){var s=r.getRangeAt(0),l=Array.from(s.getClientRects()),u=y.getBoundingClientRect(),d=l.map(function(V){return{top:u.top+V.top,left:u.left+V.left,width:V.width,height:V.height}}),f=l[0]||s.getBoundingClientRect(),b=l[l.length-1]||f,v=mn(h,o),q=v?Qa(h,v.start,v.end):null;ar(o,{startTop:u.top+f.top,startLeft:u.left+f.left,endBottom:u.top+b.bottom,endLeft:u.left+b.left},d,q,"preview")}}}e.addEventListener("mouseup",t),e.addEventListener("mousedown",function(){be(),F()}),e.addEventListener("keyup",t),e.addEventListener("keydown",function(a){(a.metaKey||a.ctrlKey)&&(a.key==="p"||a.key==="P")&&(a.preventDefault(),Ke("edit"))}),e.addEventListener("scroll",function(){be(),F()},!0),y.contentWindow.addEventListener("scroll",function(){be(),F()})}y.onload=function(){Ie=!0,er(),$t()};function tr(){p&&p.scrollDOM&&!p.scrollDOM.__scrollSyncBound&&(p.scrollDOM.__scrollSyncBound=!0,p.scrollDOM.addEventListener("scroll",on,{passive:!0}));var e=y.contentDocument;if(e&&!e.__scrollSyncBound){e.__scrollSyncBound=!0;var t=e.scrollingElement||e.documentElement;t&&t.addEventListener("scroll",Ja,{passive:!0}),e.defaultView&&e.defaultView.addEventListener("scroll",Ja,{passive:!0})}}tr(),window.addEventListener("resize",function(){Z=null}),y.addEventListener("load",function(){requestAnimationFrame(function(){Ie=!0,$t(),tr(),$a()})});var Mt=0,Zt=[];function ar(e,t,a,r,o){be(),Mt=setTimeout(function(){rr(e,t,a,r,o)},300)}function be(){Mt&&(clearTimeout(Mt),Mt=0)}function rr(e,t,a,r,o,s){w.text=e,w.lines=r||null,w.origin=o||"",w.mode=s||"replace",wt(),I.classList.remove("hidden"),I.classList.toggle("popup-bar",!!(t&&t.width)),_.value="",hn(a),requestAnimationFrame(function(){gn(t),t&&t.focus&&_.focus()})}function gn(e){var t=8,a=10,r=e||{},o=g?t+48:t;if(I.style.width=r.width?r.width+"px":"",r.width){I.style.left=Math.max(t,r.startLeft||0)+"px",I.style.top=Math.max(o,Math.min(r.startTop||0,window.innerHeight-(I.offsetHeight||44)-t))+"px";return}var s=I.offsetWidth||300,l=I.offsetHeight||44,u=(r.startTop||0)-a-l,d=u>=o,f=d?u:(r.endBottom||0)+a,b=d?r.startLeft||0:r.endLeft!=null?r.endLeft:r.startLeft||0;I.style.left=Math.max(t,Math.min(b,window.innerWidth-s-t))+"px",I.style.top=Math.max(o,Math.min(f,window.innerHeight-l-t))+"px"}function hn(e){nr(),(e||[]).forEach(function(t){var a=document.createElement("div");a.className="fake-sel",a.style.top=t.top+"px",a.style.left=t.left+"px",a.style.width=t.width+"px",a.style.height=t.height+"px",document.body.appendChild(a),Zt.push(a)})}function nr(){Zt.forEach(function(e){e.remove()}),Zt=[]}var yn=navigator.platform||navigator.userAgent||"",Qt=/Mac|iPhone|iPod|iPad/.test(yn);function bn(e){return String(e.key).toLowerCase()!=="e"||e.shiftKey?!1:Qt?e.metaKey&&e.ctrlKey&&!e.altKey:e.ctrlKey&&e.altKey&&!e.metaKey}(function(){if(Sa){var t=Qt?["\u2318","\u2303","E"]:["Ctrl","Alt","E"],a=Qt?"":"+";Sa.innerHTML=t.map(function(r){return"<kbd>"+r+"</kbd>"}).join(a?'<span class="popup-shortcut-sep">'+a+"</span>":"")}})();function F(e){var t=e===!0&&w.origin==="editor"&&x==="edit";be(),I.classList.add("hidden"),I.classList.remove("popup-bar"),I.classList.remove("focused"),I.style.width="",w.text="",w.lines=null,w.origin="",w.mode="replace",nr(),t&&requestAnimationFrame(function(){p.focus()})}wa.onclick=ir;var or=0;_.addEventListener("compositionend",function(){or=Date.now()});function wn(e){return e.isComposing||e.keyCode===229?!0:Date.now()-or<100}_.addEventListener("keydown",function(e){if(e.key==="Enter"){if(wn(e))return;ir()}e.key==="Escape"&&F(!0)}),_.addEventListener("focus",function(){I.classList.add("focused")}),_.addEventListener("blur",function(){requestAnimationFrame(function(){document.activeElement!==wa&&I.classList.remove("focused")})}),document.addEventListener("keydown",function(e){e.key==="Escape"&&!I.classList.contains("hidden")&&F(!0)}),document.addEventListener("keydown",function(e){bn(e)&&(I.classList.contains("hidden")||(e.preventDefault(),_.focus(),_.select()))}),document.addEventListener("mousedown",function(e){I.contains(e.target)||(be(),F())}),window.addEventListener("resize",F);function Sn(){if(!w.lines)return n("annotate.lineUnknown");var e=w.lines.start,t=w.lines.end;return e===t?n("annotate.lineSingle",{a:e}):n("annotate.lineRange",{a:e,b:t})}function kn(){return w.lines?w.lines.start+"-"+w.lines.end:n("annotate.lineCompactUnknown")}async function ir(){var e=_.value.trim(),t=w.mode==="continue",a=w.mode==="annotate-line";if(!(!w.text&&!t&&!a||!i)){if(P&&m){var r=await da();if(!r){c(n("status.saveFailedNoReturn"),!0);return}}if(g){if(!m||!i.postMessage){c(n("status.noSourceFile"),!0);return}i.postMessage({type:"requestRewrite",path:m,selectedText:w.text,requirement:e,startLine:w.lines&&w.lines.start,endLine:w.lines&&w.lines.end,rewriteMode:t?"continue":"replace"}),F(!0),c(n(t?"appview.continuing":"appview.rewriting"));return}if(!i.composer||!w.text&&!a){F(!0);return}try{await i.composer.addContexts([{type:"annotation",label:(U||"Markdown")+":"+kn(),note:e||void 0,promptText:n("annotate.promptText",{lineLabel:Sn(),requirement:e?n("annotate.requirementWith",{comment:e}):n("annotate.requirementDefault"),text:w.text||n("annotate.emptyLine"),path:m||n("annotate.pathMissing")}),reminder:n("annotate.reminder")}]),F(!0),c(n("annotate.added"))}catch(o){c(String(o),!0)}}}function xn(){var e=p.getSelection();if(!e)return!1;var t=e.text.trim();if(!t)return!1;var a=Qa(p.getValue(),e.start,e.end);return ar(t,{startTop:e.startRect.top,startLeft:e.startRect.left,endBottom:e.rect.bottom,endLeft:e.rect.left},null,a,"editor"),!0}function sr(){te&&xn()}function En(e){if(!C()||!e)return!1;be();var t=Se.querySelector(".cm-line")||Se.querySelector(".cm-content"),a=(t||Se).getBoundingClientRect();return rr("",{startTop:e.rect.top,startLeft:a.left,width:Math.max(240,a.width),focus:!0},null,{start:e.line,end:e.line},"editor",g?"continue":"annotate-line"),!0}Se.addEventListener("mouseup",sr),Se.addEventListener("keyup",function(e){e.shiftKey&&sr()});var P=!1,$e=0,oe=null,ea=!1,Te=!1,ta="",aa=null;function Mn(e){ta=e,aa=h,i.postMessage({type:"saveDraft",path:e,markdown:h,base:T})}function lr(){!m||!i||!i.postMessage||ta===m&&aa===h||Mn(m)}function ra(){ta="",aa=null}function na(e){ra(),e&&i&&i.postMessage&&i.postMessage({type:"discardDraft",path:e})}function Pe(e,t){P=e,_e&&(clearTimeout(_e),_e=0),Te=!P&&!!t,k(),!P&&t&&(_e=setTimeout(function(){_e=0,P||(Te=!1,k())},3e3))}async function cr(e){if(oe)return dr(),c("\u8BF7\u5148\u5904\u7406 AI \u5199\u56DE\u4E0E\u672C\u5730\u7F16\u8F91\u7684\u51B2\u7A81\u3002",!0),!1;if($&&$.createWritable)try{var t=await $.createWritable();return await t.write(e),await t.close(),yt=(await $.getFile()).lastModified,T=e,Pe(h!==e,h===e),c(n(h===e?"status.saved":"status.savedWithNewChanges")),ra(),!0}catch(r){return c(n("status.saveFailed",{err:String(r)}),!0),!1}if(m){var a=++Oa;return c(n("status.saving")),zt[a]=e,i.postMessage({type:"saveMarkdown",path:m,markdown:e,requestId:a}),new Promise(function(r){Le[a]=r})}return c(n("status.noSourceFile"),!0),!1}document.addEventListener("keydown",function(e){var t=e.metaKey||e.ctrlKey;if(t&&(e.key==="s"||e.key==="S")){e.preventDefault(),ua();return}t&&(e.key==="p"||e.key==="P")&&(e.preventDefault(),Ke(x==="edit"?"preview":"edit"))});function ur(){Ce&&(clearInterval(Ce),Ce=0),$=null}var oa=null;function Ze(e,t,a,r,o,s){if(!r&&P&&T!==null&&e!==T)return oe={markdown:e,name:t,path:a,diskBaseline:o},c(n("status.externalUpdateSkipped"),!0),dr(),!1;var l=T!==null&&(!a||!m||a===m);return l||(te=!0),h=e,Ue=t,a&&(m=a),U=vn(a||m)||t||"Markdown",T=typeof o=="string"?o:h,oa=l?p.applyExternalValue(h):null,oa||p.setValue(h),Pe(!1),za(U),s||ye(),Ye(),Ae(),(g||x==="preview")&&X(),!0}async function dr(){if(!(ea||!oe||!P)){var e=oe,t=T;if(h===t){oe=null,Ze(e.markdown,e.name,e.path,!0,e.diskBaseline);return}if(e.markdown===t){oe=null;return}ea=!0;var a=await Gn();if(ea=!1,oe===e){if(a==="later"){c("AI \u5199\u56DE\u5DF2\u4FDD\u7559\u5728\u78C1\u76D8\uFF1B\u53EF\u7EE7\u7EED\u7F16\u8F91\u540E\u518D\u5904\u7406\u3002");return}if(oe=null,a==="remote"){na(m),Ze(e.markdown,e.name,e.path,!0,e.diskBaseline);return}a==="local"&&(T=typeof e.diskBaseline=="string"?e.diskBaseline:e.markdown,lr(),c("\u5DF2\u4FDD\u7559\u672C\u5730\u7F16\u8F91\uFF1BAI \u5199\u56DE\u7248\u672C\u4ECD\u5728\u78C1\u76D8\u4E0A\u3002"))}}}async function pr(e){Ue=e.name,yt=e.lastModified,typeof e.path=="string"&&e.path?(m=e.path,i&&i.postMessage({type:"watchPath",path:m})):m="",Ze(await e.text(),Ue,m,!0)}function In(){$&&(Ce&&clearInterval(Ce),Ce=setInterval(async function(){if(!(Ut||!$)){Ut=!0;try{var e=await $.getFile();if(e.lastModified!==yt){yt=e.lastModified;var t=await e.text();t!==T&&Ze(t,Ue,m)&&c(n("status.externalUpdateApplied"))}}catch{}Ut=!1}},800))}var Y=!1,Qe=0;function et(){Qe&&(clearTimeout(Qe),Qe=0)}function Ln(){et(),Qe=setTimeout(function(){Qe=0,Y&&(Y=!1,We=!1,k(),c(n("status.pickerTimeout"),!0))},2e4)}async function ia(){if(P){var e=await Sr(n("confirm.message",{file:U||n("common.markdownDocDefault")}));if(e==="cancel")return;if(e==="save"){var t=await da();if(!t){c(n("status.saveFailedNoReturn"),!0);return}}else e==="discard"&&na(m)}if(ur(),We&&i&&i.postMessage){if(Y){et(),We=!1,Y=!1,k(),await fr();return}Y=!0,Ln(),k(),c(n("status.openingPicker")),i.postMessage({type:"requestOpen"});return}await fr()}async function fr(){if("showOpenFilePicker"in window)try{var e=await window.showOpenFilePicker({types:[{description:"Markdown",accept:{"text/markdown":[".md",".markdown"]}}],multiple:!1});$=e[0],await pr(await $.getFile()),In();return}catch(a){if(a&&a.name==="AbortError")return}var t=document.createElement("input");t.type="file",t.accept=".md,.markdown,text/markdown",t.onchange=function(){var a=t.files&&t.files[0];a&&pr(a).catch(function(r){c(String(r),!0)})},t.click()}function Cn(){window.focus(),document.body.tabIndex=-1;try{document.body.focus({preventScroll:!0})}catch{document.body.focus()}}async function An(e){for(var t=0;t<e;t++){if(Cn(),await new Promise(function(a){requestAnimationFrame(function(){requestAnimationFrame(a)})}),document.hasFocus())return!0;await new Promise(function(a){setTimeout(a,40)})}return document.hasFocus()}function mr(e){var t=Array.from(new Set(e.match(/finch-file:\/\/local\?path=[^\s)"']+/g)||[]));return!t.length||!i||!i.postMessage?Promise.resolve(e):new Promise(function(a,r){var o=++Or;ve[o]={resolve:a,reject:r,sourceHtml:e},setTimeout(function(){ve[o]&&(delete ve[o],r(new Error(n("status.clipboardPrepareTimeout"))))},15e3),i.postMessage({type:"readClipboardImages",urls:t,requestId:o})})}function Dn(e){var t=new DOMParser().parseFromString(e,"text/html");function a(r){return r&&r.tagName==="P"&&!r.textContent.trim()&&!r.querySelector("img,video,iframe,table")}return Array.from(t.querySelectorAll("figure.figure-image")).forEach(function(r){var o=r.previousElementSibling,s=r.nextElementSibling;a(o)&&o.remove(),a(s)&&s.remove()}),t.body.innerHTML}async function vr(e,t){if(document.hasFocus()||await An(5),window.ClipboardItem&&navigator.clipboard&&navigator.clipboard.write)try{return await navigator.clipboard.write([new ClipboardItem({"text/html":Promise.resolve(e).then(function(r){return new Blob([r],{type:"text/html"})}),"text/plain":new Blob([t],{type:"text/plain"})})]),"rich"}catch{}var a=await Promise.resolve(e);return Fn(a)?"rich":Tn(t)?"plain":"none"}function Fn(e){var t=document.createElement("div");t.contentEditable="true",t.style.position="fixed",t.style.left="-9999px",t.style.top="0",t.innerHTML=e,document.body.appendChild(t);var a=document.createRange();a.selectNodeContents(t);var r=window.getSelection();r.removeAllRanges(),r.addRange(a);var o=!1;try{o=document.execCommand("copy")}catch{o=!1}return r.removeAllRanges(),t.remove(),o}function Tn(e){var t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.left="-9999px",t.style.top="0",document.body.appendChild(t),t.focus(),t.select();var a=!1;try{a=document.execCommand("copy")}catch{a=!1}return t.remove(),a}async function Pn(){if(!N){c(n("status.pleaseOpenArticle"),!0);return}try{var e=y.contentDocument&&y.contentDocument.body?y.contentDocument.body.innerText:N.replace(/<[^>]+>/g,""),t=await vr(mr(N),e);t==="none"&&(await new Promise(function(a){setTimeout(a,200)}),t=await vr(mr(N),e)),t==="rich"?c(n("status.copiedRich")):c(n(t==="plain"?"status.copiedPlainOnly":"status.copyFailed"),!0)}catch(a){c(n("status.richCopyFailed",{err:String(a)}),!0)}finally{x==="edit"&&requestAnimationFrame(function(){p.focus()})}}function On(){if(!Ie||!y.contentDocument)return null;var e=y.contentDocument.querySelector("#bm-md");if(!e)return null;var t=e.getBoundingClientRect();return{root:e,width:Math.ceil(t.width||e.scrollWidth),height:Math.ceil(t.height||e.scrollHeight)}}function sa(){var e=On();if(!e||!e.width||!e.height)return Promise.resolve(null);var t=2,a=e.root.cloneNode(!0);a.style.minHeight=e.height+"px",a.style.margin="0",a.style.boxSizing="border-box";var r;try{r=new XMLSerializer().serializeToString(a)}catch(l){return Promise.reject(new Error(n("status.serializeFailed",{err:String(l)})))}var o='<svg xmlns="http://www.w3.org/2000/svg" width="'+e.width+'" height="'+e.height+'"><foreignObject x="0" y="0" width="'+e.width+'" height="'+e.height+'">'+r+"</foreignObject></svg>",s="data:image/svg+xml;charset=utf-8,"+encodeURIComponent(o);return new Promise(function(l,u){var d=new Image;d.decoding="sync",d.onload=function(){try{var f=document.createElement("canvas");f.width=Math.round(e.width*t),f.height=Math.round(e.height*t);var b=f.getContext("2d");b.scale(t,t);var v="";try{v=y.contentWindow.getComputedStyle(e.root).backgroundColor}catch{v=""}v&&v!=="rgba(0, 0, 0, 0)"&&v!=="transparent"&&(b.fillStyle=v,b.fillRect(0,0,e.width,e.height)),b.drawImage(d,0,0,e.width,e.height),l({canvas:f,cssWidth:e.width,cssHeight:e.height})}catch(q){u(q)}},d.onerror=function(){u(new Error(n("status.imageConversionFailed")))},d.src=s})}function la(e,t,a){return new Promise(function(r,o){e.toBlob(function(s){s?r(s):o(new Error(n("status.imageGenFailed")))},t,a)})}function gr(e){for(var t="",a=32768,r=0;r<e.length;r+=a)t+=String.fromCharCode.apply(null,e.subarray(r,r+a));return btoa(t)}async function Rn(){if(!N){c(n("status.pleaseOpenArticle"),!0);return}if(!window.ClipboardItem||!navigator.clipboard||!navigator.clipboard.write){c(n("status.clipboardUnsupported"),!0);return}c(n("status.generatingImage"));var e=sa().then(function(a){if(!a)throw new Error(n("status.previewNotReady"));return la(a.canvas,"image/png")});try{await navigator.clipboard.write([new ClipboardItem({"image/png":e})]),c(n("status.imageCopied"));return}catch{try{var t=await e;await navigator.clipboard.write([new ClipboardItem({"image/png":t})]),c(n("status.imageCopied"));return}catch(r){c(n("status.copyImageFailed",{err:r&&r.message?r.message:String(r)}),!0)}}}async function Bn(){if(!N){c(n("status.pleaseOpenArticle"),!0);return}try{c(n("status.generatingImage"));var e=await sa();if(!e){c(n("status.exportImageFailedGeneric"),!0);return}var t=await la(e.canvas,"image/png"),a=await t.arrayBuffer(),r=gr(new Uint8Array(a));i&&i.postMessage&&i.postMessage({type:"exportFile",data:r,ext:"png",path:m,fileName:U,markdown:h})}catch(o){c(n("status.exportImageFailed",{err:String(o)}),!0)}}function Nn(e){for(var t=String(e);t.length<10;)t="0"+t;return t}function Q(e){for(var t=new Uint8Array(e.length),a=0;a<e.length;a++)t[a]=e.charCodeAt(a)&255;return t}function ca(e){for(var t=0,a=0;a<e.length;a++)t+=e[a].length;for(var r=new Uint8Array(t),o=0,a=0;a<e.length;a++)r.set(e[a],o),o+=e[a].length;return r}function qn(e,t,a,r,o){var s=Q(`%PDF-1.4
|
|
16
16
|
%\xE2\xE3\xCF\xD3
|
|
17
|
-
`),
|
|
17
|
+
`),l=[s],u=[0],d=s.length;function f(Ct){u.push(d),l.push(Ct),d+=Ct.length}f(Q(`1 0 obj
|
|
18
18
|
<< /Type /Catalog /Pages 2 0 R >>
|
|
19
19
|
endobj
|
|
20
|
-
`)),
|
|
20
|
+
`)),f(Q(`2 0 obj
|
|
21
21
|
<< /Type /Pages /Kids [3 0 R] /Count 1 >>
|
|
22
22
|
endobj
|
|
23
|
-
`)),
|
|
23
|
+
`)),f(Q(`3 0 obj
|
|
24
24
|
<< /Type /Page /Parent 2 0 R /MediaBox [0 0 `+r.toFixed(2)+" "+o.toFixed(2)+`] /Resources << /XObject << /Im0 4 0 R >> >> /Contents 5 0 R >>
|
|
25
25
|
endobj
|
|
26
|
-
`));var
|
|
26
|
+
`));var b=Q(`4 0 obj
|
|
27
27
|
<< /Type /XObject /Subtype /Image /Width `+t+" /Height "+a+" /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode /Length "+e.length+` >>
|
|
28
28
|
stream
|
|
29
|
-
`),
|
|
29
|
+
`),v=Q(`
|
|
30
30
|
endstream
|
|
31
31
|
endobj
|
|
32
|
-
`);
|
|
33
|
-
<< /Length `+
|
|
32
|
+
`);f(ca([b,e,v]));var q="q "+r.toFixed(2)+" 0 0 "+o.toFixed(2)+" 0 0 cm /Im0 Do Q",V=Q(q);f(ca([Q(`5 0 obj
|
|
33
|
+
<< /Length `+V.length+` >>
|
|
34
34
|
stream
|
|
35
|
-
`),
|
|
35
|
+
`),V,Q(`
|
|
36
36
|
endstream
|
|
37
37
|
endobj
|
|
38
38
|
`)]));for(var ee=d,ie=[`xref
|
|
39
39
|
0 6
|
|
40
40
|
0000000000 65535 f
|
|
41
|
-
`],ae=1;ae<=5;ae++)ie.push(
|
|
41
|
+
`],ae=1;ae<=5;ae++)ie.push(Nn(u[ae])+` 00000 n
|
|
42
42
|
`);var Lt=`trailer
|
|
43
43
|
<< /Size 6 /Root 1 0 R >>
|
|
44
44
|
startxref
|
|
45
45
|
`+ee+`
|
|
46
|
-
%%EOF`;return u.push(Z(ie.join("")+Lt)),ua(u)}async function Nn(){if(!z){l(n("status.pleaseOpenArticle"),!0);return}try{l(n("status.generatingPdf"));var e=await sa();if(!e){l(n("status.exportPdfFailedGeneric"),!0);return}var t=await la(e.canvas,"image/jpeg",.92),a=await t.arrayBuffer(),r=new Uint8Array(a),o=e.cssWidth*.75,s=e.cssHeight*.75,u=Bn(r,e.canvas.width,e.canvas.height,o,s),c=vr(u);i&&i.postMessage&&i.postMessage({type:"exportFile",data:c,ext:"pdf",path:f,fileName:W,markdown:g})}catch(d){l(n("status.exportPdfFailed",{err:String(d)}),!0)}}function tt(e,t){e&&e.addEventListener("click",function(a){a.preventDefault(),!e.disabled&&(e.disabled=!0,Promise.resolve().then(t).catch(function(r){l(String(r),!0)}).then(function(){e.disabled=!1}))})}tt(Ir,Fn),tt(Lr,Pn),tt(Ar,On),tt(Cr,Nn),tt(ke,qn);var gr="md-editor-actions-collapsed";(function(){var t=!1;try{t=localStorage.getItem(gr)==="1"}catch{}Pe&&Pe.classList.toggle("collapsed",t)})(),ka&&ka.addEventListener("click",function(e){e.preventDefault();var t=Pe.classList.toggle("collapsed");try{localStorage.setItem(gr,t?"1":"0")}catch{}});function ca(){lr(g)}function It(e){if(Fr=e,!!ke){ke.classList.toggle("loading",e),ke.disabled=e;var t=ke.querySelector(".ic-ai-style"),a=ke.querySelector(".ic-ai-style-loading");t&&(t.hidden=e),a&&(a.hidden=!e)}}function hr(){if(!g||!f||!i||!i.postMessage){l(n("status.pleaseOpenArticle"),!0);return}i.postMessage({type:"requestStyleSession",path:f,baseStyle:L}),It(!0),l(n("aiStyle.appViewDesigning"))}async function qn(){if(!g){l(n("status.pleaseOpenArticle"),!0);return}if(v||!i||!i.composer){hr();return}var e=L==="custom"?n("aiStyle.baseNoteCustom"):n("aiStyle.baseNoteOther",{style:L});try{await i.composer.addContexts([{type:"annotation",label:n("aiStyle.label",{file:W||n("common.markdownDocDefault")}),note:n("aiStyle.note"),promptText:n("aiStyle.promptText",{baseNote:e,path:f||n("aiStyle.pathMissing")}),reminder:n("aiStyle.reminder")}]),l(n("aiStyle.requested"))}catch{hr()}}function Hn(){return{fontSize:H,fontFamily:K,comfortWriting:R,style:L,customCss:L==="custom"?O:"",customStyleLabel:L==="custom"?Ee:""}}function we(){i&&i.postMessage&&i.postMessage({type:"saveWritingPreferences",preferences:Hn()})}function Wn(e){return!e||typeof e!="object"?!1:((e.fontSize===14||e.fontSize===16||e.fontSize===18)&&(H=e.fontSize),Me[e.fontFamily]&&(K=e.fontFamily),R=e.comfortWriting===!0,e.style==="custom"&&typeof e.customCss=="string"&&e.customCss?(L="custom",O=e.customCss,Ee=typeof e.customStyleLabel=="string"?e.customStyleLabel:""):["kami","bauhaus","blueprint","botanical","newsprint","retro","sketch","terminal"].indexOf(e.style)!==-1&&(L=e.style,O="",Ee=""),p.setFontSize(H),p.setFontFamily(Me[K]),p.setComfortWriting(R),!0)}function zn(e){L=e,we(),(v||k==="preview")&&G(),b()}function Un(e){if(!(e!==14&&e!==16&&e!==18)){H=e,p.setFontSize(e);try{localStorage.setItem("md-editor-font-size",String(e))}catch{}we(),b()}}function _n(e){if(Me[e]){K=e,p.setFontFamily(Me[e]);try{localStorage.setItem("md-editor-font-family",e)}catch{}we(),b()}}function yr(e){R=!!e,p.setComfortWriting(R);try{localStorage.setItem("md-editor-comfort-writing",R?"1":"0")}catch{}we(),b(),l(n(R?"status.comfortWrite":"status.comfortRead"))}function br(){B=!B,B&&te?(te=!1,F()):!B&&!te&&(te=!0),p.setFocusMode(B);try{localStorage.setItem("md-editor-focus-mode",B?"1":"0")}catch{}b(),l(n(B?"status.focusOn":"status.focusOff"))}var at=null;function rt(e){ce.hidden=!0;var t=at;at=null,t&&t(e)}function wr(e){return new Promise(function(t){at=t,xa.textContent=e,ce.hidden=!1,Oe.focus()})}async function jn(){xa.textContent="AI \u5DF2\u5199\u56DE\u6587\u4EF6\uFF0C\u4F46\u4F60\u4E5F\u6709\u672A\u4FDD\u5B58\u7F16\u8F91\u3002\u8BF7\u9009\u62E9\u4FDD\u7559\u672C\u5730\u5185\u5BB9\u6216\u91C7\u7528 AI \u7248\u672C\u3002",Rt.textContent="\u7A0D\u540E\u5904\u7406",Bt.textContent="\u4FDD\u7559\u672C\u5730",Oe.textContent="\u91C7\u7528 AI \u7248\u672C";var e=await new Promise(function(t){at=t,ce.hidden=!1,Oe.focus()});return Dt(ce),e==="save"?"remote":e==="discard"?"local":"later"}Rt&&Rt.addEventListener("click",function(){rt("cancel")}),Bt&&Bt.addEventListener("click",function(){rt("discard")}),Oe&&Oe.addEventListener("click",function(){rt("save")}),ce&&ce.addEventListener("click",function(e){e.target===ce&&rt("cancel")}),document.addEventListener("keydown",function(e){e.key==="Escape"&&at&&rt("cancel")});async function da(){return await lr(g)}function Vn(){ur(),ra(),F(),g="",ze="",W="",f="",T=null,fe=null,z="",te=!1,k="edit",p&&p.setValue(""),za(n("home.title")),ye(),$a(""),i&&i.postMessage&&i.postMessage({type:"goHome"}),Xe(),Ae(),Te(!1),l("")}async function nt(){if(P){var e=await wr(n("confirm.message",{file:W||n("common.markdownDocDefault")}));if(e==="cancel")return;if(i&&i.postMessage&&i.postMessage({type:"goHome"}),e==="save"){var t=await da();if(!t){l(n("status.saveFailedNoReturn"),!0);return}}else e==="discard"&&na(f)}Vn()}function Sr(e){if(i&&i.postMessage&&i.postMessage({type:"clientLog",message:"finch:menu received, itemId="+e}),e==="home"){nt();return}if(e==="open"){ia();return}if(e==="mode"){Ke(k==="edit"?"preview":"edit");return}if(e==="save"){ca();return}if(e==="reload"){G();return}if(e==="reveal"){f&&i&&i.postMessage&&i.postMessage({type:"openPath",path:f});return}if(e==="recentSession"){fe&&i&&i.navigation&&i.navigation.openSession&&i.navigation.openSession(fe);return}if(e&&e.indexOf("font-size:")===0){Un(Number(e.slice(10)));return}if(e&&e.indexOf("font-family:")===0){_n(e.slice(12));return}if(e==="comfort:read"){yr(!1);return}if(e==="comfort:write"){yr(!0);return}if(e==="focus"){br();return}if(e==="about"){Or();return}if(e&&e.indexOf("style:slot-use:")===0){Yn(+e.slice(15));return}if(e&&e.indexOf("style:slot-save:")===0){xr(+e.slice(16));return}if(e&&e.indexOf("style:")===0){zn(e.slice(6));return}}function pa(){[dt,pt,ft].forEach(function(e){e&&(e.hidden=!0)})}function Gn(e){if(e){var t=e.hidden;pa(),e.hidden=!t}}function fa(e,t){e&&e.addEventListener("click",function(a){a.stopPropagation(),Gn(t)}),t&&t.addEventListener("click",function(a){var r=a.target&&a.target.closest?a.target.closest("[data-app-action]"):null;if(!(r&&r.disabled)){var o=r&&r.getAttribute("data-app-action");o&&(Sr(o),pa())}})}Ma&&Ma.addEventListener("click",nt),ut&&ut.addEventListener("click",ia),re&&re.addEventListener("click",ca),Be&&Be.addEventListener("click",br),Re&&Re.addEventListener("click",function(){V=!V,document.body.classList.toggle("preview-hidden",!V),b(),V&&requestAnimationFrame(function(){p.layout(),G()})}),fa(ct,dt),fa(Nt,pt),fa(Dr,ft),document.addEventListener("click",pa);var ma=370,va=560,kr=480;ue&&ue.addEventListener("mousedown",function(e){e.preventDefault();var t=ue.parentElement;if(!t)return;var a=e.clientX,r=Ot?Ot.getBoundingClientRect().width:kr;ue.classList.add("active");var o=document.createElement("div");o.style.cssText="position:fixed;inset:0;z-index:9999;cursor:col-resize;",document.body.appendChild(o);function s(d){return Math.max(ma,Math.min(va,d))}function u(d){var m=d.clientX-a;t.style.setProperty("--preview-width",s(r-m)+"px")}function c(){ue.classList.remove("active"),o.remove(),window.removeEventListener("mousemove",u),window.removeEventListener("mouseup",c)}window.addEventListener("mousemove",u),window.addEventListener("mouseup",c)}),window.addEventListener("resize",function(){if(v){var e=ue&&ue.parentElement;if(e){var t=parseFloat(getComputedStyle(e).getPropertyValue("--preview-width"))||kr;(t>va||t<ma)&&e.style.setProperty("--preview-width",Math.max(ma,Math.min(va,t))+"px")}}});function Yn(e){var t=q[e];t&&(O=t.css,Ee=t.label,L="custom",we(),l(n("status.appliedStyleSlot",{label:t.label})),k==="preview"?G():Ke("preview"),b())}function xr(e){if(L!=="custom"||!O){l(n("status.needCustomStyleFirst"),!0);return}var t=Ee||n("common.customStyleDefault");i&&i.postMessage&&i.postMessage({type:"saveStyleSlot",slot:e,css:O,label:t,path:f})}function Xn(){E&&(clearTimeout(E),E=0),M.replaceChildren(document.createTextNode(n("aiStyle.applied")+" ")),M.className="status status-style-prompt";for(var e=0;e<3;e++)(function(t){var a=document.createElement("button");a.type="button",a.className="status-inline-btn",a.textContent=n("aiStyle.saveToSlot",{n:t+1});var r=q[t];r&&(a.title=r.label),a.addEventListener("click",function(){xr(t)}),M.appendChild(a)})(e);E=setTimeout(function(){E=0,M.replaceChildren(),M.className="status"},12e3)}i&&i.onMessage&&i.onMessage(function(e){if(!(!e||typeof e!="object")){if(e.type==="ready"){if(He=!!e.pickFileSupported,q=Array.isArray(e.styleSlots)?e.styleSlots:[null,null,null],Wn(e.writingPreferences)?v&&A()&&G():we(),e.libraryGroups&&typeof e.libraryGroups=="object"?(de=Array.isArray(e.libraryGroups.order)?e.libraryGroups.order.filter(function(se){return typeof se=="string"}):[],xe=e.libraryGroups.collapsed&&typeof e.libraryGroups.collapsed=="object"?e.libraryGroups.collapsed:{},qe.length&&Gt(qe)):(de.length||Object.keys(xe).length)&&Vt(),typeof e.locale=="string"&&e.locale){var t=/^zh/i.test(e.locale);t!==it&&(it=t,Dt(),wt())}e.assistantName&&(Ge=e.assistantName,wt()),Ba(),e.homeDir&&(he=e.homeDir,Nr()),b();return}if(e.type==="styleSlots"){q=Array.isArray(e.styleSlots)?e.styleSlots:[null,null,null],typeof e.savedSlot=="number"&&q[e.savedSlot]&&l(n("status.savedToSlot",{slot:e.savedSlot+1,label:q[e.savedSlot].label})),b();return}if(e.type==="clipboardImages"){var a=ve[e.requestId];if(a){delete ve[e.requestId];var r=a.sourceHtml,o=e.images&&typeof e.images=="object"?e.images:{};Object.keys(o).forEach(function(se){typeof o[se]=="string"&&(r=r.split(se).join(o[se]))}),a.resolve(An(r))}return}if(e.type==="clipboardImagesError"){var s=ve[e.requestId];s&&(delete ve[e.requestId],s.reject(new Error(e.message||n("status.clipboardPrepareFailedDefault"))));return}if(e.type==="pastedImage"){var u=me[e.requestId];u&&(delete me[e.requestId],u.resolve(e.url));return}if(e.type==="pasteImageError"){var c=me[e.requestId];c&&(delete me[e.requestId],c.reject(new Error(e.message||n("status.pasteImageFailedDefault")))),l(n("status.pasteImageFailed",{msg:e.message||""}));return}if(e.type==="finch:env"){v=e.view==="appView",v&&(i&&i.panel&&i.panel.setTitle&&i.panel.setTitle(n("home.title")).catch(function(){}),ye(),Gr()),v&&!Fa&&(Fa=!0,V=!1,document.body.classList.add("preview-hidden")),document.body.classList.toggle("app-view",v),Ea&&(Ea.hidden=!v),p.setAiHint(n("appview.hintSpace"),n("appview.hintSpaceCode"));var d=e.cwd||"",m=e.sessionId||"",x=e.spaceId||"";(d!==Ve||m!==_t||x!==jt||!bt)&&(Ve=d,_t=m,jt=x,bt=!0,kt([])),Ae(),ye(),b(),v&&A()&&G(),(!Ft.hidden||v)&&St();return}if(e.type==="recentDocuments"){if(!e.library&&(e.cwd||"")!==Ve)return;kt(e.documents),e.library&&Gt(e.documents);return}if(e.type==="status"){l(e.message);return}if(e.type==="rewriteSessionStarted"){N=e.sessionId&&e.turnId?{sessionId:e.sessionId,turnId:e.turnId}:null,p.setAiWorkingLines(Number(e.startLine)||0,Number(e.endLine)||0),ge(e.rewriteMode==="continue"?n("appview.continuing"):n("appview.rewriting"),!1,e.sessionId,0);return}if(e.type==="rewriteCancellationRequested"){N&&N.turnId===e.turnId&&(N.cancelling=!0),ge(n("appview.cancelling"),!1,e.sessionId,0);return}if(e.type==="rewriteSessionFinished"){N=null,p.setAiWorkingLines(0,0),ge(n("appview.rewriteDone"),!1,e.sessionId,5e3);return}if(e.type==="rewriteSessionFailed"){var S=N&&N.turnId===e.turnId&&N.cancelling;N=null,p.setAiWorkingLines(0,0),ge(S?n("appview.cancelled"):e.message||"Rewrite failed.",!S,e.sessionId,5e3);return}if(e.type==="styleSessionStarted"){It(!0),ge(n("aiStyle.appViewDesigning"),!1,e.sessionId,0);return}if(e.type==="styleSessionFinished"){It(!1),ge(e.message||n("aiStyle.appViewDone"),!1,e.sessionId,5e3);return}if(e.type==="styleSessionFailed"){It(!1),ge(e.message||n("aiStyle.appViewFailed"),!0,e.sessionId,5e3);return}if(e.type!=="lastFileUnavailable"){if(e.type==="lastSessionInfo"){fe=e.sessionId||null,b(),ja();return}if(e.type==="finch:menu"){Sr(e.itemId);return}if(e.type==="document"){var Q=Y;Y=!1,et();var U=e.markdown||"",ee=e.path||"",ie=Number(e.revision)||0;if(ee&&ee===f&&ie&&ie<=$e)return;var ae=!!ee&&!!f&&ee!==f;if((ae||T===null)&&(fe=null),ae&&Et&&ee!==Et){Ce===ee&&(Ce="");return}if(!ae&&U===T){ie&&($e=Math.max($e,ie)),b();return}var Lt=T===null,At=Ye;Ye=!1;var Kn=!!ee&&Ce===ee;Ce="";var Jn=Ze(U,e.title||n("common.markdownDocDefault"),e.path||f,Q||Lt||ae,e.diskMarkdown,Kn);if(!Jn){b();return}if($e=ie||(ae?0:$e),e.draftRestored)Te(!0),l(n("status.draftRestored"));else if(e.draftConflict)l(n("status.draftConflict"),!0);else if(At)l(n("status.opened",{file:W}));else if(!Lt){var X=oa;X&&X.hunks>1?l(n("status.contentUpdatedSpots",{count:X.hunks,lines:X.changedLines})):X&&X.fromLine===X.toLine?l(n("status.contentUpdatedLine",{line:X.fromLine})):l(X?n("status.contentUpdatedLines",{from:X.fromLine,to:X.toLine}):n("status.contentUpdated"))}return}if(e.type==="sourceMissing"){e.path&&e.path===f&&l(n("status.sourceMissing"),!0);return}if(e.type==="bmRendered"){if(e.requestId!==Pa)return;$a(e.html||""),Xe(),_e=!1,b(),l("");return}if(e.type==="savedMarkdown"){var ot=zt[e.requestId];delete zt[e.requestId];var Ct=Ie[e.requestId];if(delete Ie[e.requestId],e.requestId!==Oa||typeof ot!="string"){Ct&&Ct(!1);return}T=ot,Te(g!==ot,g===ot),l(n(g===ot?"status.saved":"status.savedWithNewChanges")),Ct&&Ct(!0);return}if(e.type==="customStyleSet"){O=e.css||"",Ee=e.label||n("common.customStyleDefault"),L="custom",we(),typeof e.savedSlot=="number"?(q=Array.isArray(e.styleSlots)?e.styleSlots:q,l(n("status.savedAppliedToSlot",{labelPrefix:e.label?e.label+" \xB7 ":"",slot:e.savedSlot+1}))):Xn(),k==="preview"?G():Ke("preview"),b();return}if(e.type==="exported"){l(n("status.exported",{path:e.path}));return}if(e.type!=="watchStarted"){if(e.type==="pickCancelled"){Y=!1,et(),b(),l("");return}if(e.type==="error"){Ye=!1,Et="",Ce="",Object.keys(Ie).forEach(function(se){var Er=Ie[se];delete Ie[se],Er&&Er(!1)}),Y=!1,et(),e.fallback&&(He=!1),_e=!1,b(),l(e.message,!0);return}}}}}),i&&i.postMessage&&i.postMessage({type:"panelReady"}),setTimeout(function(){!A()&&i&&i.postMessage&&i.postMessage({type:"requestLastFile"}),Ra||St()},400),Dt(),Ba(),wt(),Xe(),Ae()})();})();
|
|
46
|
+
%%EOF`;return l.push(Q(ie.join("")+Lt)),ca(l)}async function Hn(){if(!N){c(n("status.pleaseOpenArticle"),!0);return}try{c(n("status.generatingPdf"));var e=await sa();if(!e){c(n("status.exportPdfFailedGeneric"),!0);return}var t=await la(e.canvas,"image/jpeg",.92),a=await t.arrayBuffer(),r=new Uint8Array(a),o=e.cssWidth*.75,s=e.cssHeight*.75,l=qn(r,e.canvas.width,e.canvas.height,o,s),u=gr(l);i&&i.postMessage&&i.postMessage({type:"exportFile",data:u,ext:"pdf",path:m,fileName:U,markdown:h})}catch(d){c(n("status.exportPdfFailed",{err:String(d)}),!0)}}function tt(e,t){e&&e.addEventListener("click",function(a){a.preventDefault(),!e.disabled&&(e.disabled=!0,Promise.resolve().then(t).catch(function(r){c(String(r),!0)}).then(function(){e.disabled=!1}))})}tt(Lr,Pn),tt(Cr,Rn),tt(Ar,Bn),tt(Dr,Hn),tt(ke,Wn);var hr="md-editor-actions-collapsed";(function(){var t=!1;try{t=localStorage.getItem(hr)==="1"}catch{}Oe&&Oe.classList.toggle("collapsed",t)})(),ka&&ka.addEventListener("click",function(e){e.preventDefault();var t=Oe.classList.toggle("collapsed");try{localStorage.setItem(hr,t?"1":"0")}catch{}});function ua(){cr(h)}function It(e){if(Tr=e,!!ke){ke.classList.toggle("loading",e),ke.disabled=e;var t=ke.querySelector(".ic-ai-style"),a=ke.querySelector(".ic-ai-style-loading");t&&(t.hidden=e),a&&(a.hidden=!e)}}function yr(){if(!h||!m||!i||!i.postMessage){c(n("status.pleaseOpenArticle"),!0);return}i.postMessage({type:"requestStyleSession",path:m,baseStyle:L}),It(!0),c(n("aiStyle.appViewDesigning"))}async function Wn(){if(!h){c(n("status.pleaseOpenArticle"),!0);return}if(g||!i||!i.composer){yr();return}var e=L==="custom"?n("aiStyle.baseNoteCustom"):n("aiStyle.baseNoteOther",{style:L});try{await i.composer.addContexts([{type:"annotation",label:n("aiStyle.label",{file:U||n("common.markdownDocDefault")}),note:n("aiStyle.note"),promptText:n("aiStyle.promptText",{baseNote:e,path:m||n("aiStyle.pathMissing")}),reminder:n("aiStyle.reminder")}]),c(n("aiStyle.requested"))}catch{yr()}}function zn(){return{fontSize:z,fontFamily:J,comfortWriting:R,style:L,customCss:L==="custom"?O:"",customStyleLabel:L==="custom"?Ee:""}}function we(){i&&i.postMessage&&i.postMessage({type:"saveWritingPreferences",preferences:zn()})}function Un(e){return!e||typeof e!="object"?!1:((e.fontSize===14||e.fontSize===16||e.fontSize===18)&&(z=e.fontSize),Me[e.fontFamily]&&(J=e.fontFamily),R=e.comfortWriting===!0,e.style==="custom"&&typeof e.customCss=="string"&&e.customCss?(L="custom",O=e.customCss,Ee=typeof e.customStyleLabel=="string"?e.customStyleLabel:""):["kami","bauhaus","blueprint","botanical","newsprint","retro","sketch","terminal"].indexOf(e.style)!==-1&&(L=e.style,O="",Ee=""),p.setFontSize(z),p.setFontFamily(Me[J]),p.setComfortWriting(R),!0)}function Vn(e){L=e,we(),(g||x==="preview")&&X(),k()}function _n(e){if(!(e!==14&&e!==16&&e!==18)){z=e,p.setFontSize(e);try{localStorage.setItem("md-editor-font-size",String(e))}catch{}we(),k()}}function jn(e){if(Me[e]){J=e,p.setFontFamily(Me[e]);try{localStorage.setItem("md-editor-font-family",e)}catch{}we(),k()}}function br(e){R=!!e,p.setComfortWriting(R);try{localStorage.setItem("md-editor-comfort-writing",R?"1":"0")}catch{}we(),k(),c(n(R?"status.comfortWrite":"status.comfortRead"))}function wr(){B=!B,B&&te?(te=!1,F()):!B&&!te&&(te=!0),p.setFocusMode(B);try{localStorage.setItem("md-editor-focus-mode",B?"1":"0")}catch{}k(),c(n(B?"status.focusOn":"status.focusOff"))}var at=null;function rt(e){ue.hidden=!0;var t=at;at=null,t&&t(e)}function Sr(e){return new Promise(function(t){at=t,xa.textContent=e,ue.hidden=!1,Re.focus()})}async function Gn(){xa.textContent="AI \u5DF2\u5199\u56DE\u6587\u4EF6\uFF0C\u4F46\u4F60\u4E5F\u6709\u672A\u4FDD\u5B58\u7F16\u8F91\u3002\u8BF7\u9009\u62E9\u4FDD\u7559\u672C\u5730\u5185\u5BB9\u6216\u91C7\u7528 AI \u7248\u672C\u3002",Rt.textContent="\u7A0D\u540E\u5904\u7406",Bt.textContent="\u4FDD\u7559\u672C\u5730",Re.textContent="\u91C7\u7528 AI \u7248\u672C";var e=await new Promise(function(t){at=t,ue.hidden=!1,Re.focus()});return Dt(ue),e==="save"?"remote":e==="discard"?"local":"later"}Rt&&Rt.addEventListener("click",function(){rt("cancel")}),Bt&&Bt.addEventListener("click",function(){rt("discard")}),Re&&Re.addEventListener("click",function(){rt("save")}),ue&&ue.addEventListener("click",function(e){e.target===ue&&rt("cancel")}),document.addEventListener("keydown",function(e){e.key==="Escape"&&at&&rt("cancel")});async function da(){return await cr(h)}function Xn(){ur(),ra(),F(),h="",Ue="",U="",m="",T=null,fe=null,N="",te=!1,x="edit",p&&p.setValue(""),za(n("home.title")),ye(),Za(""),i&&i.postMessage&&i.postMessage({type:"goHome"}),Ye(),Ae(),Pe(!1),c("")}async function nt(){if(P){var e=await Sr(n("confirm.message",{file:U||n("common.markdownDocDefault")}));if(e==="cancel")return;if(i&&i.postMessage&&i.postMessage({type:"goHome"}),e==="save"){var t=await da();if(!t){c(n("status.saveFailedNoReturn"),!0);return}}else e==="discard"&&na(m)}Xn()}function kr(e){if(i&&i.postMessage&&i.postMessage({type:"clientLog",message:"finch:menu received, itemId="+e}),e==="home"){nt();return}if(e==="open"){ia();return}if(e==="mode"){Ke(x==="edit"?"preview":"edit");return}if(e==="save"){ua();return}if(e==="reload"){X();return}if(e==="reveal"){m&&i&&i.postMessage&&i.postMessage({type:"openPath",path:m});return}if(e==="recentSession"){fe&&i&&i.navigation&&i.navigation.openSession&&i.navigation.openSession(fe);return}if(e&&e.indexOf("font-size:")===0){_n(Number(e.slice(10)));return}if(e&&e.indexOf("font-family:")===0){jn(e.slice(12));return}if(e==="comfort:read"){br(!1);return}if(e==="comfort:write"){br(!0);return}if(e==="focus"){wr();return}if(e==="about"){Rr();return}if(e&&e.indexOf("style:slot-use:")===0){Kn(+e.slice(15));return}if(e&&e.indexOf("style:slot-save:")===0){Er(+e.slice(16));return}if(e&&e.indexOf("style:")===0){Vn(e.slice(6));return}}function pa(){[dt,pt,ft].forEach(function(e){e&&(e.hidden=!0)})}function Yn(e){if(e){var t=e.hidden;pa(),e.hidden=!t}}function fa(e,t){e&&e.addEventListener("click",function(a){a.stopPropagation(),Yn(t)}),t&&t.addEventListener("click",function(a){var r=a.target&&a.target.closest?a.target.closest("[data-app-action]"):null;if(!(r&&r.disabled)){var o=r&&r.getAttribute("data-app-action");o&&(kr(o),pa())}})}Ma&&Ma.addEventListener("click",nt),ct&&ct.addEventListener("click",ia),re&&re.addEventListener("click",ua),Ne&&Ne.addEventListener("click",wr),Be&&Be.addEventListener("click",function(){G=!G,document.body.classList.toggle("preview-hidden",!G),k(),G&&requestAnimationFrame(function(){p.layout(),X()})}),fa(ut,dt),fa(Nt,pt),fa(Fr,ft),document.addEventListener("click",pa);var ma=370,va=560,xr=480;ce&&ce.addEventListener("mousedown",function(e){e.preventDefault();var t=ce.parentElement;if(!t)return;var a=e.clientX,r=Ot?Ot.getBoundingClientRect().width:xr;ce.classList.add("active");var o=document.createElement("div");o.style.cssText="position:fixed;inset:0;z-index:9999;cursor:col-resize;",document.body.appendChild(o);function s(d){return Math.max(ma,Math.min(va,d))}function l(d){var f=d.clientX-a;t.style.setProperty("--preview-width",s(r-f)+"px")}function u(){ce.classList.remove("active"),o.remove(),window.removeEventListener("mousemove",l),window.removeEventListener("mouseup",u)}window.addEventListener("mousemove",l),window.addEventListener("mouseup",u)}),window.addEventListener("resize",function(){if(g){var e=ce&&ce.parentElement;if(e){var t=parseFloat(getComputedStyle(e).getPropertyValue("--preview-width"))||xr;(t>va||t<ma)&&e.style.setProperty("--preview-width",Math.max(ma,Math.min(va,t))+"px")}}});function Kn(e){var t=W[e];t&&(O=t.css,Ee=t.label,L="custom",we(),c(n("status.appliedStyleSlot",{label:t.label})),x==="preview"?X():Ke("preview"),k())}function Er(e){if(L!=="custom"||!O){c(n("status.needCustomStyleFirst"),!0);return}var t=Ee||n("common.customStyleDefault");i&&i.postMessage&&i.postMessage({type:"saveStyleSlot",slot:e,css:O,label:t,path:m})}function Jn(){E&&(clearTimeout(E),E=0),M.replaceChildren(document.createTextNode(n("aiStyle.applied")+" ")),M.className="status status-style-prompt";for(var e=0;e<3;e++)(function(t){var a=document.createElement("button");a.type="button",a.className="status-inline-btn",a.textContent=n("aiStyle.saveToSlot",{n:t+1});var r=W[t];r&&(a.title=r.label),a.addEventListener("click",function(){Er(t)}),M.appendChild(a)})(e);E=setTimeout(function(){E=0,M.replaceChildren(),M.className="status"},12e3)}i&&i.onMessage&&i.onMessage(function(e){if(!(!e||typeof e!="object")){if(e.type==="ready"){if(We=!!e.pickFileSupported,W=Array.isArray(e.styleSlots)?e.styleSlots:[null,null,null],Un(e.writingPreferences)?g&&C()&&X():we(),e.libraryGroups&&typeof e.libraryGroups=="object"?(de=Array.isArray(e.libraryGroups.order)?e.libraryGroups.order.filter(function(se){return typeof se=="string"}):[],xe=e.libraryGroups.collapsed&&typeof e.libraryGroups.collapsed=="object"?e.libraryGroups.collapsed:{},He.length&&Gt(He)):(de.length||Object.keys(xe).length)&&jt(),typeof e.locale=="string"&&e.locale){var t=/^zh/i.test(e.locale);t!==it&&(it=t,Dt(),wt())}e.assistantName&&(Ge=e.assistantName,wt()),Ba(),e.homeDir&&(he=e.homeDir,qr()),k();return}if(e.type==="styleSlots"){W=Array.isArray(e.styleSlots)?e.styleSlots:[null,null,null],typeof e.savedSlot=="number"&&W[e.savedSlot]&&c(n("status.savedToSlot",{slot:e.savedSlot+1,label:W[e.savedSlot].label})),k();return}if(e.type==="clipboardImages"){var a=ve[e.requestId];if(a){delete ve[e.requestId];var r=a.sourceHtml,o=e.images&&typeof e.images=="object"?e.images:{};Object.keys(o).forEach(function(se){typeof o[se]=="string"&&(r=r.split(se).join(o[se]))}),a.resolve(Dn(r))}return}if(e.type==="clipboardImagesError"){var s=ve[e.requestId];s&&(delete ve[e.requestId],s.reject(new Error(e.message||n("status.clipboardPrepareFailedDefault"))));return}if(e.type==="pastedImage"){var l=me[e.requestId];l&&(delete me[e.requestId],l.resolve(e.url));return}if(e.type==="pasteImageError"){var u=me[e.requestId];u&&(delete me[e.requestId],u.reject(new Error(e.message||n("status.pasteImageFailedDefault")))),c(n("status.pasteImageFailed",{msg:e.message||""}));return}if(e.type==="finch:env"){g=e.view==="appView",g&&(i&&i.panel&&i.panel.setTitle&&i.panel.setTitle(n("home.title")).catch(function(){}),ye(),Xr()),g&&!Fa&&(Fa=!0,G=!1,document.body.classList.add("preview-hidden")),document.body.classList.toggle("app-view",g),Ea&&(Ea.hidden=!g),p.setAiHint(n("appview.hintSpace"),n("appview.hintSpaceCode"));var d=e.cwd||"",f=e.sessionId||"",b=e.spaceId||"";(d!==je||f!==Vt||b!==_t||!bt)&&(je=d,Vt=f,_t=b,bt=!0,kt([])),Ae(),ye(),k(),g&&C()&&X(),(!Ft.hidden||g)&&St();return}if(e.type==="recentDocuments"){if(!e.library&&(e.cwd||"")!==je)return;kt(e.documents),e.library&&Gt(e.documents);return}if(e.type==="status"){c(e.message);return}if(e.type==="rewriteSessionStarted"){H=e.sessionId&&e.turnId?{sessionId:e.sessionId,turnId:e.turnId}:null,p.setAiWorkingLines(Number(e.startLine)||0,Number(e.endLine)||0),ge(e.rewriteMode==="continue"?n("appview.continuing"):n("appview.rewriting"),!1,e.sessionId,0);return}if(e.type==="rewriteCancellationRequested"){H&&H.turnId===e.turnId&&(H.cancelling=!0),ge(n("appview.cancelling"),!1,e.sessionId,0);return}if(e.type==="rewriteSessionFinished"){H=null,p.setAiWorkingLines(0,0),ge(n("appview.rewriteDone"),!1,e.sessionId,5e3);return}if(e.type==="rewriteSessionFailed"){var v=H&&H.turnId===e.turnId&&H.cancelling;H=null,p.setAiWorkingLines(0,0),ge(v?n("appview.cancelled"):e.message||"Rewrite failed.",!v,e.sessionId,5e3);return}if(e.type==="styleSessionStarted"){It(!0),ge(n("aiStyle.appViewDesigning"),!1,e.sessionId,0);return}if(e.type==="styleSessionFinished"){It(!1),ge(e.message||n("aiStyle.appViewDone"),!1,e.sessionId,5e3);return}if(e.type==="styleSessionFailed"){It(!1),ge(e.message||n("aiStyle.appViewFailed"),!0,e.sessionId,5e3);return}if(e.type!=="lastFileUnavailable"){if(e.type==="lastSessionInfo"){fe=e.sessionId||null,k(),_a();return}if(e.type==="finch:menu"){kr(e.itemId);return}if(e.type==="document"){var q=Y;Y=!1,et();var V=e.markdown||"",ee=e.path||"",ie=Number(e.revision)||0;if(ee&&ee===m&&ie&&ie<=$e)return;var ae=!!ee&&!!m&&ee!==m;if((ae||T===null)&&(fe=null),ae&&Et&&ee!==Et){De===ee&&(De="");return}if(!ae&&V===T){ie&&($e=Math.max($e,ie)),k();return}var Lt=T===null,Ct=Xe;Xe=!1;var $n=!!ee&&De===ee;De="";var Zn=Ze(V,e.title||n("common.markdownDocDefault"),e.path||m,q||Lt||ae,e.diskMarkdown,$n);if(!Zn){k();return}if($e=ie||(ae?0:$e),e.draftRestored)Pe(!0),c(n("status.draftRestored"));else if(e.draftConflict)c(n("status.draftConflict"),!0);else if(Ct)c(n("status.opened",{file:U}));else if(!Lt){var K=oa;K&&K.hunks>1?c(n("status.contentUpdatedSpots",{count:K.hunks,lines:K.changedLines})):K&&K.fromLine===K.toLine?c(n("status.contentUpdatedLine",{line:K.fromLine})):c(K?n("status.contentUpdatedLines",{from:K.fromLine,to:K.toLine}):n("status.contentUpdated"))}return}if(e.type==="sourceMissing"){e.path&&e.path===m&&c(n("status.sourceMissing"),!0);return}if(e.type==="bmRendered"){if(e.requestId!==Pa)return;Za(e.html||""),Ye(),Ve=!1,k(),c("");return}if(e.type==="savedMarkdown"){var ot=zt[e.requestId];delete zt[e.requestId];var At=Le[e.requestId];if(delete Le[e.requestId],e.requestId!==Oa||typeof ot!="string"){At&&At(!1);return}T=ot,Pe(h!==ot,h===ot),c(n(h===ot?"status.saved":"status.savedWithNewChanges")),At&&At(!0);return}if(e.type==="customStyleSet"){O=e.css||"",Ee=e.label||n("common.customStyleDefault"),L="custom",we(),typeof e.savedSlot=="number"?(W=Array.isArray(e.styleSlots)?e.styleSlots:W,c(n("status.savedAppliedToSlot",{labelPrefix:e.label?e.label+" \xB7 ":"",slot:e.savedSlot+1}))):Jn(),x==="preview"?X():Ke("preview"),k();return}if(e.type==="exported"){c(n("status.exported",{path:e.path}));return}if(e.type!=="watchStarted"){if(e.type==="pickCancelled"){Y=!1,et(),k(),c("");return}if(e.type==="error"){Xe=!1,Et="",De="",Object.keys(Le).forEach(function(se){var Mr=Le[se];delete Le[se],Mr&&Mr(!1)}),Y=!1,et(),e.fallback&&(We=!1),Ve=!1,k(),c(e.message,!0);return}}}}}),i&&i.postMessage&&i.postMessage({type:"panelReady"}),setTimeout(function(){!C()&&i&&i.postMessage&&i.postMessage({type:"requestLastFile"}),Ra||St()},400),Dt(),Ba(),wt(),Ye(),Ae()})();})();
|
package/package.json
CHANGED