AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
feat: optimize note image sharing (#292)
tianma-ifad73ea8f2d62
diff --git a/apps/ios/EdgeEver/Features/Workspace/MemoDetailView.swift b/apps/ios/EdgeEver/Features/Workspace/MemoDetailView.swiftindex c5074e95..a1b6ad73 100644--- a/apps/ios/EdgeEver/Features/Workspace/MemoDetailView.swift+++ b/apps/ios/EdgeEver/Features/Workspace/MemoDetailView.swift@@ -18,6 +18,12 @@ struct MemoDetailView: View {@State private var imageExportMessage: MemoImageExportMessage?@State private var imageExporting = false@State private var imageExportBuffer = MemoImageExportBuffer()+ @State private var imageShareOptionsOpen = false+ @State private var imageShareFormat = "png"+ @State private var imageShareBackground = "slate"+ @State private var imageShareNotebook = true+ @State private var imageShareTags = true+ @State private var imageShareUpdatedAt = true@State private var error: String?@State private var conflictItem: OutboxItem?@State private var outboxStatus: OutboxStatus?@@ -120,6 +126,54 @@ struct MemoDetailView: View {imageExportSharePayload = nil}}+ .sheet(isPresented: $imageShareOptionsOpen) {+ NavigationStack {+ Form {+ Section(env.preferences.t("背景", en: "Background")) {+ Picker(env.preferences.t("背景", en: "Background"), selection: $imageShareBackground) {+ Text(env.preferences.t("简洁", en: "Clean")).tag("slate")+ Text(env.preferences.t("薄荷", en: "Mint")).tag("mint")+ Text(env.preferences.t("暖色", en: "Warm")).tag("warm")+ }+ .pickerStyle(.segmented)+ }+ Section(env.preferences.t("笔记信息", en: "Note information")) {+ Toggle(env.preferences.t("笔记本", en: "Notebook"), isOn: $imageShareNotebook)+ Toggle(env.preferences.t("标签", en: "Tags"), isOn: $imageShareTags)+ Toggle(env.preferences.t("更新时间", en: "Updated time"), isOn: $imageShareUpdatedAt)+ }+ Section(env.preferences.t("图片格式", en: "Image format")) {+ Picker(env.preferences.t("图片格式", en: "Image format"), selection: $imageShareFormat) {+ Text(env.preferences.t("PNG · 文字更清晰", en: "PNG · Best for text")).tag("png")+ Text(env.preferences.t("JPEG · 文件更小", en: "JPEG · Smaller file")).tag("jpeg")+ }+ .pickerStyle(.segmented)+ }+ }+ .navigationTitle(env.preferences.t("分享为图片", en: "Share as image"))+ .navigationBarTitleDisplayMode(.inline)+ .toolbar {+ ToolbarItem(placement: .cancellationAction) {+ Button(env.preferences.t("取消", en: "Cancel")) { imageShareOptionsOpen = false }+ }+ ToolbarItem(placement: .confirmationAction) {+ Button(env.preferences.t("生成并分享", en: "Generate & Share")) {+ guard let memo else { return }+ imageShareOptionsOpen = false+ exportMemoImage(+ memo,+ format: imageShareFormat,+ background: imageShareBackground,+ showNotebook: imageShareNotebook,+ showTags: imageShareTags,+ showUpdatedAt: imageShareUpdatedAt+ )+ }+ .disabled(imageExporting || !bodyReady || memo == nil)+ }+ }+ }+ }.alert(item: $imageExportMessage) { message inAlert(title: Text(message.title),@@ -184,8 +238,12 @@ struct MemoDetailView: View {Button(imageExporting? env.preferences.t("正在导出图片…", en: "Exporting image…")- : env.preferences.t("导出 PNG", en: "Export PNG")+ : env.preferences.t("分享为图片", en: "Share as image")) {+ imageShareOptionsOpen = true+ }+ .disabled(imageExporting || !bodyReady)+ Button(env.preferences.t("高级导出 PNG", en: "Advanced export PNG")) {exportMemoImage(memo, format: "png")}.disabled(imageExporting || !bodyReady)@@ -859,7 +917,14 @@ struct MemoDetailView: View {}}- private func exportMemoImage(_ memo: MemoDetail, format: String) {+ private func exportMemoImage(+ _ memo: MemoDetail,+ format: String,+ background: String = "slate",+ showNotebook: Bool = true,+ showTags: Bool = true,+ showUpdatedAt: Bool = true+ ) {guard !imageExporting, bodyReady else { return }let requestId = UUID().uuidStringimageExportBuffer.start(requestId: requestId)@@ -870,9 +935,10 @@ struct MemoDetailView: View {"format": format,"title": title?.isEmpty == false ? title! : env.preferences.t("无标题笔记", en: "Untitled note"),"fallbackTitle": env.preferences.t("无标题笔记", en: "Untitled note"),- "notebook": notebookName(for: memo),- "tags": memo.tags,- "updatedAt": memo.updatedAt,+ "notebook": showNotebook ? notebookName(for: memo) : "",+ "tags": showTags ? memo.tags : [],+ "updatedAt": showUpdatedAt ? memo.updatedAt : "",+ "background": background,])}diff --git a/apps/ios/EdgeEver/Resources/EditorBundle/index.html b/apps/ios/EdgeEver/Resources/EditorBundle/index.htmlindex f78ab0bb..aae23a62 100644--- a/apps/ios/EdgeEver/Resources/EditorBundle/index.html+++ b/apps/ios/EdgeEver/Resources/EditorBundle/index.html@@ -814,7 +814,7 @@ l0,-`+(r+144)+`c-2,-159.3,-10,-310.7,-24,-454c-53.3,-528,-210,-949.7,`)},LI="edgeever-inline-sentinel",Yct=(t,e,r)=>{var i;const n=(i=t.storage.markdown)==null?void 0:i.manager;return n!=null&&n.serialize?n.serialize($_({type:"doc",content:[{type:"paragraph",content:e}]})).replaceAll(O_,"\\$"):r},Xct=t=>{const e=t.state.selection;if(e.empty||e.from>=e.to)return null;const r=[];if(t.state.doc.nodesBetween(e.from,e.to,(i,a)=>{if(!i.isTextblock)return!0;const s=a+1,o=s+i.content.size,l=Math.max(e.from,s),u=Math.min(e.to,o);return u>l&&r.push({node:i,contentFrom:s,contentTo:o,from:l,to:u}),!1}),r.length===1){const i=r[0],a=i.node.cut(i.from-i.contentFrom,i.to-i.contentFrom).toJSON(),s=t.state.doc.textBetween(i.from,i.to,``),o=Yct(t,a.content??[],s).trim();return o?{from:i.from,to:i.to,isInline:!0,markdown:o,text:s}:null}const n=Uct(t,e.from,e.to).trim();return n?{from:e.from,to:e.to,isInline:!1,markdown:n,text:t.state.doc.textBetween(e.from,e.to,`-`)}:null},jct=(t,e,r)=>{var f,p,g;const n=(f=t.storage.markdown)==null?void 0:f.manager,i=e.trim(),a=((p=n==null?void 0:n.parse)==null?void 0:p.call(n,i).content)??[{type:"text",text:i}];if(!r)return a;const s=i.replace(/\s*\n+\s*/g," "),o=(g=n==null?void 0:n.parse)==null?void 0:g.call(n,`${LI}${s}`).content,l=(o==null?void 0:o.length)===1?o[0]:null,u=(l==null?void 0:l.type)==="paragraph"?l.content??[]:[],h=u[0];if((h==null?void 0:h.type)!=="text"||typeof h.text!="string"||!h.text.startsWith(LI))return[{type:"text",text:s}];const d=h.text.slice(LI.length);return[...d?[{...h,text:d}]:[],...u.slice(1)]};function Vh(t){try{const e=JSON.stringify(t.getJSON()),r=O2e(t);Ss({type:"change",contentMarkdown:r,contentJson:e})}catch(e){Ss({type:"error",message:e instanceof Error?e.message:String(e)})}}function Kct(t,e){const r=e.trim().toLocaleLowerCase();if(r.length===0)return[];const n=[];let i=null;t.state.doc.descendants((l,u)=>{if(!(!l.isText||!l.text)){i!==null&&u>i&&n.push({char:"\0",pos:-1});for(let h=0;h<l.text.length;h+=1)n.push({char:l.text[h]??"",pos:u+h});i=u+l.text.length}});const a=n.map(l=>l.char).join("").toLocaleLowerCase(),s=[];let o=a.indexOf(r);for(;o!==-1;){const l=n[o],u=n[o+r.length-1];l&&u&&l.pos>=0&&u.pos>=0&&s.push({from:l.pos,to:u.pos+1}),o=a.indexOf(r,o+r.length)}return s}const xte=()=>Tr.isActive("taskItem")?"taskItem":"listItem";function $2e(t){var r;if(WS.classList.toggle("editor-mode",t),WS.innerHTML="",!t)return;const e=[{id:"image",label:"▧+",run:()=>Ss({type:"pickImage"})},{id:"bold",label:"B",run:()=>Tr.chain().focus().toggleBold().run()},{id:"bullet",label:"•",run:()=>Tr.chain().focus().toggleBulletList().run()},{id:"task",label:"☑",run:()=>Tr.chain().focus().toggleTaskList().run()},{id:"indent",label:"⇥",run:()=>Tr.chain().focus().sinkListItem(xte()).run()},{id:"outdent",label:"⇤",run:()=>Tr.chain().focus().liftListItem(xte()).run()},{id:"quote",label:"❝",run:()=>Tr.chain().focus().toggleBlockquote().run()},{id:"hr",label:"—",run:()=>Tr.chain().focus().setHorizontalRule().run()}];for(const n of e){const i=document.createElement("button");i.type="button",i.textContent=n.label,i.dataset.action=n.id;const a={image:["插入图片","Insert image"],bold:["粗体","Bold"],bullet:["项目符号列表","Bullet list"],task:["任务清单","Task list"],indent:["增加列表缩进","Increase list indent"],outdent:["减少列表缩进","Decrease list indent"],quote:["引用","Block quote"],hr:["分隔线","Horizontal rule"]};i.setAttribute("aria-label",((r=a[n.id])==null?void 0:r[M2e==="en-US"?1:0])??n.id),i.addEventListener("click",()=>{n.run(),n.id!=="image"&&Vh(Tr),G8()}),WS.appendChild(i)}G8()}function G8(){const t={bold:Tr.isActive("bold"),bullet:Tr.isActive("bulletList"),task:Tr.isActive("taskList"),quote:Tr.isActive("blockquote")};WS.querySelectorAll("button[data-action]").forEach(e=>{e.classList.toggle("is-active",t[e.dataset.action??""]??!1)})}async function MI(t="light"){Ql.querySelectorAll("[data-placeholder]").forEach(e=>{e.dataset.placeholder=OP}),await Vct(Ql),xs==="viewer"&&await Hct(Ql,t)}async function Zct(t){var l;if(!t.requestId||t.format!=="png"&&t.format!=="jpeg")return;const e=document.createElement("div");e.style.cssText=`position:fixed;left:-100000px;top:0;width:${mte}px;pointer-events:none;`;const r=document.createElement("div");r.className="edgeever-image-document";const n=document.createElement("article");n.className="edgeever-image-card";const i=document.createElement("h1");i.className="edgeever-image-title",i.textContent=t.title||t.fallbackTitle,n.appendChild(i);const a=[t.notebook,t.updatedAt,...(t.tags??[]).map(u=>`#${u}`)].filter(Boolean);if(a.length>0){const u=document.createElement("div");u.className="edgeever-image-meta",u.textContent=a.join(" · "),n.appendChild(u)}const s=document.createElement("div");s.className="edgeever-image-content";const o=Tr.view.dom.cloneNode(!0);o.removeAttribute("contenteditable"),o.querySelectorAll("button, [contenteditable='true']").forEach(u=>{u.removeAttribute("contenteditable"),u instanceof HTMLButtonElement&&u.remove()}),s.appendChild(o),n.appendChild(s),r.appendChild(n),e.appendChild(r),document.body.appendChild(e);try{await((l=document.fonts)==null?void 0:l.ready),await Promise.all(Array.from(r.querySelectorAll("img")).map(async x=>{if(!x.complete)try{await x.decode()}catch{}}));const u=Math.max(1,Math.ceil(r.getBoundingClientRect().height)),h=await Aot(r,{backgroundColor:"#f8fafc",height:u,pixelRatio:$ct,skipFonts:!0,width:mte}),d=await new Promise((x,b)=>{h.toBlob(w=>w?x(w):b(new Error("Image renderer returned an empty file")),t.format==="jpeg"?"image/jpeg":"image/png",t.format==="jpeg"?.9:1)}),f=t.format==="jpeg"?"jpg":"png",p=Bct(t.title,t.fallbackTitle),g=await Fct(d),m=`${p}.${f}`,y=t.format==="jpeg"?"image/jpeg":"image/png",v=zct(g);for(let x=0;x<v.length;x+=yte)Ss({type:"imageExportChunk",requestId:t.requestId,chunk:v.slice(x,x+yte)}),await new Promise(b=>setTimeout(b,0));Ss({type:"imageExportComplete",requestId:t.requestId,filename:m,mimeType:y})}catch(u){Ss({type:"imageExportError",requestId:t.requestId,message:u instanceof Error?u.message:"Image export failed"})}finally{e.remove()}}const Qct={exportImage(t){Zct(t)},configure(t){const e=t.mode==="editor"?"editor":"viewer",r=e!==xs;xs=e,M2e=t.locale==="en-US"?"en-US":"zh-CN",Tr.setEditable(xs==="editor"),$2e(xs==="editor"),document.documentElement.dataset.theme=t.theme||"light",document.body.classList.toggle("viewer-mode",xs==="viewer"),document.body.classList.toggle("editor-mode",xs==="editor"),t.placeholder&&(OP=t.placeholder,Ql.querySelectorAll("[data-placeholder]").forEach(n=>{n.dataset.placeholder=OP})),xs==="editor"&&r&&requestAnimationFrame(()=>{try{Tr.commands.focus("end")}catch{}}),MI(t.theme||"light")},setMarkdown(t){var e;w3=!0;try{Tr.commands.setContent(t||"",{contentType:"markdown"})}catch{try{const r=(e=Tr.storage.markdown)==null?void 0:e.manager;if(r)Tr.commands.setContent(r.parse(t||""));else throw new Error("no markdown manager")}catch{Tr.commands.setContent({type:"doc",content:[{type:"paragraph",content:t?[{type:"text",text:t}]:[]}]})}}Tr.setEditable(xs==="editor"),w3=!1,MI(document.documentElement.dataset.theme||"light")},setDocumentFromJSON(t){w3=!0;try{const e=JSON.parse(t);Tr.commands.setContent(e)}catch{Tr.commands.setContent({type:"doc",content:[{type:"paragraph"}]})}Tr.setEditable(xs==="editor"),w3=!1,MI(document.documentElement.dataset.theme||"light")},resolveResource(t,e){const r=V8.get(t);r&&(V8.delete(t),r(e))},getMarkdown(){return O2e(Tr)},getDocument(){return JSON.stringify(Tr.getJSON())},captureSelection(){const t=Xct(Tr);return t?(OT={from:t.from,to:t.to,isInline:t.isInline,documentFingerprint:JSON.stringify(Tr.getJSON())},JSON.stringify({from:t.from,to:t.to,markdown:t.markdown,text:t.text})):(OT=null,null)},applySelectionDraft(t,e){var s,o;const r=OT;if(!r||!t.trim())return!1;if(JSON.stringify(Tr.getJSON())!==r.documentFingerprint)return OT=null,!1;const n=Tr.state.doc.content.size,i=Math.min(Math.max(r.from,0),n),a=Math.min(Math.max(r.to,i),n);try{const l=(s=Tr.storage.markdown)==null?void 0:s.manager,u=(o=l==null?void 0:l.parse)==null?void 0:o.call(l,t),h=e==="replace"?jct(Tr,t,r.isInline):(u==null?void 0:u.content)??t,d=e==="append"?{from:a,to:a}:{from:i,to:a};return Tr.chain().focus().insertContentAt(d,h).run(),OT=null,Vh(Tr),!0}catch{return!1}},undo(){if(!Tr.can().undo())return!1;const t=Tr.commands.undo();return t&&Vh(Tr),t},focusEnd(){var t;try{Tr.commands.focus("end")}catch{}try{const e=(t=Tr.view)==null?void 0:t.dom;e&&typeof e.focus=="function"&&e.focus({preventScroll:!0})}catch{}},flush(){Vh(Tr)},exec(t){var r;const e={bold:()=>Tr.chain().focus().toggleBold().run(),bulletList:()=>Tr.chain().focus().toggleBulletList().run(),taskList:()=>Tr.chain().focus().toggleTaskList().run(),blockquote:()=>Tr.chain().focus().toggleBlockquote().run(),horizontalRule:()=>Tr.chain().focus().setHorizontalRule().run(),heading2:()=>Tr.chain().focus().toggleHeading({level:2}).run(),codeBlock:()=>Tr.chain().focus().toggleCodeBlock().run()};(r=e[t])==null||r.call(e),Vh(Tr)},beginImageUpload(t,e){Tr.chain().focus().setImage({src:e,alt:t}).run();const r=Ql.querySelectorAll("img"),n=r[r.length-1];n&&(n.dataset.uploadId=t),Vh(Tr)},completeImageUpload(t,e,r){Tr.chain().focus().setImage({src:e,alt:r||t||""}).run();const n=Ql.querySelectorAll("img"),i=n[n.length-1];i&&(i.dataset.originalSrc=e,delete i.dataset.uploadId),Vh(Tr)},cancelImageUpload(t){const e=Ql.querySelector(`img[data-upload-id="${t}"]`);e==null||e.remove(),Vh(Tr)},search(t,e){const r=Kct(Tr,t),n=r.length>0?Math.min(Math.max(Number.isFinite(e)?e:0,0),r.length-1):0,i=r[n];if(i){Tr.commands.setTextSelection({from:i.from,to:i.to});try{const a=Tr.view.domAtPos(i.from).node,s=a instanceof Element?a:a.parentElement;s==null||s.scrollIntoView({block:"center",behavior:"smooth"})}catch{}}Ss({type:"searchResult",count:r.length,index:n})}};window.EdgeEverEditor=Qct;$2e(!1);Ss({type:"ready",startupMs:Math.round(performance.now()-Oct)});class Bt extends Error{constructor(e,r){var n="KaTeX parse error: "+e,i,a,s=r&&r.loc;if(s&&s.start<=s.end){var o=s.lexer.input;i=s.start,a=s.end,i===o.length?n+=" at end of input: ":n+=" at position "+(i+1)+": ";var l=o.slice(i,a).replace(/[^]/g,"$&̲"),u;i>15?u="…"+o.slice(i-15,i):u=o.slice(0,i);var h;a+15<o.length?h=o.slice(a,a+15)+"…":h=o.slice(a),n+=u+l+h}super(n),this.name="ParseError",this.position=void 0,this.length=void 0,this.rawMessage=void 0,Object.setPrototypeOf(this,Bt.prototype),this.position=i,i!=null&&a!=null&&(this.length=a-i),this.rawMessage=e}}var Jct=/([A-Z])/g,eut=t=>t.replace(Jct,"-$1").toLowerCase(),tut={"&":"&",">":">","<":"<",'"':""","'":"'"},rut=/[&><"']/g,Gs=t=>String(t).replace(rut,e=>tut[e]),US=t=>t.type==="ordgroup"||t.type==="color"?t.body.length===1?US(t.body[0]):t:t.type==="font"?US(t.body):t,nut=new Set(["mathord","textord","atom"]),Gd=t=>nut.has(US(t).type),iut=t=>{var e=/^[\x00-\x20]*([^\\/#?]*?)(:|�*58|�*3a|&colon)/i.exec(t);return e?e[2]!==":"||!/^[a-zA-Z][a-zA-Z0-9+\-.]*$/.test(e[1])?null:e[1].toLowerCase():"_relative"},q8={displayMode:{type:"boolean",description:"Render math in display mode, which puts the math in display style (so \\int and \\sum are large, for example), and centers the math on the page on its own line.",cli:"-d, --display-mode"},output:{type:{enum:["htmlAndMathml","html","mathml"]},description:"Determines the markup language of the output.",cli:"-F, --format <type>"},leqno:{type:"boolean",description:"Render display math in leqno style (left-justified tags)."},fleqn:{type:"boolean",description:"Render display math flush left."},throwOnError:{type:"boolean",default:!0,cli:"-t, --no-throw-on-error",cliDescription:"Render errors (in the color given by --error-color) instead of throwing a ParseError exception when encountering an error."},errorColor:{type:"string",default:"#cc0000",cli:"-c, --error-color <color>",cliDescription:"A color string given in the format 'rgb' or 'rrggbb' (no #). This option determines the color of errors rendered by the -t option.",cliProcessor:t=>"#"+t},macros:{type:"object",cli:"-m, --macro <def>",cliDescription:"Define custom macro of the form '\\foo:expansion' (use multiple -m arguments for multiple macros).",cliDefault:[],cliProcessor:(t,e)=>(e.push(t),e)},minRuleThickness:{type:"number",description:"Specifies a minimum thickness, in ems, for fraction lines, `\\sqrt` top lines, `{array}` vertical lines, `\\hline`, `\\hdashline`, `\\underline`, `\\overline`, and the borders of `\\fbox`, `\\boxed`, and `\\fcolorbox`.",processor:t=>Math.max(0,t),cli:"--min-rule-thickness <size>",cliProcessor:parseFloat},colorIsTextColor:{type:"boolean",description:"Makes \\color behave like LaTeX's 2-argument \\textcolor, instead of LaTeX's one-argument \\color mode change.",cli:"-b, --color-is-text-color"},strict:{type:[{enum:["warn","ignore","error"]},"boolean","function"],description:"Turn on strict / LaTeX faithfulness mode, which throws an error if the input uses features that are not supported by LaTeX.",cli:"-S, --strict",cliDefault:!1},trust:{type:["boolean","function"],description:"Trust the input, enabling all HTML features such as \\url.",cli:"-T, --trust"},maxSize:{type:"number",default:1/0,description:"If non-zero, all user-specified sizes, e.g. in \\rule{500em}{500em}, will be capped to maxSize ems. Otherwise, elements and spaces can be arbitrarily large",processor:t=>Math.max(0,t),cli:"-s, --max-size <n>",cliProcessor:parseInt},maxExpand:{type:"number",default:1e3,description:"Limit the number of macro expansions to the specified number, to prevent e.g. infinite macro loops. If set to Infinity, the macro expander will try to fully expand as in LaTeX.",processor:t=>Math.max(0,t),cli:"-e, --max-expand <n>",cliProcessor:t=>t==="Infinity"?1/0:parseInt(t)},globalGroup:{type:"boolean",cli:!1}};function aut(t){if(typeof t!="string")return t.enum[0];switch(t){case"boolean":return!1;case"string":return"";case"number":return 0;case"object":return{};default:throw new Error("Unexpected schema type; settings must declare an explicit default.")}}function sut(t){if(t.default!==void 0)return t.default;var e=Array.isArray(t.type)?t.type[0]:t.type;return aut(e)}function out(t,e,r,n){var i=r[e];t[e]=i!==void 0?n.processor?n.processor(i):i:sut(n)}class Kq{constructor(e){e===void 0&&(e={}),this.displayMode=void 0,this.output=void 0,this.leqno=void 0,this.fleqn=void 0,this.throwOnError=void 0,this.errorColor=void 0,this.macros=void 0,this.minRuleThickness=void 0,this.colorIsTextColor=void 0,this.strict=void 0,this.trust=void 0,this.maxSize=void 0,this.maxExpand=void 0,this.globalGroup=void 0,e=e||{};for(var r of Object.keys(q8)){var n=q8[r];n&&out(this,r,e,n)}}reportNonstrict(e,r,n){var i=this.strict;if(typeof i=="function"&&(i=i(e,r,n)),!(!i||i==="ignore")){if(i===!0||i==="error")throw new Bt("LaTeX-incompatible input and strict mode is set to 'error': "+(r+" ["+e+"]"),n);i==="warn"?typeof console<"u"&&console.warn("LaTeX-incompatible input and strict mode is set to 'warn': "+(r+" ["+e+"]")):typeof console<"u"&&console.warn("LaTeX-incompatible input and strict mode is set to "+("unrecognized '"+i+"': "+r+" ["+e+"]"))}}useStrictBehavior(e,r,n){var i=this.strict;if(typeof i=="function")try{i=i(e,r,n)}catch{i="error"}return!i||i==="ignore"?!1:i===!0||i==="error"?!0:i==="warn"?(typeof console<"u"&&console.warn("LaTeX-incompatible input and strict mode is set to 'warn': "+(r+" ["+e+"]")),!1):(typeof console<"u"&&console.warn("LaTeX-incompatible input and strict mode is set to "+("unrecognized '"+i+"': "+r+" ["+e+"]")),!1)}isTrusted(e){if("url"in e&&e.url&&!e.protocol){var r=iut(e.url);if(r==null)return!1;e.protocol=r}var n=typeof this.trust=="function"?this.trust(e):this.trust;return!!n}}class hf{constructor(e,r,n){this.id=void 0,this.size=void 0,this.cramped=void 0,this.id=e,this.size=r,this.cramped=n}sup(){return Au[lut[this.id]]}sub(){return Au[cut[this.id]]}fracNum(){return Au[uut[this.id]]}fracDen(){return Au[hut[this.id]]}cramp(){return Au[dut[this.id]]}text(){return Au[fut[this.id]]}isTight(){return this.size>=2}}var Zq=0,W8=1,Oy=2,fd=3,vw=4,Jl=5,t4=6,mo=7,Au=[new hf(Zq,0,!1),new hf(W8,0,!0),new hf(Oy,1,!1),new hf(fd,1,!0),new hf(vw,2,!1),new hf(Jl,2,!0),new hf(t4,3,!1),new hf(mo,3,!0)],lut=[vw,Jl,vw,Jl,t4,mo,t4,mo],cut=[Jl,Jl,Jl,Jl,mo,mo,mo,mo],uut=[Oy,fd,vw,Jl,t4,mo,t4,mo],hut=[fd,fd,Jl,Jl,mo,mo,mo,mo],dut=[W8,W8,fd,fd,Jl,Jl,mo,mo],fut=[Zq,W8,Oy,fd,Oy,fd,Oy,fd],Zr={DISPLAY:Au[Zq],TEXT:Au[Oy],SCRIPT:Au[vw],SCRIPTSCRIPT:Au[t4]},$P=[{name:"latin",blocks:[[256,591],[768,879]]},{name:"cyrillic",blocks:[[1024,1279]]},{name:"armenian",blocks:[[1328,1423]]},{name:"brahmic",blocks:[[2304,4255]]},{name:"georgian",blocks:[[4256,4351]]},{name:"cjk",blocks:[[12288,12543],[19968,40879],[65280,65376]]},{name:"hangul",blocks:[[44032,55215]]}];function put(t){for(var e=0;e<$P.length;e++)for(var r=$P[e],n=0;n<r.blocks.length;n++){var i=r.blocks[n];if(t>=i[0]&&t<=i[1])return r.name}return null}var YS=[];$P.forEach(t=>t.blocks.forEach(e=>YS.push(...e)));function P2e(t){for(var e=0;e<YS.length;e+=2)if(t>=YS[e]&&t<=YS[e+1])return!0;return!1}var La=t=>t+" "+t,f1=80,gut=function(e,r){return"M95,"+(622+e+r)+`+`)}:null},jct=(t,e,r)=>{var f,p,g;const n=(f=t.storage.markdown)==null?void 0:f.manager,i=e.trim(),a=((p=n==null?void 0:n.parse)==null?void 0:p.call(n,i).content)??[{type:"text",text:i}];if(!r)return a;const s=i.replace(/\s*\n+\s*/g," "),o=(g=n==null?void 0:n.parse)==null?void 0:g.call(n,`${LI}${s}`).content,l=(o==null?void 0:o.length)===1?o[0]:null,u=(l==null?void 0:l.type)==="paragraph"?l.content??[]:[],h=u[0];if((h==null?void 0:h.type)!=="text"||typeof h.text!="string"||!h.text.startsWith(LI))return[{type:"text",text:s}];const d=h.text.slice(LI.length);return[...d?[{...h,text:d}]:[],...u.slice(1)]};function Vh(t){try{const e=JSON.stringify(t.getJSON()),r=O2e(t);Ss({type:"change",contentMarkdown:r,contentJson:e})}catch(e){Ss({type:"error",message:e instanceof Error?e.message:String(e)})}}function Kct(t,e){const r=e.trim().toLocaleLowerCase();if(r.length===0)return[];const n=[];let i=null;t.state.doc.descendants((l,u)=>{if(!(!l.isText||!l.text)){i!==null&&u>i&&n.push({char:"\0",pos:-1});for(let h=0;h<l.text.length;h+=1)n.push({char:l.text[h]??"",pos:u+h});i=u+l.text.length}});const a=n.map(l=>l.char).join("").toLocaleLowerCase(),s=[];let o=a.indexOf(r);for(;o!==-1;){const l=n[o],u=n[o+r.length-1];l&&u&&l.pos>=0&&u.pos>=0&&s.push({from:l.pos,to:u.pos+1}),o=a.indexOf(r,o+r.length)}return s}const xte=()=>Tr.isActive("taskItem")?"taskItem":"listItem";function $2e(t){var r;if(WS.classList.toggle("editor-mode",t),WS.innerHTML="",!t)return;const e=[{id:"image",label:"▧+",run:()=>Ss({type:"pickImage"})},{id:"bold",label:"B",run:()=>Tr.chain().focus().toggleBold().run()},{id:"bullet",label:"•",run:()=>Tr.chain().focus().toggleBulletList().run()},{id:"task",label:"☑",run:()=>Tr.chain().focus().toggleTaskList().run()},{id:"indent",label:"⇥",run:()=>Tr.chain().focus().sinkListItem(xte()).run()},{id:"outdent",label:"⇤",run:()=>Tr.chain().focus().liftListItem(xte()).run()},{id:"quote",label:"❝",run:()=>Tr.chain().focus().toggleBlockquote().run()},{id:"hr",label:"—",run:()=>Tr.chain().focus().setHorizontalRule().run()}];for(const n of e){const i=document.createElement("button");i.type="button",i.textContent=n.label,i.dataset.action=n.id;const a={image:["插入图片","Insert image"],bold:["粗体","Bold"],bullet:["项目符号列表","Bullet list"],task:["任务清单","Task list"],indent:["增加列表缩进","Increase list indent"],outdent:["减少列表缩进","Decrease list indent"],quote:["引用","Block quote"],hr:["分隔线","Horizontal rule"]};i.setAttribute("aria-label",((r=a[n.id])==null?void 0:r[M2e==="en-US"?1:0])??n.id),i.addEventListener("click",()=>{n.run(),n.id!=="image"&&Vh(Tr),G8()}),WS.appendChild(i)}G8()}function G8(){const t={bold:Tr.isActive("bold"),bullet:Tr.isActive("bulletList"),task:Tr.isActive("taskList"),quote:Tr.isActive("blockquote")};WS.querySelectorAll("button[data-action]").forEach(e=>{e.classList.toggle("is-active",t[e.dataset.action??""]??!1)})}async function MI(t="light"){Ql.querySelectorAll("[data-placeholder]").forEach(e=>{e.dataset.placeholder=OP}),await Vct(Ql),xs==="viewer"&&await Hct(Ql,t)}async function Zct(t){var l;if(!t.requestId||t.format!=="png"&&t.format!=="jpeg")return;const e=document.createElement("div");e.style.cssText=`position:fixed;left:-100000px;top:0;width:${mte}px;pointer-events:none;`;const r=document.createElement("div");r.className="edgeever-image-document";const n=document.createElement("article");n.className="edgeever-image-card";const i=document.createElement("h1");i.className="edgeever-image-title",i.textContent=t.title||t.fallbackTitle,n.appendChild(i);const a=[t.notebook,t.updatedAt,...(t.tags??[]).map(u=>`#${u}`)].filter(Boolean);if(a.length>0){const u=document.createElement("div");u.className="edgeever-image-meta",u.textContent=a.join(" · "),n.appendChild(u)}const s=document.createElement("div");s.className="edgeever-image-content";const o=Tr.view.dom.cloneNode(!0);o.removeAttribute("contenteditable"),o.querySelectorAll("button, [contenteditable='true']").forEach(u=>{u.removeAttribute("contenteditable"),u instanceof HTMLButtonElement&&u.remove()}),s.appendChild(o),n.appendChild(s),r.appendChild(n),e.appendChild(r),document.body.appendChild(e);try{await((l=document.fonts)==null?void 0:l.ready),await Promise.all(Array.from(r.querySelectorAll("img")).map(async b=>{if(!b.complete)try{await b.decode()}catch{}}));const u=Math.max(1,Math.ceil(r.getBoundingClientRect().height)),h={mint:"#ecfdf5",slate:"#f8fafc",warm:"#fffbeb"}[t.background??"slate"];r.style.backgroundColor=h;const d=await Aot(r,{backgroundColor:h,height:u,pixelRatio:$ct,skipFonts:!0,width:mte}),f=await new Promise((b,w)=>{d.toBlob(k=>k?b(k):w(new Error("Image renderer returned an empty file")),t.format==="jpeg"?"image/jpeg":"image/png",t.format==="jpeg"?.9:1)}),p=t.format==="jpeg"?"jpg":"png",g=Bct(t.title,t.fallbackTitle),m=await Fct(f),y=`${g}.${p}`,v=t.format==="jpeg"?"image/jpeg":"image/png",x=zct(m);for(let b=0;b<x.length;b+=yte)Ss({type:"imageExportChunk",requestId:t.requestId,chunk:x.slice(b,b+yte)}),await new Promise(w=>setTimeout(w,0));Ss({type:"imageExportComplete",requestId:t.requestId,filename:y,mimeType:v})}catch(u){Ss({type:"imageExportError",requestId:t.requestId,message:u instanceof Error?u.message:"Image export failed"})}finally{e.remove()}}const Qct={exportImage(t){Zct(t)},configure(t){const e=t.mode==="editor"?"editor":"viewer",r=e!==xs;xs=e,M2e=t.locale==="en-US"?"en-US":"zh-CN",Tr.setEditable(xs==="editor"),$2e(xs==="editor"),document.documentElement.dataset.theme=t.theme||"light",document.body.classList.toggle("viewer-mode",xs==="viewer"),document.body.classList.toggle("editor-mode",xs==="editor"),t.placeholder&&(OP=t.placeholder,Ql.querySelectorAll("[data-placeholder]").forEach(n=>{n.dataset.placeholder=OP})),xs==="editor"&&r&&requestAnimationFrame(()=>{try{Tr.commands.focus("end")}catch{}}),MI(t.theme||"light")},setMarkdown(t){var e;w3=!0;try{Tr.commands.setContent(t||"",{contentType:"markdown"})}catch{try{const r=(e=Tr.storage.markdown)==null?void 0:e.manager;if(r)Tr.commands.setContent(r.parse(t||""));else throw new Error("no markdown manager")}catch{Tr.commands.setContent({type:"doc",content:[{type:"paragraph",content:t?[{type:"text",text:t}]:[]}]})}}Tr.setEditable(xs==="editor"),w3=!1,MI(document.documentElement.dataset.theme||"light")},setDocumentFromJSON(t){w3=!0;try{const e=JSON.parse(t);Tr.commands.setContent(e)}catch{Tr.commands.setContent({type:"doc",content:[{type:"paragraph"}]})}Tr.setEditable(xs==="editor"),w3=!1,MI(document.documentElement.dataset.theme||"light")},resolveResource(t,e){const r=V8.get(t);r&&(V8.delete(t),r(e))},getMarkdown(){return O2e(Tr)},getDocument(){return JSON.stringify(Tr.getJSON())},captureSelection(){const t=Xct(Tr);return t?(OT={from:t.from,to:t.to,isInline:t.isInline,documentFingerprint:JSON.stringify(Tr.getJSON())},JSON.stringify({from:t.from,to:t.to,markdown:t.markdown,text:t.text})):(OT=null,null)},applySelectionDraft(t,e){var s,o;const r=OT;if(!r||!t.trim())return!1;if(JSON.stringify(Tr.getJSON())!==r.documentFingerprint)return OT=null,!1;const n=Tr.state.doc.content.size,i=Math.min(Math.max(r.from,0),n),a=Math.min(Math.max(r.to,i),n);try{const l=(s=Tr.storage.markdown)==null?void 0:s.manager,u=(o=l==null?void 0:l.parse)==null?void 0:o.call(l,t),h=e==="replace"?jct(Tr,t,r.isInline):(u==null?void 0:u.content)??t,d=e==="append"?{from:a,to:a}:{from:i,to:a};return Tr.chain().focus().insertContentAt(d,h).run(),OT=null,Vh(Tr),!0}catch{return!1}},undo(){if(!Tr.can().undo())return!1;const t=Tr.commands.undo();return t&&Vh(Tr),t},focusEnd(){var t;try{Tr.commands.focus("end")}catch{}try{const e=(t=Tr.view)==null?void 0:t.dom;e&&typeof e.focus=="function"&&e.focus({preventScroll:!0})}catch{}},flush(){Vh(Tr)},exec(t){var r;const e={bold:()=>Tr.chain().focus().toggleBold().run(),bulletList:()=>Tr.chain().focus().toggleBulletList().run(),taskList:()=>Tr.chain().focus().toggleTaskList().run(),blockquote:()=>Tr.chain().focus().toggleBlockquote().run(),horizontalRule:()=>Tr.chain().focus().setHorizontalRule().run(),heading2:()=>Tr.chain().focus().toggleHeading({level:2}).run(),codeBlock:()=>Tr.chain().focus().toggleCodeBlock().run()};(r=e[t])==null||r.call(e),Vh(Tr)},beginImageUpload(t,e){Tr.chain().focus().setImage({src:e,alt:t}).run();const r=Ql.querySelectorAll("img"),n=r[r.length-1];n&&(n.dataset.uploadId=t),Vh(Tr)},completeImageUpload(t,e,r){Tr.chain().focus().setImage({src:e,alt:r||t||""}).run();const n=Ql.querySelectorAll("img"),i=n[n.length-1];i&&(i.dataset.originalSrc=e,delete i.dataset.uploadId),Vh(Tr)},cancelImageUpload(t){const e=Ql.querySelector(`img[data-upload-id="${t}"]`);e==null||e.remove(),Vh(Tr)},search(t,e){const r=Kct(Tr,t),n=r.length>0?Math.min(Math.max(Number.isFinite(e)?e:0,0),r.length-1):0,i=r[n];if(i){Tr.commands.setTextSelection({from:i.from,to:i.to});try{const a=Tr.view.domAtPos(i.from).node,s=a instanceof Element?a:a.parentElement;s==null||s.scrollIntoView({block:"center",behavior:"smooth"})}catch{}}Ss({type:"searchResult",count:r.length,index:n})}};window.EdgeEverEditor=Qct;$2e(!1);Ss({type:"ready",startupMs:Math.round(performance.now()-Oct)});class Bt extends Error{constructor(e,r){var n="KaTeX parse error: "+e,i,a,s=r&&r.loc;if(s&&s.start<=s.end){var o=s.lexer.input;i=s.start,a=s.end,i===o.length?n+=" at end of input: ":n+=" at position "+(i+1)+": ";var l=o.slice(i,a).replace(/[^]/g,"$&̲"),u;i>15?u="…"+o.slice(i-15,i):u=o.slice(0,i);var h;a+15<o.length?h=o.slice(a,a+15)+"…":h=o.slice(a),n+=u+l+h}super(n),this.name="ParseError",this.position=void 0,this.length=void 0,this.rawMessage=void 0,Object.setPrototypeOf(this,Bt.prototype),this.position=i,i!=null&&a!=null&&(this.length=a-i),this.rawMessage=e}}var Jct=/([A-Z])/g,eut=t=>t.replace(Jct,"-$1").toLowerCase(),tut={"&":"&",">":">","<":"<",'"':""","'":"'"},rut=/[&><"']/g,Gs=t=>String(t).replace(rut,e=>tut[e]),US=t=>t.type==="ordgroup"||t.type==="color"?t.body.length===1?US(t.body[0]):t:t.type==="font"?US(t.body):t,nut=new Set(["mathord","textord","atom"]),Gd=t=>nut.has(US(t).type),iut=t=>{var e=/^[\x00-\x20]*([^\\/#?]*?)(:|�*58|�*3a|&colon)/i.exec(t);return e?e[2]!==":"||!/^[a-zA-Z][a-zA-Z0-9+\-.]*$/.test(e[1])?null:e[1].toLowerCase():"_relative"},q8={displayMode:{type:"boolean",description:"Render math in display mode, which puts the math in display style (so \\int and \\sum are large, for example), and centers the math on the page on its own line.",cli:"-d, --display-mode"},output:{type:{enum:["htmlAndMathml","html","mathml"]},description:"Determines the markup language of the output.",cli:"-F, --format <type>"},leqno:{type:"boolean",description:"Render display math in leqno style (left-justified tags)."},fleqn:{type:"boolean",description:"Render display math flush left."},throwOnError:{type:"boolean",default:!0,cli:"-t, --no-throw-on-error",cliDescription:"Render errors (in the color given by --error-color) instead of throwing a ParseError exception when encountering an error."},errorColor:{type:"string",default:"#cc0000",cli:"-c, --error-color <color>",cliDescription:"A color string given in the format 'rgb' or 'rrggbb' (no #). This option determines the color of errors rendered by the -t option.",cliProcessor:t=>"#"+t},macros:{type:"object",cli:"-m, --macro <def>",cliDescription:"Define custom macro of the form '\\foo:expansion' (use multiple -m arguments for multiple macros).",cliDefault:[],cliProcessor:(t,e)=>(e.push(t),e)},minRuleThickness:{type:"number",description:"Specifies a minimum thickness, in ems, for fraction lines, `\\sqrt` top lines, `{array}` vertical lines, `\\hline`, `\\hdashline`, `\\underline`, `\\overline`, and the borders of `\\fbox`, `\\boxed`, and `\\fcolorbox`.",processor:t=>Math.max(0,t),cli:"--min-rule-thickness <size>",cliProcessor:parseFloat},colorIsTextColor:{type:"boolean",description:"Makes \\color behave like LaTeX's 2-argument \\textcolor, instead of LaTeX's one-argument \\color mode change.",cli:"-b, --color-is-text-color"},strict:{type:[{enum:["warn","ignore","error"]},"boolean","function"],description:"Turn on strict / LaTeX faithfulness mode, which throws an error if the input uses features that are not supported by LaTeX.",cli:"-S, --strict",cliDefault:!1},trust:{type:["boolean","function"],description:"Trust the input, enabling all HTML features such as \\url.",cli:"-T, --trust"},maxSize:{type:"number",default:1/0,description:"If non-zero, all user-specified sizes, e.g. in \\rule{500em}{500em}, will be capped to maxSize ems. Otherwise, elements and spaces can be arbitrarily large",processor:t=>Math.max(0,t),cli:"-s, --max-size <n>",cliProcessor:parseInt},maxExpand:{type:"number",default:1e3,description:"Limit the number of macro expansions to the specified number, to prevent e.g. infinite macro loops. If set to Infinity, the macro expander will try to fully expand as in LaTeX.",processor:t=>Math.max(0,t),cli:"-e, --max-expand <n>",cliProcessor:t=>t==="Infinity"?1/0:parseInt(t)},globalGroup:{type:"boolean",cli:!1}};function aut(t){if(typeof t!="string")return t.enum[0];switch(t){case"boolean":return!1;case"string":return"";case"number":return 0;case"object":return{};default:throw new Error("Unexpected schema type; settings must declare an explicit default.")}}function sut(t){if(t.default!==void 0)return t.default;var e=Array.isArray(t.type)?t.type[0]:t.type;return aut(e)}function out(t,e,r,n){var i=r[e];t[e]=i!==void 0?n.processor?n.processor(i):i:sut(n)}class Kq{constructor(e){e===void 0&&(e={}),this.displayMode=void 0,this.output=void 0,this.leqno=void 0,this.fleqn=void 0,this.throwOnError=void 0,this.errorColor=void 0,this.macros=void 0,this.minRuleThickness=void 0,this.colorIsTextColor=void 0,this.strict=void 0,this.trust=void 0,this.maxSize=void 0,this.maxExpand=void 0,this.globalGroup=void 0,e=e||{};for(var r of Object.keys(q8)){var n=q8[r];n&&out(this,r,e,n)}}reportNonstrict(e,r,n){var i=this.strict;if(typeof i=="function"&&(i=i(e,r,n)),!(!i||i==="ignore")){if(i===!0||i==="error")throw new Bt("LaTeX-incompatible input and strict mode is set to 'error': "+(r+" ["+e+"]"),n);i==="warn"?typeof console<"u"&&console.warn("LaTeX-incompatible input and strict mode is set to 'warn': "+(r+" ["+e+"]")):typeof console<"u"&&console.warn("LaTeX-incompatible input and strict mode is set to "+("unrecognized '"+i+"': "+r+" ["+e+"]"))}}useStrictBehavior(e,r,n){var i=this.strict;if(typeof i=="function")try{i=i(e,r,n)}catch{i="error"}return!i||i==="ignore"?!1:i===!0||i==="error"?!0:i==="warn"?(typeof console<"u"&&console.warn("LaTeX-incompatible input and strict mode is set to 'warn': "+(r+" ["+e+"]")),!1):(typeof console<"u"&&console.warn("LaTeX-incompatible input and strict mode is set to "+("unrecognized '"+i+"': "+r+" ["+e+"]")),!1)}isTrusted(e){if("url"in e&&e.url&&!e.protocol){var r=iut(e.url);if(r==null)return!1;e.protocol=r}var n=typeof this.trust=="function"?this.trust(e):this.trust;return!!n}}class hf{constructor(e,r,n){this.id=void 0,this.size=void 0,this.cramped=void 0,this.id=e,this.size=r,this.cramped=n}sup(){return Au[lut[this.id]]}sub(){return Au[cut[this.id]]}fracNum(){return Au[uut[this.id]]}fracDen(){return Au[hut[this.id]]}cramp(){return Au[dut[this.id]]}text(){return Au[fut[this.id]]}isTight(){return this.size>=2}}var Zq=0,W8=1,Oy=2,fd=3,vw=4,Jl=5,t4=6,mo=7,Au=[new hf(Zq,0,!1),new hf(W8,0,!0),new hf(Oy,1,!1),new hf(fd,1,!0),new hf(vw,2,!1),new hf(Jl,2,!0),new hf(t4,3,!1),new hf(mo,3,!0)],lut=[vw,Jl,vw,Jl,t4,mo,t4,mo],cut=[Jl,Jl,Jl,Jl,mo,mo,mo,mo],uut=[Oy,fd,vw,Jl,t4,mo,t4,mo],hut=[fd,fd,Jl,Jl,mo,mo,mo,mo],dut=[W8,W8,fd,fd,Jl,Jl,mo,mo],fut=[Zq,W8,Oy,fd,Oy,fd,Oy,fd],Zr={DISPLAY:Au[Zq],TEXT:Au[Oy],SCRIPT:Au[vw],SCRIPTSCRIPT:Au[t4]},$P=[{name:"latin",blocks:[[256,591],[768,879]]},{name:"cyrillic",blocks:[[1024,1279]]},{name:"armenian",blocks:[[1328,1423]]},{name:"brahmic",blocks:[[2304,4255]]},{name:"georgian",blocks:[[4256,4351]]},{name:"cjk",blocks:[[12288,12543],[19968,40879],[65280,65376]]},{name:"hangul",blocks:[[44032,55215]]}];function put(t){for(var e=0;e<$P.length;e++)for(var r=$P[e],n=0;n<r.blocks.length;n++){var i=r.blocks[n];if(t>=i[0]&&t<=i[1])return r.name}return null}var YS=[];$P.forEach(t=>t.blocks.forEach(e=>YS.push(...e)));function P2e(t){for(var e=0;e<YS.length;e+=2)if(t>=YS[e]&&t<=YS[e+1])return!0;return!1}var La=t=>t+" "+t,f1=80,gut=function(e,r){return"M95,"+(622+e+r)+`c-2.7,0,-7.17,-2.7,-13.5,-8c-5.8,-5.3,-9.5,-10,-9.5,-14c0,-2,0.3,-3.3,1,-4c1.3,-2.7,23.83,-20.7,67.5,-54c44.2,-33.3,65.8,-50.3,66.5,-51c1.3,-1.3,3,-2,5,-2c4.7,0,8.7,3.3,12,10diff --git a/apps/ios/EditorBundle/index.html b/apps/ios/EditorBundle/index.htmlindex f78ab0bb..aae23a62 100644--- a/apps/ios/EditorBundle/index.html+++ b/apps/ios/EditorBundle/index.html@@ -814,7 +814,7 @@ l0,-`+(r+144)+`c-2,-159.3,-10,-310.7,-24,-454c-53.3,-528,-210,-949.7,`)},LI="edgeever-inline-sentinel",Yct=(t,e,r)=>{var i;const n=(i=t.storage.markdown)==null?void 0:i.manager;return n!=null&&n.serialize?n.serialize($_({type:"doc",content:[{type:"paragraph",content:e}]})).replaceAll(O_,"\\$"):r},Xct=t=>{const e=t.state.selection;if(e.empty||e.from>=e.to)return null;const r=[];if(t.state.doc.nodesBetween(e.from,e.to,(i,a)=>{if(!i.isTextblock)return!0;const s=a+1,o=s+i.content.size,l=Math.max(e.from,s),u=Math.min(e.to,o);return u>l&&r.push({node:i,contentFrom:s,contentTo:o,from:l,to:u}),!1}),r.length===1){const i=r[0],a=i.node.cut(i.from-i.contentFrom,i.to-i.contentFrom).toJSON(),s=t.state.doc.textBetween(i.from,i.to,``),o=Yct(t,a.content??[],s).trim();return o?{from:i.from,to:i.to,isInline:!0,markdown:o,text:s}:null}const n=Uct(t,e.from,e.to).trim();return n?{from:e.from,to:e.to,isInline:!1,markdown:n,text:t.state.doc.textBetween(e.from,e.to,`-`)}:null},jct=(t,e,r)=>{var f,p,g;const n=(f=t.storage.markdown)==null?void 0:f.manager,i=e.trim(),a=((p=n==null?void 0:n.parse)==null?void 0:p.call(n,i).content)??[{type:"text",text:i}];if(!r)return a;const s=i.replace(/\s*\n+\s*/g," "),o=(g=n==null?void 0:n.parse)==null?void 0:g.call(n,`${LI}${s}`).content,l=(o==null?void 0:o.length)===1?o[0]:null,u=(l==null?void 0:l.type)==="paragraph"?l.content??[]:[],h=u[0];if((h==null?void 0:h.type)!=="text"||typeof h.text!="string"||!h.text.startsWith(LI))return[{type:"text",text:s}];const d=h.text.slice(LI.length);return[...d?[{...h,text:d}]:[],...u.slice(1)]};function Vh(t){try{const e=JSON.stringify(t.getJSON()),r=O2e(t);Ss({type:"change",contentMarkdown:r,contentJson:e})}catch(e){Ss({type:"error",message:e instanceof Error?e.message:String(e)})}}function Kct(t,e){const r=e.trim().toLocaleLowerCase();if(r.length===0)return[];const n=[];let i=null;t.state.doc.descendants((l,u)=>{if(!(!l.isText||!l.text)){i!==null&&u>i&&n.push({char:"\0",pos:-1});for(let h=0;h<l.text.length;h+=1)n.push({char:l.text[h]??"",pos:u+h});i=u+l.text.length}});const a=n.map(l=>l.char).join("").toLocaleLowerCase(),s=[];let o=a.indexOf(r);for(;o!==-1;){const l=n[o],u=n[o+r.length-1];l&&u&&l.pos>=0&&u.pos>=0&&s.push({from:l.pos,to:u.pos+1}),o=a.indexOf(r,o+r.length)}return s}const xte=()=>Tr.isActive("taskItem")?"taskItem":"listItem";function $2e(t){var r;if(WS.classList.toggle("editor-mode",t),WS.innerHTML="",!t)return;const e=[{id:"image",label:"▧+",run:()=>Ss({type:"pickImage"})},{id:"bold",label:"B",run:()=>Tr.chain().focus().toggleBold().run()},{id:"bullet",label:"•",run:()=>Tr.chain().focus().toggleBulletList().run()},{id:"task",label:"☑",run:()=>Tr.chain().focus().toggleTaskList().run()},{id:"indent",label:"⇥",run:()=>Tr.chain().focus().sinkListItem(xte()).run()},{id:"outdent",label:"⇤",run:()=>Tr.chain().focus().liftListItem(xte()).run()},{id:"quote",label:"❝",run:()=>Tr.chain().focus().toggleBlockquote().run()},{id:"hr",label:"—",run:()=>Tr.chain().focus().setHorizontalRule().run()}];for(const n of e){const i=document.createElement("button");i.type="button",i.textContent=n.label,i.dataset.action=n.id;const a={image:["插入图片","Insert image"],bold:["粗体","Bold"],bullet:["项目符号列表","Bullet list"],task:["任务清单","Task list"],indent:["增加列表缩进","Increase list indent"],outdent:["减少列表缩进","Decrease list indent"],quote:["引用","Block quote"],hr:["分隔线","Horizontal rule"]};i.setAttribute("aria-label",((r=a[n.id])==null?void 0:r[M2e==="en-US"?1:0])??n.id),i.addEventListener("click",()=>{n.run(),n.id!=="image"&&Vh(Tr),G8()}),WS.appendChild(i)}G8()}function G8(){const t={bold:Tr.isActive("bold"),bullet:Tr.isActive("bulletList"),task:Tr.isActive("taskList"),quote:Tr.isActive("blockquote")};WS.querySelectorAll("button[data-action]").forEach(e=>{e.classList.toggle("is-active",t[e.dataset.action??""]??!1)})}async function MI(t="light"){Ql.querySelectorAll("[data-placeholder]").forEach(e=>{e.dataset.placeholder=OP}),await Vct(Ql),xs==="viewer"&&await Hct(Ql,t)}async function Zct(t){var l;if(!t.requestId||t.format!=="png"&&t.format!=="jpeg")return;const e=document.createElement("div");e.style.cssText=`position:fixed;left:-100000px;top:0;width:${mte}px;pointer-events:none;`;const r=document.createElement("div");r.className="edgeever-image-document";const n=document.createElement("article");n.className="edgeever-image-card";const i=document.createElement("h1");i.className="edgeever-image-title",i.textContent=t.title||t.fallbackTitle,n.appendChild(i);const a=[t.notebook,t.updatedAt,...(t.tags??[]).map(u=>`#${u}`)].filter(Boolean);if(a.length>0){const u=document.createElement("div");u.className="edgeever-image-meta",u.textContent=a.join(" · "),n.appendChild(u)}const s=document.createElement("div");s.className="edgeever-image-content";const o=Tr.view.dom.cloneNode(!0);o.removeAttribute("contenteditable"),o.querySelectorAll("button, [contenteditable='true']").forEach(u=>{u.removeAttribute("contenteditable"),u instanceof HTMLButtonElement&&u.remove()}),s.appendChild(o),n.appendChild(s),r.appendChild(n),e.appendChild(r),document.body.appendChild(e);try{await((l=document.fonts)==null?void 0:l.ready),await Promise.all(Array.from(r.querySelectorAll("img")).map(async x=>{if(!x.complete)try{await x.decode()}catch{}}));const u=Math.max(1,Math.ceil(r.getBoundingClientRect().height)),h=await Aot(r,{backgroundColor:"#f8fafc",height:u,pixelRatio:$ct,skipFonts:!0,width:mte}),d=await new Promise((x,b)=>{h.toBlob(w=>w?x(w):b(new Error("Image renderer returned an empty file")),t.format==="jpeg"?"image/jpeg":"image/png",t.format==="jpeg"?.9:1)}),f=t.format==="jpeg"?"jpg":"png",p=Bct(t.title,t.fallbackTitle),g=await Fct(d),m=`${p}.${f}`,y=t.format==="jpeg"?"image/jpeg":"image/png",v=zct(g);for(let x=0;x<v.length;x+=yte)Ss({type:"imageExportChunk",requestId:t.requestId,chunk:v.slice(x,x+yte)}),await new Promise(b=>setTimeout(b,0));Ss({type:"imageExportComplete",requestId:t.requestId,filename:m,mimeType:y})}catch(u){Ss({type:"imageExportError",requestId:t.requestId,message:u instanceof Error?u.message:"Image export failed"})}finally{e.remove()}}const Qct={exportImage(t){Zct(t)},configure(t){const e=t.mode==="editor"?"editor":"viewer",r=e!==xs;xs=e,M2e=t.locale==="en-US"?"en-US":"zh-CN",Tr.setEditable(xs==="editor"),$2e(xs==="editor"),document.documentElement.dataset.theme=t.theme||"light",document.body.classList.toggle("viewer-mode",xs==="viewer"),document.body.classList.toggle("editor-mode",xs==="editor"),t.placeholder&&(OP=t.placeholder,Ql.querySelectorAll("[data-placeholder]").forEach(n=>{n.dataset.placeholder=OP})),xs==="editor"&&r&&requestAnimationFrame(()=>{try{Tr.commands.focus("end")}catch{}}),MI(t.theme||"light")},setMarkdown(t){var e;w3=!0;try{Tr.commands.setContent(t||"",{contentType:"markdown"})}catch{try{const r=(e=Tr.storage.markdown)==null?void 0:e.manager;if(r)Tr.commands.setContent(r.parse(t||""));else throw new Error("no markdown manager")}catch{Tr.commands.setContent({type:"doc",content:[{type:"paragraph",content:t?[{type:"text",text:t}]:[]}]})}}Tr.setEditable(xs==="editor"),w3=!1,MI(document.documentElement.dataset.theme||"light")},setDocumentFromJSON(t){w3=!0;try{const e=JSON.parse(t);Tr.commands.setContent(e)}catch{Tr.commands.setContent({type:"doc",content:[{type:"paragraph"}]})}Tr.setEditable(xs==="editor"),w3=!1,MI(document.documentElement.dataset.theme||"light")},resolveResource(t,e){const r=V8.get(t);r&&(V8.delete(t),r(e))},getMarkdown(){return O2e(Tr)},getDocument(){return JSON.stringify(Tr.getJSON())},captureSelection(){const t=Xct(Tr);return t?(OT={from:t.from,to:t.to,isInline:t.isInline,documentFingerprint:JSON.stringify(Tr.getJSON())},JSON.stringify({from:t.from,to:t.to,markdown:t.markdown,text:t.text})):(OT=null,null)},applySelectionDraft(t,e){var s,o;const r=OT;if(!r||!t.trim())return!1;if(JSON.stringify(Tr.getJSON())!==r.documentFingerprint)return OT=null,!1;const n=Tr.state.doc.content.size,i=Math.min(Math.max(r.from,0),n),a=Math.min(Math.max(r.to,i),n);try{const l=(s=Tr.storage.markdown)==null?void 0:s.manager,u=(o=l==null?void 0:l.parse)==null?void 0:o.call(l,t),h=e==="replace"?jct(Tr,t,r.isInline):(u==null?void 0:u.content)??t,d=e==="append"?{from:a,to:a}:{from:i,to:a};return Tr.chain().focus().insertContentAt(d,h).run(),OT=null,Vh(Tr),!0}catch{return!1}},undo(){if(!Tr.can().undo())return!1;const t=Tr.commands.undo();return t&&Vh(Tr),t},focusEnd(){var t;try{Tr.commands.focus("end")}catch{}try{const e=(t=Tr.view)==null?void 0:t.dom;e&&typeof e.focus=="function"&&e.focus({preventScroll:!0})}catch{}},flush(){Vh(Tr)},exec(t){var r;const e={bold:()=>Tr.chain().focus().toggleBold().run(),bulletList:()=>Tr.chain().focus().toggleBulletList().run(),taskList:()=>Tr.chain().focus().toggleTaskList().run(),blockquote:()=>Tr.chain().focus().toggleBlockquote().run(),horizontalRule:()=>Tr.chain().focus().setHorizontalRule().run(),heading2:()=>Tr.chain().focus().toggleHeading({level:2}).run(),codeBlock:()=>Tr.chain().focus().toggleCodeBlock().run()};(r=e[t])==null||r.call(e),Vh(Tr)},beginImageUpload(t,e){Tr.chain().focus().setImage({src:e,alt:t}).run();const r=Ql.querySelectorAll("img"),n=r[r.length-1];n&&(n.dataset.uploadId=t),Vh(Tr)},completeImageUpload(t,e,r){Tr.chain().focus().setImage({src:e,alt:r||t||""}).run();const n=Ql.querySelectorAll("img"),i=n[n.length-1];i&&(i.dataset.originalSrc=e,delete i.dataset.uploadId),Vh(Tr)},cancelImageUpload(t){const e=Ql.querySelector(`img[data-upload-id="${t}"]`);e==null||e.remove(),Vh(Tr)},search(t,e){const r=Kct(Tr,t),n=r.length>0?Math.min(Math.max(Number.isFinite(e)?e:0,0),r.length-1):0,i=r[n];if(i){Tr.commands.setTextSelection({from:i.from,to:i.to});try{const a=Tr.view.domAtPos(i.from).node,s=a instanceof Element?a:a.parentElement;s==null||s.scrollIntoView({block:"center",behavior:"smooth"})}catch{}}Ss({type:"searchResult",count:r.length,index:n})}};window.EdgeEverEditor=Qct;$2e(!1);Ss({type:"ready",startupMs:Math.round(performance.now()-Oct)});class Bt extends Error{constructor(e,r){var n="KaTeX parse error: "+e,i,a,s=r&&r.loc;if(s&&s.start<=s.end){var o=s.lexer.input;i=s.start,a=s.end,i===o.length?n+=" at end of input: ":n+=" at position "+(i+1)+": ";var l=o.slice(i,a).replace(/[^]/g,"$&̲"),u;i>15?u="…"+o.slice(i-15,i):u=o.slice(0,i);var h;a+15<o.length?h=o.slice(a,a+15)+"…":h=o.slice(a),n+=u+l+h}super(n),this.name="ParseError",this.position=void 0,this.length=void 0,this.rawMessage=void 0,Object.setPrototypeOf(this,Bt.prototype),this.position=i,i!=null&&a!=null&&(this.length=a-i),this.rawMessage=e}}var Jct=/([A-Z])/g,eut=t=>t.replace(Jct,"-$1").toLowerCase(),tut={"&":"&",">":">","<":"<",'"':""","'":"'"},rut=/[&><"']/g,Gs=t=>String(t).replace(rut,e=>tut[e]),US=t=>t.type==="ordgroup"||t.type==="color"?t.body.length===1?US(t.body[0]):t:t.type==="font"?US(t.body):t,nut=new Set(["mathord","textord","atom"]),Gd=t=>nut.has(US(t).type),iut=t=>{var e=/^[\x00-\x20]*([^\\/#?]*?)(:|�*58|�*3a|&colon)/i.exec(t);return e?e[2]!==":"||!/^[a-zA-Z][a-zA-Z0-9+\-.]*$/.test(e[1])?null:e[1].toLowerCase():"_relative"},q8={displayMode:{type:"boolean",description:"Render math in display mode, which puts the math in display style (so \\int and \\sum are large, for example), and centers the math on the page on its own line.",cli:"-d, --display-mode"},output:{type:{enum:["htmlAndMathml","html","mathml"]},description:"Determines the markup language of the output.",cli:"-F, --format <type>"},leqno:{type:"boolean",description:"Render display math in leqno style (left-justified tags)."},fleqn:{type:"boolean",description:"Render display math flush left."},throwOnError:{type:"boolean",default:!0,cli:"-t, --no-throw-on-error",cliDescription:"Render errors (in the color given by --error-color) instead of throwing a ParseError exception when encountering an error."},errorColor:{type:"string",default:"#cc0000",cli:"-c, --error-color <color>",cliDescription:"A color string given in the format 'rgb' or 'rrggbb' (no #). This option determines the color of errors rendered by the -t option.",cliProcessor:t=>"#"+t},macros:{type:"object",cli:"-m, --macro <def>",cliDescription:"Define custom macro of the form '\\foo:expansion' (use multiple -m arguments for multiple macros).",cliDefault:[],cliProcessor:(t,e)=>(e.push(t),e)},minRuleThickness:{type:"number",description:"Specifies a minimum thickness, in ems, for fraction lines, `\\sqrt` top lines, `{array}` vertical lines, `\\hline`, `\\hdashline`, `\\underline`, `\\overline`, and the borders of `\\fbox`, `\\boxed`, and `\\fcolorbox`.",processor:t=>Math.max(0,t),cli:"--min-rule-thickness <size>",cliProcessor:parseFloat},colorIsTextColor:{type:"boolean",description:"Makes \\color behave like LaTeX's 2-argument \\textcolor, instead of LaTeX's one-argument \\color mode change.",cli:"-b, --color-is-text-color"},strict:{type:[{enum:["warn","ignore","error"]},"boolean","function"],description:"Turn on strict / LaTeX faithfulness mode, which throws an error if the input uses features that are not supported by LaTeX.",cli:"-S, --strict",cliDefault:!1},trust:{type:["boolean","function"],description:"Trust the input, enabling all HTML features such as \\url.",cli:"-T, --trust"},maxSize:{type:"number",default:1/0,description:"If non-zero, all user-specified sizes, e.g. in \\rule{500em}{500em}, will be capped to maxSize ems. Otherwise, elements and spaces can be arbitrarily large",processor:t=>Math.max(0,t),cli:"-s, --max-size <n>",cliProcessor:parseInt},maxExpand:{type:"number",default:1e3,description:"Limit the number of macro expansions to the specified number, to prevent e.g. infinite macro loops. If set to Infinity, the macro expander will try to fully expand as in LaTeX.",processor:t=>Math.max(0,t),cli:"-e, --max-expand <n>",cliProcessor:t=>t==="Infinity"?1/0:parseInt(t)},globalGroup:{type:"boolean",cli:!1}};function aut(t){if(typeof t!="string")return t.enum[0];switch(t){case"boolean":return!1;case"string":return"";case"number":return 0;case"object":return{};default:throw new Error("Unexpected schema type; settings must declare an explicit default.")}}function sut(t){if(t.default!==void 0)return t.default;var e=Array.isArray(t.type)?t.type[0]:t.type;return aut(e)}function out(t,e,r,n){var i=r[e];t[e]=i!==void 0?n.processor?n.processor(i):i:sut(n)}class Kq{constructor(e){e===void 0&&(e={}),this.displayMode=void 0,this.output=void 0,this.leqno=void 0,this.fleqn=void 0,this.throwOnError=void 0,this.errorColor=void 0,this.macros=void 0,this.minRuleThickness=void 0,this.colorIsTextColor=void 0,this.strict=void 0,this.trust=void 0,this.maxSize=void 0,this.maxExpand=void 0,this.globalGroup=void 0,e=e||{};for(var r of Object.keys(q8)){var n=q8[r];n&&out(this,r,e,n)}}reportNonstrict(e,r,n){var i=this.strict;if(typeof i=="function"&&(i=i(e,r,n)),!(!i||i==="ignore")){if(i===!0||i==="error")throw new Bt("LaTeX-incompatible input and strict mode is set to 'error': "+(r+" ["+e+"]"),n);i==="warn"?typeof console<"u"&&console.warn("LaTeX-incompatible input and strict mode is set to 'warn': "+(r+" ["+e+"]")):typeof console<"u"&&console.warn("LaTeX-incompatible input and strict mode is set to "+("unrecognized '"+i+"': "+r+" ["+e+"]"))}}useStrictBehavior(e,r,n){var i=this.strict;if(typeof i=="function")try{i=i(e,r,n)}catch{i="error"}return!i||i==="ignore"?!1:i===!0||i==="error"?!0:i==="warn"?(typeof console<"u"&&console.warn("LaTeX-incompatible input and strict mode is set to 'warn': "+(r+" ["+e+"]")),!1):(typeof console<"u"&&console.warn("LaTeX-incompatible input and strict mode is set to "+("unrecognized '"+i+"': "+r+" ["+e+"]")),!1)}isTrusted(e){if("url"in e&&e.url&&!e.protocol){var r=iut(e.url);if(r==null)return!1;e.protocol=r}var n=typeof this.trust=="function"?this.trust(e):this.trust;return!!n}}class hf{constructor(e,r,n){this.id=void 0,this.size=void 0,this.cramped=void 0,this.id=e,this.size=r,this.cramped=n}sup(){return Au[lut[this.id]]}sub(){return Au[cut[this.id]]}fracNum(){return Au[uut[this.id]]}fracDen(){return Au[hut[this.id]]}cramp(){return Au[dut[this.id]]}text(){return Au[fut[this.id]]}isTight(){return this.size>=2}}var Zq=0,W8=1,Oy=2,fd=3,vw=4,Jl=5,t4=6,mo=7,Au=[new hf(Zq,0,!1),new hf(W8,0,!0),new hf(Oy,1,!1),new hf(fd,1,!0),new hf(vw,2,!1),new hf(Jl,2,!0),new hf(t4,3,!1),new hf(mo,3,!0)],lut=[vw,Jl,vw,Jl,t4,mo,t4,mo],cut=[Jl,Jl,Jl,Jl,mo,mo,mo,mo],uut=[Oy,fd,vw,Jl,t4,mo,t4,mo],hut=[fd,fd,Jl,Jl,mo,mo,mo,mo],dut=[W8,W8,fd,fd,Jl,Jl,mo,mo],fut=[Zq,W8,Oy,fd,Oy,fd,Oy,fd],Zr={DISPLAY:Au[Zq],TEXT:Au[Oy],SCRIPT:Au[vw],SCRIPTSCRIPT:Au[t4]},$P=[{name:"latin",blocks:[[256,591],[768,879]]},{name:"cyrillic",blocks:[[1024,1279]]},{name:"armenian",blocks:[[1328,1423]]},{name:"brahmic",blocks:[[2304,4255]]},{name:"georgian",blocks:[[4256,4351]]},{name:"cjk",blocks:[[12288,12543],[19968,40879],[65280,65376]]},{name:"hangul",blocks:[[44032,55215]]}];function put(t){for(var e=0;e<$P.length;e++)for(var r=$P[e],n=0;n<r.blocks.length;n++){var i=r.blocks[n];if(t>=i[0]&&t<=i[1])return r.name}return null}var YS=[];$P.forEach(t=>t.blocks.forEach(e=>YS.push(...e)));function P2e(t){for(var e=0;e<YS.length;e+=2)if(t>=YS[e]&&t<=YS[e+1])return!0;return!1}var La=t=>t+" "+t,f1=80,gut=function(e,r){return"M95,"+(622+e+r)+`+`)}:null},jct=(t,e,r)=>{var f,p,g;const n=(f=t.storage.markdown)==null?void 0:f.manager,i=e.trim(),a=((p=n==null?void 0:n.parse)==null?void 0:p.call(n,i).content)??[{type:"text",text:i}];if(!r)return a;const s=i.replace(/\s*\n+\s*/g," "),o=(g=n==null?void 0:n.parse)==null?void 0:g.call(n,`${LI}${s}`).content,l=(o==null?void 0:o.length)===1?o[0]:null,u=(l==null?void 0:l.type)==="paragraph"?l.content??[]:[],h=u[0];if((h==null?void 0:h.type)!=="text"||typeof h.text!="string"||!h.text.startsWith(LI))return[{type:"text",text:s}];const d=h.text.slice(LI.length);return[...d?[{...h,text:d}]:[],...u.slice(1)]};function Vh(t){try{const e=JSON.stringify(t.getJSON()),r=O2e(t);Ss({type:"change",contentMarkdown:r,contentJson:e})}catch(e){Ss({type:"error",message:e instanceof Error?e.message:String(e)})}}function Kct(t,e){const r=e.trim().toLocaleLowerCase();if(r.length===0)return[];const n=[];let i=null;t.state.doc.descendants((l,u)=>{if(!(!l.isText||!l.text)){i!==null&&u>i&&n.push({char:"\0",pos:-1});for(let h=0;h<l.text.length;h+=1)n.push({char:l.text[h]??"",pos:u+h});i=u+l.text.length}});const a=n.map(l=>l.char).join("").toLocaleLowerCase(),s=[];let o=a.indexOf(r);for(;o!==-1;){const l=n[o],u=n[o+r.length-1];l&&u&&l.pos>=0&&u.pos>=0&&s.push({from:l.pos,to:u.pos+1}),o=a.indexOf(r,o+r.length)}return s}const xte=()=>Tr.isActive("taskItem")?"taskItem":"listItem";function $2e(t){var r;if(WS.classList.toggle("editor-mode",t),WS.innerHTML="",!t)return;const e=[{id:"image",label:"▧+",run:()=>Ss({type:"pickImage"})},{id:"bold",label:"B",run:()=>Tr.chain().focus().toggleBold().run()},{id:"bullet",label:"•",run:()=>Tr.chain().focus().toggleBulletList().run()},{id:"task",label:"☑",run:()=>Tr.chain().focus().toggleTaskList().run()},{id:"indent",label:"⇥",run:()=>Tr.chain().focus().sinkListItem(xte()).run()},{id:"outdent",label:"⇤",run:()=>Tr.chain().focus().liftListItem(xte()).run()},{id:"quote",label:"❝",run:()=>Tr.chain().focus().toggleBlockquote().run()},{id:"hr",label:"—",run:()=>Tr.chain().focus().setHorizontalRule().run()}];for(const n of e){const i=document.createElement("button");i.type="button",i.textContent=n.label,i.dataset.action=n.id;const a={image:["插入图片","Insert image"],bold:["粗体","Bold"],bullet:["项目符号列表","Bullet list"],task:["任务清单","Task list"],indent:["增加列表缩进","Increase list indent"],outdent:["减少列表缩进","Decrease list indent"],quote:["引用","Block quote"],hr:["分隔线","Horizontal rule"]};i.setAttribute("aria-label",((r=a[n.id])==null?void 0:r[M2e==="en-US"?1:0])??n.id),i.addEventListener("click",()=>{n.run(),n.id!=="image"&&Vh(Tr),G8()}),WS.appendChild(i)}G8()}function G8(){const t={bold:Tr.isActive("bold"),bullet:Tr.isActive("bulletList"),task:Tr.isActive("taskList"),quote:Tr.isActive("blockquote")};WS.querySelectorAll("button[data-action]").forEach(e=>{e.classList.toggle("is-active",t[e.dataset.action??""]??!1)})}async function MI(t="light"){Ql.querySelectorAll("[data-placeholder]").forEach(e=>{e.dataset.placeholder=OP}),await Vct(Ql),xs==="viewer"&&await Hct(Ql,t)}async function Zct(t){var l;if(!t.requestId||t.format!=="png"&&t.format!=="jpeg")return;const e=document.createElement("div");e.style.cssText=`position:fixed;left:-100000px;top:0;width:${mte}px;pointer-events:none;`;const r=document.createElement("div");r.className="edgeever-image-document";const n=document.createElement("article");n.className="edgeever-image-card";const i=document.createElement("h1");i.className="edgeever-image-title",i.textContent=t.title||t.fallbackTitle,n.appendChild(i);const a=[t.notebook,t.updatedAt,...(t.tags??[]).map(u=>`#${u}`)].filter(Boolean);if(a.length>0){const u=document.createElement("div");u.className="edgeever-image-meta",u.textContent=a.join(" · "),n.appendChild(u)}const s=document.createElement("div");s.className="edgeever-image-content";const o=Tr.view.dom.cloneNode(!0);o.removeAttribute("contenteditable"),o.querySelectorAll("button, [contenteditable='true']").forEach(u=>{u.removeAttribute("contenteditable"),u instanceof HTMLButtonElement&&u.remove()}),s.appendChild(o),n.appendChild(s),r.appendChild(n),e.appendChild(r),document.body.appendChild(e);try{await((l=document.fonts)==null?void 0:l.ready),await Promise.all(Array.from(r.querySelectorAll("img")).map(async b=>{if(!b.complete)try{await b.decode()}catch{}}));const u=Math.max(1,Math.ceil(r.getBoundingClientRect().height)),h={mint:"#ecfdf5",slate:"#f8fafc",warm:"#fffbeb"}[t.background??"slate"];r.style.backgroundColor=h;const d=await Aot(r,{backgroundColor:h,height:u,pixelRatio:$ct,skipFonts:!0,width:mte}),f=await new Promise((b,w)=>{d.toBlob(k=>k?b(k):w(new Error("Image renderer returned an empty file")),t.format==="jpeg"?"image/jpeg":"image/png",t.format==="jpeg"?.9:1)}),p=t.format==="jpeg"?"jpg":"png",g=Bct(t.title,t.fallbackTitle),m=await Fct(f),y=`${g}.${p}`,v=t.format==="jpeg"?"image/jpeg":"image/png",x=zct(m);for(let b=0;b<x.length;b+=yte)Ss({type:"imageExportChunk",requestId:t.requestId,chunk:x.slice(b,b+yte)}),await new Promise(w=>setTimeout(w,0));Ss({type:"imageExportComplete",requestId:t.requestId,filename:y,mimeType:v})}catch(u){Ss({type:"imageExportError",requestId:t.requestId,message:u instanceof Error?u.message:"Image export failed"})}finally{e.remove()}}const Qct={exportImage(t){Zct(t)},configure(t){const e=t.mode==="editor"?"editor":"viewer",r=e!==xs;xs=e,M2e=t.locale==="en-US"?"en-US":"zh-CN",Tr.setEditable(xs==="editor"),$2e(xs==="editor"),document.documentElement.dataset.theme=t.theme||"light",document.body.classList.toggle("viewer-mode",xs==="viewer"),document.body.classList.toggle("editor-mode",xs==="editor"),t.placeholder&&(OP=t.placeholder,Ql.querySelectorAll("[data-placeholder]").forEach(n=>{n.dataset.placeholder=OP})),xs==="editor"&&r&&requestAnimationFrame(()=>{try{Tr.commands.focus("end")}catch{}}),MI(t.theme||"light")},setMarkdown(t){var e;w3=!0;try{Tr.commands.setContent(t||"",{contentType:"markdown"})}catch{try{const r=(e=Tr.storage.markdown)==null?void 0:e.manager;if(r)Tr.commands.setContent(r.parse(t||""));else throw new Error("no markdown manager")}catch{Tr.commands.setContent({type:"doc",content:[{type:"paragraph",content:t?[{type:"text",text:t}]:[]}]})}}Tr.setEditable(xs==="editor"),w3=!1,MI(document.documentElement.dataset.theme||"light")},setDocumentFromJSON(t){w3=!0;try{const e=JSON.parse(t);Tr.commands.setContent(e)}catch{Tr.commands.setContent({type:"doc",content:[{type:"paragraph"}]})}Tr.setEditable(xs==="editor"),w3=!1,MI(document.documentElement.dataset.theme||"light")},resolveResource(t,e){const r=V8.get(t);r&&(V8.delete(t),r(e))},getMarkdown(){return O2e(Tr)},getDocument(){return JSON.stringify(Tr.getJSON())},captureSelection(){const t=Xct(Tr);return t?(OT={from:t.from,to:t.to,isInline:t.isInline,documentFingerprint:JSON.stringify(Tr.getJSON())},JSON.stringify({from:t.from,to:t.to,markdown:t.markdown,text:t.text})):(OT=null,null)},applySelectionDraft(t,e){var s,o;const r=OT;if(!r||!t.trim())return!1;if(JSON.stringify(Tr.getJSON())!==r.documentFingerprint)return OT=null,!1;const n=Tr.state.doc.content.size,i=Math.min(Math.max(r.from,0),n),a=Math.min(Math.max(r.to,i),n);try{const l=(s=Tr.storage.markdown)==null?void 0:s.manager,u=(o=l==null?void 0:l.parse)==null?void 0:o.call(l,t),h=e==="replace"?jct(Tr,t,r.isInline):(u==null?void 0:u.content)??t,d=e==="append"?{from:a,to:a}:{from:i,to:a};return Tr.chain().focus().insertContentAt(d,h).run(),OT=null,Vh(Tr),!0}catch{return!1}},undo(){if(!Tr.can().undo())return!1;const t=Tr.commands.undo();return t&&Vh(Tr),t},focusEnd(){var t;try{Tr.commands.focus("end")}catch{}try{const e=(t=Tr.view)==null?void 0:t.dom;e&&typeof e.focus=="function"&&e.focus({preventScroll:!0})}catch{}},flush(){Vh(Tr)},exec(t){var r;const e={bold:()=>Tr.chain().focus().toggleBold().run(),bulletList:()=>Tr.chain().focus().toggleBulletList().run(),taskList:()=>Tr.chain().focus().toggleTaskList().run(),blockquote:()=>Tr.chain().focus().toggleBlockquote().run(),horizontalRule:()=>Tr.chain().focus().setHorizontalRule().run(),heading2:()=>Tr.chain().focus().toggleHeading({level:2}).run(),codeBlock:()=>Tr.chain().focus().toggleCodeBlock().run()};(r=e[t])==null||r.call(e),Vh(Tr)},beginImageUpload(t,e){Tr.chain().focus().setImage({src:e,alt:t}).run();const r=Ql.querySelectorAll("img"),n=r[r.length-1];n&&(n.dataset.uploadId=t),Vh(Tr)},completeImageUpload(t,e,r){Tr.chain().focus().setImage({src:e,alt:r||t||""}).run();const n=Ql.querySelectorAll("img"),i=n[n.length-1];i&&(i.dataset.originalSrc=e,delete i.dataset.uploadId),Vh(Tr)},cancelImageUpload(t){const e=Ql.querySelector(`img[data-upload-id="${t}"]`);e==null||e.remove(),Vh(Tr)},search(t,e){const r=Kct(Tr,t),n=r.length>0?Math.min(Math.max(Number.isFinite(e)?e:0,0),r.length-1):0,i=r[n];if(i){Tr.commands.setTextSelection({from:i.from,to:i.to});try{const a=Tr.view.domAtPos(i.from).node,s=a instanceof Element?a:a.parentElement;s==null||s.scrollIntoView({block:"center",behavior:"smooth"})}catch{}}Ss({type:"searchResult",count:r.length,index:n})}};window.EdgeEverEditor=Qct;$2e(!1);Ss({type:"ready",startupMs:Math.round(performance.now()-Oct)});class Bt extends Error{constructor(e,r){var n="KaTeX parse error: "+e,i,a,s=r&&r.loc;if(s&&s.start<=s.end){var o=s.lexer.input;i=s.start,a=s.end,i===o.length?n+=" at end of input: ":n+=" at position "+(i+1)+": ";var l=o.slice(i,a).replace(/[^]/g,"$&̲"),u;i>15?u="…"+o.slice(i-15,i):u=o.slice(0,i);var h;a+15<o.length?h=o.slice(a,a+15)+"…":h=o.slice(a),n+=u+l+h}super(n),this.name="ParseError",this.position=void 0,this.length=void 0,this.rawMessage=void 0,Object.setPrototypeOf(this,Bt.prototype),this.position=i,i!=null&&a!=null&&(this.length=a-i),this.rawMessage=e}}var Jct=/([A-Z])/g,eut=t=>t.replace(Jct,"-$1").toLowerCase(),tut={"&":"&",">":">","<":"<",'"':""","'":"'"},rut=/[&><"']/g,Gs=t=>String(t).replace(rut,e=>tut[e]),US=t=>t.type==="ordgroup"||t.type==="color"?t.body.length===1?US(t.body[0]):t:t.type==="font"?US(t.body):t,nut=new Set(["mathord","textord","atom"]),Gd=t=>nut.has(US(t).type),iut=t=>{var e=/^[\x00-\x20]*([^\\/#?]*?)(:|�*58|�*3a|&colon)/i.exec(t);return e?e[2]!==":"||!/^[a-zA-Z][a-zA-Z0-9+\-.]*$/.test(e[1])?null:e[1].toLowerCase():"_relative"},q8={displayMode:{type:"boolean",description:"Render math in display mode, which puts the math in display style (so \\int and \\sum are large, for example), and centers the math on the page on its own line.",cli:"-d, --display-mode"},output:{type:{enum:["htmlAndMathml","html","mathml"]},description:"Determines the markup language of the output.",cli:"-F, --format <type>"},leqno:{type:"boolean",description:"Render display math in leqno style (left-justified tags)."},fleqn:{type:"boolean",description:"Render display math flush left."},throwOnError:{type:"boolean",default:!0,cli:"-t, --no-throw-on-error",cliDescription:"Render errors (in the color given by --error-color) instead of throwing a ParseError exception when encountering an error."},errorColor:{type:"string",default:"#cc0000",cli:"-c, --error-color <color>",cliDescription:"A color string given in the format 'rgb' or 'rrggbb' (no #). This option determines the color of errors rendered by the -t option.",cliProcessor:t=>"#"+t},macros:{type:"object",cli:"-m, --macro <def>",cliDescription:"Define custom macro of the form '\\foo:expansion' (use multiple -m arguments for multiple macros).",cliDefault:[],cliProcessor:(t,e)=>(e.push(t),e)},minRuleThickness:{type:"number",description:"Specifies a minimum thickness, in ems, for fraction lines, `\\sqrt` top lines, `{array}` vertical lines, `\\hline`, `\\hdashline`, `\\underline`, `\\overline`, and the borders of `\\fbox`, `\\boxed`, and `\\fcolorbox`.",processor:t=>Math.max(0,t),cli:"--min-rule-thickness <size>",cliProcessor:parseFloat},colorIsTextColor:{type:"boolean",description:"Makes \\color behave like LaTeX's 2-argument \\textcolor, instead of LaTeX's one-argument \\color mode change.",cli:"-b, --color-is-text-color"},strict:{type:[{enum:["warn","ignore","error"]},"boolean","function"],description:"Turn on strict / LaTeX faithfulness mode, which throws an error if the input uses features that are not supported by LaTeX.",cli:"-S, --strict",cliDefault:!1},trust:{type:["boolean","function"],description:"Trust the input, enabling all HTML features such as \\url.",cli:"-T, --trust"},maxSize:{type:"number",default:1/0,description:"If non-zero, all user-specified sizes, e.g. in \\rule{500em}{500em}, will be capped to maxSize ems. Otherwise, elements and spaces can be arbitrarily large",processor:t=>Math.max(0,t),cli:"-s, --max-size <n>",cliProcessor:parseInt},maxExpand:{type:"number",default:1e3,description:"Limit the number of macro expansions to the specified number, to prevent e.g. infinite macro loops. If set to Infinity, the macro expander will try to fully expand as in LaTeX.",processor:t=>Math.max(0,t),cli:"-e, --max-expand <n>",cliProcessor:t=>t==="Infinity"?1/0:parseInt(t)},globalGroup:{type:"boolean",cli:!1}};function aut(t){if(typeof t!="string")return t.enum[0];switch(t){case"boolean":return!1;case"string":return"";case"number":return 0;case"object":return{};default:throw new Error("Unexpected schema type; settings must declare an explicit default.")}}function sut(t){if(t.default!==void 0)return t.default;var e=Array.isArray(t.type)?t.type[0]:t.type;return aut(e)}function out(t,e,r,n){var i=r[e];t[e]=i!==void 0?n.processor?n.processor(i):i:sut(n)}class Kq{constructor(e){e===void 0&&(e={}),this.displayMode=void 0,this.output=void 0,this.leqno=void 0,this.fleqn=void 0,this.throwOnError=void 0,this.errorColor=void 0,this.macros=void 0,this.minRuleThickness=void 0,this.colorIsTextColor=void 0,this.strict=void 0,this.trust=void 0,this.maxSize=void 0,this.maxExpand=void 0,this.globalGroup=void 0,e=e||{};for(var r of Object.keys(q8)){var n=q8[r];n&&out(this,r,e,n)}}reportNonstrict(e,r,n){var i=this.strict;if(typeof i=="function"&&(i=i(e,r,n)),!(!i||i==="ignore")){if(i===!0||i==="error")throw new Bt("LaTeX-incompatible input and strict mode is set to 'error': "+(r+" ["+e+"]"),n);i==="warn"?typeof console<"u"&&console.warn("LaTeX-incompatible input and strict mode is set to 'warn': "+(r+" ["+e+"]")):typeof console<"u"&&console.warn("LaTeX-incompatible input and strict mode is set to "+("unrecognized '"+i+"': "+r+" ["+e+"]"))}}useStrictBehavior(e,r,n){var i=this.strict;if(typeof i=="function")try{i=i(e,r,n)}catch{i="error"}return!i||i==="ignore"?!1:i===!0||i==="error"?!0:i==="warn"?(typeof console<"u"&&console.warn("LaTeX-incompatible input and strict mode is set to 'warn': "+(r+" ["+e+"]")),!1):(typeof console<"u"&&console.warn("LaTeX-incompatible input and strict mode is set to "+("unrecognized '"+i+"': "+r+" ["+e+"]")),!1)}isTrusted(e){if("url"in e&&e.url&&!e.protocol){var r=iut(e.url);if(r==null)return!1;e.protocol=r}var n=typeof this.trust=="function"?this.trust(e):this.trust;return!!n}}class hf{constructor(e,r,n){this.id=void 0,this.size=void 0,this.cramped=void 0,this.id=e,this.size=r,this.cramped=n}sup(){return Au[lut[this.id]]}sub(){return Au[cut[this.id]]}fracNum(){return Au[uut[this.id]]}fracDen(){return Au[hut[this.id]]}cramp(){return Au[dut[this.id]]}text(){return Au[fut[this.id]]}isTight(){return this.size>=2}}var Zq=0,W8=1,Oy=2,fd=3,vw=4,Jl=5,t4=6,mo=7,Au=[new hf(Zq,0,!1),new hf(W8,0,!0),new hf(Oy,1,!1),new hf(fd,1,!0),new hf(vw,2,!1),new hf(Jl,2,!0),new hf(t4,3,!1),new hf(mo,3,!0)],lut=[vw,Jl,vw,Jl,t4,mo,t4,mo],cut=[Jl,Jl,Jl,Jl,mo,mo,mo,mo],uut=[Oy,fd,vw,Jl,t4,mo,t4,mo],hut=[fd,fd,Jl,Jl,mo,mo,mo,mo],dut=[W8,W8,fd,fd,Jl,Jl,mo,mo],fut=[Zq,W8,Oy,fd,Oy,fd,Oy,fd],Zr={DISPLAY:Au[Zq],TEXT:Au[Oy],SCRIPT:Au[vw],SCRIPTSCRIPT:Au[t4]},$P=[{name:"latin",blocks:[[256,591],[768,879]]},{name:"cyrillic",blocks:[[1024,1279]]},{name:"armenian",blocks:[[1328,1423]]},{name:"brahmic",blocks:[[2304,4255]]},{name:"georgian",blocks:[[4256,4351]]},{name:"cjk",blocks:[[12288,12543],[19968,40879],[65280,65376]]},{name:"hangul",blocks:[[44032,55215]]}];function put(t){for(var e=0;e<$P.length;e++)for(var r=$P[e],n=0;n<r.blocks.length;n++){var i=r.blocks[n];if(t>=i[0]&&t<=i[1])return r.name}return null}var YS=[];$P.forEach(t=>t.blocks.forEach(e=>YS.push(...e)));function P2e(t){for(var e=0;e<YS.length;e+=2)if(t>=YS[e]&&t<=YS[e+1])return!0;return!1}var La=t=>t+" "+t,f1=80,gut=function(e,r){return"M95,"+(622+e+r)+`c-2.7,0,-7.17,-2.7,-13.5,-8c-5.8,-5.3,-9.5,-10,-9.5,-14c0,-2,0.3,-3.3,1,-4c1.3,-2.7,23.83,-20.7,67.5,-54c44.2,-33.3,65.8,-50.3,66.5,-51c1.3,-1.3,3,-2,5,-2c4.7,0,8.7,3.3,12,10diff --git a/apps/ios/EditorSource/src/main.ts b/apps/ios/EditorSource/src/main.tsindex 7f59efc9..b4c45b35 100644--- a/apps/ios/EditorSource/src/main.ts+++ b/apps/ios/EditorSource/src/main.ts@@ -142,6 +142,7 @@ type ImageExportRequest = {notebook?: string;tags?: string[];updatedAt?: string;+ background?: "mint" | "slate" | "warm";};let mode: "viewer" | "editor" = "viewer";let locale = "zh-CN";@@ -1125,8 +1126,14 @@ async function exportNoteImage(request: ImageExportRequest) {try { await image.decode(); } catch { /* Export the readable remainder. */ }}));const totalHeight = Math.max(1, Math.ceil(documentRoot.getBoundingClientRect().height));+ const backgroundColor = {+ mint: "#ecfdf5",+ slate: "#f8fafc",+ warm: "#fffbeb",+ }[request.background ?? "slate"];+ documentRoot.style.backgroundColor = backgroundColor;const canvas = await toCanvas(documentRoot, {- backgroundColor: "#f8fafc",+ backgroundColor,height: totalHeight,pixelRatio: IMAGE_EXPORT_PIXEL_RATIO,skipFonts: true,diff --git a/apps/mobile/src/components/LocalTiptapEditor.tsx b/apps/mobile/src/components/LocalTiptapEditor.tsxindex 78c43866..e9b3aba9 100644--- a/apps/mobile/src/components/LocalTiptapEditor.tsx+++ b/apps/mobile/src/components/LocalTiptapEditor.tsx@@ -160,6 +160,7 @@ type ImageExportRequest = {notebook?: string;tags?: string[];updatedAt?: string;+ background?: "mint" | "slate" | "warm";};const IMAGE_EXPORT_LIGHT_STYLES = `@@ -1136,8 +1137,14 @@ function LocalTiptapEditorImpl(props: LocalTiptapEditorProps) {try { await image.decode(); } catch { /* Export the readable remainder. */ }}));const totalHeight = Math.max(1, Math.ceil(documentRoot.getBoundingClientRect().height));+ const backgroundColor = {+ mint: "#ecfdf5",+ slate: "#f8fafc",+ warm: "#fffbeb",+ }[request.background ?? "slate"];+ documentRoot.style.backgroundColor = backgroundColor;const canvas = await toCanvas(documentRoot, {- backgroundColor: "#f8fafc",+ backgroundColor,height: totalHeight,pixelRatio: IMAGE_EXPORT_PIXEL_RATIO,skipFonts: true,diff --git a/apps/mobile/src/screens/WorkspaceMemoDetail.tsx b/apps/mobile/src/screens/WorkspaceMemoDetail.tsxindex db303166..eec31412 100644--- a/apps/mobile/src/screens/WorkspaceMemoDetail.tsx+++ b/apps/mobile/src/screens/WorkspaceMemoDetail.tsx@@ -420,6 +420,12 @@ export const MemoDetailModal = ({const [resourceTarget, setResourceTarget] = useState<MobileResourceTarget | null>(null);const [viewerReady, setViewerReady] = useState(false);const [isExportingImage, setIsExportingImage] = useState(false);+ const [imageShareOptionsOpen, setImageShareOptionsOpen] = useState(false);+ const [imageShareFormat, setImageShareFormat] = useState<"jpeg" | "png">("png");+ const [imageShareBackground, setImageShareBackground] = useState<"mint" | "slate" | "warm">("slate");+ const [imageShareNotebook, setImageShareNotebook] = useState(true);+ const [imageShareTags, setImageShareTags] = useState(true);+ const [imageShareUpdatedAt, setImageShareUpdatedAt] = useState(true);const viewerRef = useRef<LocalTiptapEditorRef>(null);const imageExportRequestRef = useRef<string | null>(null);const imageExportChunksRef = useRef<string[]>([]);@@ -654,7 +660,15 @@ export const MemoDetailModal = ({}}, [resolvedLocale]);- const exportMemoImage = useCallback((format: "jpeg" | "png") => {+ const exportMemoImage = useCallback((+ format: "jpeg" | "png",+ options: {+ background?: "mint" | "slate" | "warm";+ showNotebook?: boolean;+ showTags?: boolean;+ showUpdatedAt?: boolean;+ } = {},+ ) => {if (!memo || !viewerReady || isExportingImage) return;const requestId = `${Date.now()}-${Math.random().toString(36).slice(2)}`;imageExportRequestRef.current = requestId;@@ -665,9 +679,10 @@ export const MemoDetailModal = ({format,title: memo.title?.trim() || (resolvedLocale === "en-US" ? "Untitled note" : "无标题笔记"),fallbackTitle: resolvedLocale === "en-US" ? "Untitled note" : "无标题笔记",- notebook: notebookName,- tags: memo.tags,- updatedAt: new Date(memo.updatedAt).toLocaleString(resolvedLocale),+ notebook: options.showNotebook === false ? "" : notebookName,+ tags: options.showTags === false ? [] : memo.tags,+ updatedAt: options.showUpdatedAt === false ? "" : new Date(memo.updatedAt).toLocaleString(resolvedLocale),+ background: options.background ?? "slate",})));}, [isExportingImage, memo, notebookName, resolvedLocale, viewerReady]);@@ -963,14 +978,20 @@ export const MemoDetailModal = ({/><DetailActionSheetItemdisabled={isExportingImage || !viewerReady}- icon={isExportingImage ? <ActivityIndicator color="#16A06E" size="small" /> : <Download color="#0f172a" size={18} />}- label={isExportingImage ? "正在导出图片" : "导出 PNG"}+ icon={isExportingImage ? <ActivityIndicator color="#16A06E" size="small" /> : <Share2 color="#0f172a" size={18} />}+ label={isExportingImage ? "正在生成分享图片" : "分享为图片"}+ onPress={() => closeActionsAndRun(() => setImageShareOptionsOpen(true))}+ />+ <DetailActionSheetItem+ disabled={isExportingImage || !viewerReady}+ icon={<Download color="#0f172a" size={18} />}+ label="高级导出 PNG"onPress={() => closeActionsAndRun(() => exportMemoImage("png"))}/><DetailActionSheetItemdisabled={isExportingImage || !viewerReady}icon={<Download color="#0f172a" size={18} />}- label="导出 JPEG"+ label="高级导出 JPEG"onPress={() => closeActionsAndRun(() => exportMemoImage("jpeg"))}/>{memo.isDeleted ? (@@ -988,6 +1009,68 @@ export const MemoDetailModal = ({</Pressable></Modal>) : null}+ <Modal animationType="fade" onRequestClose={() => setImageShareOptionsOpen(false)} transparent visible={imageShareOptionsOpen}>+ <Pressable onPress={() => setImageShareOptionsOpen(false)} style={styles.actionSheetBackdrop}>+ <Pressable style={styles.actionSheet}>+ <View style={styles.actionSheetHandle} />+ <Text style={styles.actionSheetTitle}>分享为图片</Text>+ <Text style={imageShareStyles.description}>生成一张完整长图,并通过系统分享面板发送。</Text>+ <Text style={styles.actionSheetSectionTitle}>背景</Text>+ <View style={imageShareStyles.choiceRow}>+ {(["slate", "mint", "warm"] as const).map((value) => (+ <Pressable+ key={value}+ accessibilityRole="button"+ onPress={() => setImageShareBackground(value)}+ style={[+ imageShareStyles.choice,+ value === "slate" ? imageShareStyles.slateChoice : value === "mint" ? imageShareStyles.mintChoice : imageShareStyles.warmChoice,+ imageShareBackground === value && imageShareStyles.choiceActive,+ ]}+ >+ <Text style={imageShareStyles.choiceText}>{value === "slate" ? "简洁" : value === "mint" ? "薄荷" : "暖色"}</Text>+ </Pressable>+ ))}+ </View>+ <Text style={styles.actionSheetSectionTitle}>笔记信息</Text>+ {([+ ["笔记本", imageShareNotebook, setImageShareNotebook],+ ["标签", imageShareTags, setImageShareTags],+ ["更新时间", imageShareUpdatedAt, setImageShareUpdatedAt],+ ] as const).map(([label, selected, setSelected]) => (+ <Pressable key={label} accessibilityRole="checkbox" accessibilityState={{ checked: selected }} onPress={() => setSelected(!selected)} style={imageShareStyles.optionRow}>+ <Text style={imageShareStyles.optionLabel}>{label}</Text>+ <Text style={imageShareStyles.optionCheck}>{selected ? "✓" : ""}</Text>+ </Pressable>+ ))}+ <Text style={styles.actionSheetSectionTitle}>格式</Text>+ <View style={imageShareStyles.choiceRow}>+ {(["png", "jpeg"] as const).map((value) => (+ <Pressable key={value} accessibilityRole="button" onPress={() => setImageShareFormat(value)} style={[imageShareStyles.formatChoice, imageShareFormat === value && imageShareStyles.choiceActive]}>+ <Text style={imageShareStyles.choiceText}>{value === "png" ? "PNG · 文字更清晰" : "JPEG · 文件更小"}</Text>+ </Pressable>+ ))}+ </View>+ <Pressable+ accessibilityRole="button"+ disabled={isExportingImage}+ onPress={() => {+ setImageShareOptionsOpen(false);+ exportMemoImage(imageShareFormat, {+ background: imageShareBackground,+ showNotebook: imageShareNotebook,+ showTags: imageShareTags,+ showUpdatedAt: imageShareUpdatedAt,+ });+ }}+ style={[imageShareStyles.shareButton, isExportingImage && styles.buttonDisabled]}+ >+ <Share2 color="#ffffff" size={18} />+ <Text style={imageShareStyles.shareButtonText}>生成并分享</Text>+ </Pressable>+ </Pressable>+ </Pressable>+ </Modal>{memo && !memo.isDeleted ? (<MobileAiAssistantModalmemo={memo}@@ -1054,6 +1137,89 @@ export const MemoDetailModal = ({);};+const imageShareStyles = StyleSheet.create({+ choice: {+ alignItems: "center",+ borderColor: "#cbd5e1",+ borderRadius: 8,+ borderWidth: 1,+ flex: 1,+ justifyContent: "center",+ minHeight: 42,+ paddingHorizontal: 8,+ },+ choiceActive: {+ borderColor: "#16A06E",+ borderWidth: 2,+ },+ choiceRow: {+ flexDirection: "row",+ gap: 8,+ },+ choiceText: {+ color: "#0f172a",+ fontSize: 12,+ fontWeight: "700",+ },+ description: {+ color: "#64748b",+ fontSize: 13,+ lineHeight: 20,+ },+ formatChoice: {+ alignItems: "center",+ borderColor: "#cbd5e1",+ borderRadius: 8,+ borderWidth: 1,+ flex: 1,+ justifyContent: "center",+ minHeight: 44,+ paddingHorizontal: 8,+ },+ mintChoice: {+ backgroundColor: "#ecfdf5",+ },+ optionCheck: {+ color: "#16A06E",+ fontSize: 18,+ fontWeight: "800",+ width: 24,+ },+ optionLabel: {+ color: "#0f172a",+ flex: 1,+ fontSize: 14,+ fontWeight: "600",+ },+ optionRow: {+ alignItems: "center",+ flexDirection: "row",+ minHeight: 42,+ paddingHorizontal: 8,+ },+ shareButton: {+ alignItems: "center",+ backgroundColor: "#16A06E",+ borderRadius: 9,+ flexDirection: "row",+ gap: 8,+ justifyContent: "center",+ marginTop: 12,+ minHeight: 48,+ },+ shareButtonText: {+ color: "#ffffff",+ fontSize: 15,+ fontWeight: "800",+ },+ slateChoice: {+ backgroundColor: "#f8fafc",+ },+ warmChoice: {+ backgroundColor: "#fffbeb",+ },+});+const detailLayoutStyles = StyleSheet.create({body: {flex: 1,diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsxindex d9158ce8..cd247c21 100644--- a/apps/web/src/components/EditorPane.tsx+++ b/apps/web/src/components/EditorPane.tsx@@ -39,6 +39,7 @@ import {ImageDown,Printer,Link2,+ Share2,Copy,} from "lucide-react";import { Button } from "@/components/ui/button";@@ -96,6 +97,7 @@ import { sanitizeAndScopeCss } from "@/lib/css-sandbox";import { RevisionHistoryDialog } from "./dialogs/RevisionHistoryDialog";import { ExternalLinkDialog } from "./dialogs/ExternalLinkDialog";import { memoShareQueryKey, ShareMemoDialog } from "./dialogs/ShareMemoDialog";+import { ShareNoteImageDialog, type ShareNoteImageSource } from "./dialogs/ShareNoteImageDialog";import { AiAssistantDialog, type AiAssistantAnchor } from "./dialogs/AiAssistantDialog";import { api } from "@/lib/api";import { isDesktopResourceRuntime, stageDesktopResource, toDesktopResourceUrl } from "@/lib/desktop-resources";@@ -766,6 +768,8 @@ const RichEditorPane = ({const [imagePreview, setImagePreview] = useState<ImagePreviewRequestDetail | null>(null);const [historyOpen, setHistoryOpen] = useState(false);const [shareOpen, setShareOpen] = useState(false);+ const [imageShareOpen, setImageShareOpen] = useState(false);+ const [imageShareSource, setImageShareSource] = useState<ShareNoteImageSource | null>(null);const [aiAssistantOpen, setAiAssistantOpen] = useState(false);const [aiAssistantAnchor, setAiAssistantAnchor] = useState<AiAssistantAnchor>({ left: 24, placement: "below", top: 96 });const aiBubbleMenu = useAiBubbleMenu(aiAssistantOpen);@@ -2861,33 +2865,51 @@ const RichEditorPane = ({useMobilePlainTextEditor,]);+ const buildImageExportOptions = useCallback((format: NoteImageFormat) => {+ if (!isEditorReady(editor) || !memo) return;+ const currentDocument = useMobilePlainTextEditor+ ? markdownToDoc(getMobilePlainTextValue())+ : useMarkdownSourceEditor+ ? markdownToDoc(markdownSource)+ : editor.getJSON() as TiptapDoc;+ return {+ bodyHtml: serializeNoteDocumentForPrint(editor, currentDocument),+ title: title.trim() || t("common.untitledMemo"),+ notebook: notebookOptions.find((notebook) => notebook.id === memo.notebookId)?.name ?? "",+ tags: parseTagsText(tagsText),+ updatedAt: formatDateTime(memo.updatedAt),+ language: i18n.resolvedLanguage ?? i18n.language,+ fallbackTitle: t("common.untitledMemo"),+ format,+ styles: NOTE_HTML_FULL_STYLES,+ };+ }, [+ editor,+ getMobilePlainTextValue,+ i18n.language,+ i18n.resolvedLanguage,+ markdownSource,+ memo,+ notebookOptions,+ t,+ tagsText,+ title,+ useMarkdownSourceEditor,+ useMobilePlainTextEditor,+ ]);+const imageExportInProgressRef = useRef(false);const handleExportImage = useCallback(async (format: NoteImageFormat) => {- if (!isEditorReady(editor) || !memo) return;+ const options = buildImageExportOptions(format);+ if (!options) return;if (imageExportInProgressRef.current) {window.alert(t("editor.imageExport.inProgress"));return;}imageExportInProgressRef.current = true;- const currentDocument = useMobilePlainTextEditor- ? markdownToDoc(getMobilePlainTextValue())- : useMarkdownSourceEditor- ? markdownToDoc(markdownSource)- : editor.getJSON() as TiptapDoc;-try {- const result = await downloadNoteImage({- bodyHtml: serializeNoteDocumentForPrint(editor, currentDocument),- title: title.trim() || t("common.untitledMemo"),- notebook: notebookOptions.find((notebook) => notebook.id === memo.notebookId)?.name ?? "",- tags: parseTagsText(tagsText),- updatedAt: formatDateTime(memo.updatedAt),- language: i18n.resolvedLanguage ?? i18n.language,- fallbackTitle: t("common.untitledMemo"),- format,- styles: NOTE_HTML_FULL_STYLES,- });+ const result = await downloadNoteImage(options);const noticeKind = getHtmlImageEmbedNoticeKind(result.images);if (noticeKind === "partial") {window.alert(t("editor.imageExport.imageEmbedPartial", result.images));@@ -2900,20 +2922,18 @@ const RichEditorPane = ({imageExportInProgressRef.current = false;}}, [- editor,- getMobilePlainTextValue,- i18n.language,- i18n.resolvedLanguage,- markdownSource,- memo,- notebookOptions,+ buildImageExportOptions,t,- tagsText,- title,- useMarkdownSourceEditor,- useMobilePlainTextEditor,]);+ const handleOpenImageShare = useCallback(() => {+ const options = buildImageExportOptions("png");+ if (!options) return;+ const { format: _format, ...source } = options;+ setImageShareSource(source);+ setImageShareOpen(true);+ }, [buildImageExportOptions]);+const handleSaveAsTemplate = useCallback(() => {if (!memo) {return;@@ -2964,6 +2984,9 @@ const RichEditorPane = ({case "export-pdf":handleExportPdf(documentActionRequest.printWindow);break;+ case "share-image":+ handleOpenImageShare();+ break;case "export-png":void handleExportImage("png");break;@@ -2981,6 +3004,7 @@ const RichEditorPane = ({handleExportImage,handleExportMarkdown,handleExportPdf,+ handleOpenImageShare,handleSaveAsTemplate,hydratedEditorMemoId,memo,@@ -4290,6 +4314,13 @@ const RichEditorPane = ({<Printer className="h-4 w-4 text-slate-500" />{t("editor.exportPdf")}</DropdownMenuItem>+ <DropdownMenuItem+ className="flex h-9 w-full items-center gap-2 px-3 text-left text-sm text-slate-700 hover:bg-slate-50 cursor-pointer outline-none"+ onClick={handleOpenImageShare}+ >+ <Share2 className="h-4 w-4 text-slate-500" />+ {t("editor.imageShare.action")}+ </DropdownMenuItem><DropdownMenuItemclassName="flex h-9 w-full items-center gap-2 px-3 text-left text-sm text-slate-700 hover:bg-slate-50 cursor-pointer outline-none"onClick={() => void handleExportImage("png")}@@ -5003,6 +5034,14 @@ const RichEditorPane = ({<ShareMemoDialog memoId={memo.id} open={shareOpen} onOpenChange={setShareOpen} />+ {imageShareSource && (+ <ShareNoteImageDialog+ open={imageShareOpen}+ source={imageShareSource}+ onOpenChange={setImageShareOpen}+ />+ )}+{mobileNotebookSheetOpen && (<MobileNotebookSelectSheetisUpdating={notebookUpdatePending || saveMutation.isPending}diff --git a/apps/web/src/components/MemoListPane.tsx b/apps/web/src/components/MemoListPane.tsxindex 2f328db7..29d7b9e7 100644--- a/apps/web/src/components/MemoListPane.tsx+++ b/apps/web/src/components/MemoListPane.tsx@@ -40,6 +40,7 @@ import {CheckCircle2,TagX,Link2,+ Share2,FileDown,FileCode2,ImageDown,@@ -1580,6 +1581,13 @@ export const MemoListPane = ({<Printer className="h-4 w-4 text-slate-500" />{t("editor.exportPdf")}</DropdownMenuItem>+ <DropdownMenuItem+ className="flex h-9 w-full items-center gap-2 px-3 text-left text-sm text-slate-700 hover:bg-slate-50 cursor-pointer outline-none"+ onClick={() => requestContextDocumentAction("share-image")}+ >+ <Share2 className="h-4 w-4 text-slate-500" />+ {t("editor.imageShare.action")}+ </DropdownMenuItem><DropdownMenuItemclassName="flex h-9 w-full items-center gap-2 px-3 text-left text-sm text-slate-700 hover:bg-slate-50 cursor-pointer outline-none"onClick={() => requestContextDocumentAction("export-png")}diff --git a/apps/web/src/components/dialogs/ShareNoteImageDialog.tsx b/apps/web/src/components/dialogs/ShareNoteImageDialog.tsxnew file mode 100644index 00000000..ec38d397--- /dev/null+++ b/apps/web/src/components/dialogs/ShareNoteImageDialog.tsx@@ -0,0 +1,217 @@+import { Download, LoaderCircle, Share2 } from "lucide-react";+import { useEffect, useMemo, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { Button } from "@/components/ui/button";+import { Checkbox } from "@/components/ui/checkbox";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import {+ createNoteImage,+ downloadPreparedNoteImage,+ type DownloadNoteImageOptions,+ type NoteImageBackground,+ type NoteImageFormat,+ type PreparedNoteImage,+} from "@/lib/note-image-export";+import { getHtmlImageEmbedNoticeKind } from "@/lib/note-html-export";+import { cn } from "@/lib/utils";++export type ShareNoteImageSource = Omit<DownloadNoteImageOptions, "background" | "format">;++export const ShareNoteImageDialog = ({+ open,+ onOpenChange,+ source,+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ source: ShareNoteImageSource;+}) => {+ const { t } = useTranslation();+ const [format, setFormat] = useState<NoteImageFormat>("png");+ const [background, setBackground] = useState<NoteImageBackground>("slate");+ const [showNotebook, setShowNotebook] = useState(true);+ const [showTags, setShowTags] = useState(true);+ const [showUpdatedAt, setShowUpdatedAt] = useState(true);+ const [prepared, setPrepared] = useState<PreparedNoteImage | null>(null);+ const [previewUrl, setPreviewUrl] = useState("");+ const [error, setError] = useState(false);+ const generationRef = useRef(0);++ useEffect(() => {+ if (!open) return;+ setFormat("png");+ setBackground("slate");+ setShowNotebook(true);+ setShowTags(true);+ setShowUpdatedAt(true);+ }, [open, source.title]);++ useEffect(() => {+ if (!open) return;+ const generation = ++generationRef.current;+ setPrepared(null);+ setError(false);+ const timer = window.setTimeout(() => {+ void createNoteImage({+ ...source,+ background,+ format,+ notebook: showNotebook ? source.notebook : "",+ tags: showTags ? source.tags : [],+ updatedAt: showUpdatedAt ? source.updatedAt : "",+ }).then((result) => {+ if (generation !== generationRef.current) return;+ setPreviewUrl((current) => {+ if (current) URL.revokeObjectURL(current);+ return URL.createObjectURL(result.blob);+ });+ setPrepared(result);+ }).catch(() => {+ if (generation === generationRef.current) setError(true);+ });+ }, 180);+ return () => window.clearTimeout(timer);+ }, [background, format, open, showNotebook, showTags, showUpdatedAt, source]);++ useEffect(() => () => {+ generationRef.current += 1;+ if (previewUrl) URL.revokeObjectURL(previewUrl);+ }, [previewUrl]);++ const shareFile = useMemo(() => prepared+ ? new File([prepared.blob], prepared.filename, { type: prepared.mimeType })+ : null, [prepared]);+ const canUseSystemShare = Boolean(+ shareFile && navigator.canShare?.({ files: [shareFile] }) && navigator.share,+ );+ const noticeKind = prepared ? getHtmlImageEmbedNoticeKind(prepared.images) : "none";++ const complete = async () => {+ if (!prepared || !shareFile) return;+ if (canUseSystemShare) {+ try {+ await navigator.share({ files: [shareFile], title: source.title });+ onOpenChange(false);+ } catch (shareError) {+ if (shareError instanceof DOMException && shareError.name === "AbortError") return;+ setError(true);+ }+ return;+ }+ downloadPreparedNoteImage(prepared);+ onOpenChange(false);+ };++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-h-[92vh] max-w-4xl gap-0 overflow-hidden p-0">+ <DialogHeader className="border-b border-slate-200 px-5 py-4 pr-12 text-left">+ <DialogTitle className="flex items-center gap-2 text-base">+ <Share2 className="h-5 w-5 text-emerald-600" />+ {t("editor.imageShare.title")}+ </DialogTitle>+ <DialogDescription>{t("editor.imageShare.description")}</DialogDescription>+ </DialogHeader>++ <div className="grid min-h-0 flex-1 gap-0 md:grid-cols-[minmax(0,1fr)_18rem]">+ <div className="min-h-64 overflow-auto bg-slate-100 p-4 md:max-h-[68vh]">+ {previewUrl && prepared ? (+ <img+ alt={t("editor.imageShare.previewAlt")}+ className="mx-auto block h-auto w-full max-w-[32rem] rounded-md shadow-lg"+ src={previewUrl}+ />+ ) : error ? (+ <div className="flex min-h-64 items-center justify-center text-sm text-rose-600" role="alert">+ {t("editor.imageExport.error")}+ </div>+ ) : (+ <div className="flex min-h-64 items-center justify-center gap-2 text-sm text-slate-500" role="status">+ <LoaderCircle className="h-5 w-5 animate-spin" />+ {t("editor.imageShare.generating")}+ </div>+ )}+ </div>++ <div className="space-y-5 overflow-y-auto border-t border-slate-200 p-5 md:max-h-[68vh] md:border-l md:border-t-0">+ <fieldset className="space-y-2">+ <legend className="text-xs font-semibold uppercase tracking-wide text-slate-500">+ {t("editor.imageShare.background")}+ </legend>+ <div className="grid grid-cols-3 gap-2">+ {(["slate", "mint", "warm"] as const).map((value) => (+ <button+ key={value}+ aria-pressed={background === value}+ className={cn(+ "h-10 rounded-md border text-xs font-medium outline-none focus-visible:ring-2 focus-visible:ring-emerald-500",+ value === "slate" && "bg-slate-50",+ value === "mint" && "bg-emerald-50",+ value === "warm" && "bg-amber-50",+ background === value ? "border-emerald-500 ring-1 ring-emerald-500" : "border-slate-200",+ )}+ type="button"+ onClick={() => setBackground(value)}+ >+ {t(`editor.imageShare.backgrounds.${value}`)}+ </button>+ ))}+ </div>+ </fieldset>++ <fieldset className="space-y-3">+ <legend className="text-xs font-semibold uppercase tracking-wide text-slate-500">+ {t("editor.imageShare.metadata")}+ </legend>+ {([+ ["notebook", showNotebook, setShowNotebook],+ ["tags", showTags, setShowTags],+ ["updatedAt", showUpdatedAt, setShowUpdatedAt],+ ] as const).map(([key, checked, setChecked]) => (+ <label key={key} className="flex cursor-pointer items-center gap-2 text-sm text-slate-700">+ <Checkbox checked={checked} onCheckedChange={(value) => setChecked(value === true)} />+ {t(`editor.imageShare.fields.${key}`)}+ </label>+ ))}+ </fieldset>++ <label className="grid gap-2 text-xs font-semibold uppercase tracking-wide text-slate-500">+ {t("editor.imageShare.format")}+ <Select value={format} onValueChange={(value) => setFormat(value as NoteImageFormat)}>+ <SelectTrigger className="font-normal normal-case tracking-normal text-slate-700">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="png">PNG · {t("editor.imageShare.pngHint")}</SelectItem>+ <SelectItem value="jpeg">JPEG · {t("editor.imageShare.jpegHint")}</SelectItem>+ </SelectContent>+ </Select>+ </label>++ {noticeKind !== "none" ? (+ <p className="text-xs leading-5 text-amber-700">+ {t(noticeKind === "partial" ? "editor.imageExport.imageEmbedPartial" : "editor.imageExport.imageEmbedFailed", prepared?.images)}+ </p>+ ) : null}+ </div>+ </div>++ <DialogFooter className="border-t border-slate-200 px-5 py-4">+ <Button variant="ghost" onClick={() => onOpenChange(false)}>{t("common.cancel")}</Button>+ <Button variant="solid" disabled={!prepared} onClick={() => void complete()}>+ {canUseSystemShare ? <Share2 className="h-4 w-4" /> : <Download className="h-4 w-4" />}+ {t(canUseSystemShare ? "editor.imageShare.share" : "editor.imageShare.download")}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+};diff --git a/apps/web/src/lib/app-helpers.ts b/apps/web/src/lib/app-helpers.tsindex 1bb3c9cb..2d1deca6 100644--- a/apps/web/src/lib/app-helpers.ts+++ b/apps/web/src/lib/app-helpers.ts@@ -35,6 +35,7 @@ export type MemoDocumentAction =| "export-markdown"| "export-html"| "export-pdf"+ | "share-image"| "export-png"| "export-jpeg"| "save-as-template";diff --git a/apps/web/src/lib/note-image-export.ts b/apps/web/src/lib/note-image-export.tsindex cc834c7c..c7bb643e 100644--- a/apps/web/src/lib/note-image-export.ts+++ b/apps/web/src/lib/note-image-export.ts@@ -6,23 +6,32 @@ import {} from "@/lib/note-html-export";export type NoteImageFormat = "jpeg" | "png";+export type NoteImageBackground = "mint" | "slate" | "warm";export type DownloadNoteImageOptions = NoteHtmlExportMeta & {bodyHtml: string;fallbackTitle: string;format: NoteImageFormat;+ background?: NoteImageBackground;styles: string;};-export type DownloadNoteImageResult = {+export type PreparedNoteImage = {+ blob: Blob;filename: string;images: HtmlImageEmbedResult;+ mimeType: "image/jpeg" | "image/png";};export const NOTE_IMAGE_EXPORT_WIDTH = 768;export const NOTE_IMAGE_EXPORT_PIXEL_RATIO = 1.5;const WINDOWS_RESERVED_NAME = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i;+const NOTE_IMAGE_BACKGROUND_COLORS: Record<NoteImageBackground, string> = {+ mint: "#ecfdf5",+ slate: "#f8fafc",+ warm: "#fffbeb",+};export const buildImageExportBasename = (title: string, fallback: string) => {const sanitized = title@@ -44,7 +53,7 @@ const canvasToImageBlob = (canvas: HTMLCanvasElement, format: NoteImageFormat) =);});-const downloadBlob = (blob: Blob, filename: string) => {+export const downloadPreparedNoteImage = ({ blob, filename }: Pick<PreparedNoteImage, "blob" | "filename">) => {const url = URL.createObjectURL(blob);const link = document.createElement("a");link.href = url;@@ -67,12 +76,12 @@ const waitForImages = async (root: HTMLElement) => {}));};-const renderImage = async (source: HTMLElement, format: NoteImageFormat) => {+const renderImage = async (source: HTMLElement, format: NoteImageFormat, backgroundColor: string) => {await document.fonts?.ready;await waitForImages(source);const totalHeight = Math.max(1, Math.ceil(source.getBoundingClientRect().height));const canvas = await toCanvas(source, {- backgroundColor: "#f8fafc",+ backgroundColor,cacheBust: false,height: totalHeight,pixelRatio: NOTE_IMAGE_EXPORT_PIXEL_RATIO,@@ -82,7 +91,7 @@ const renderImage = async (source: HTMLElement, format: NoteImageFormat) => {return canvasToImageBlob(canvas, format);};-export const downloadNoteImage = async ({+export const createNoteImage = async ({bodyHtml,title,notebook,@@ -90,8 +99,9 @@ export const downloadNoteImage = async ({updatedAt,fallbackTitle,format,+ background = "slate",styles,-}: DownloadNoteImageOptions): Promise<DownloadNoteImageResult> => {+}: DownloadNoteImageOptions): Promise<PreparedNoteImage> => {const prepared = await prepareNoteBodyHtmlForExport(bodyHtml);const host = document.createElement("div");host.style.cssText = [@@ -115,17 +125,27 @@ export const downloadNoteImage = async ({source.style.width = `${NOTE_IMAGE_EXPORT_WIDTH}px`;source.style.maxWidth = "none";source.style.margin = "0";+ source.style.backgroundColor = NOTE_IMAGE_BACKGROUND_COLORS[background];document.body.appendChild(host);try {- const image = await renderImage(source, format);+ const blob = await renderImage(source, format, NOTE_IMAGE_BACKGROUND_COLORS[background]);const basename = buildImageExportBasename(title, fallbackTitle);const extension = format === "jpeg" ? "jpg" : "png";const filename = `${basename}.${extension}`;- downloadBlob(image, filename);-- return { filename, images: prepared.images };+ return {+ blob,+ filename,+ images: prepared.images,+ mimeType: format === "jpeg" ? "image/jpeg" : "image/png",+ };} finally {host.remove();}};++export const downloadNoteImage = async (options: DownloadNoteImageOptions) => {+ const prepared = await createNoteImage(options);+ downloadPreparedNoteImage(prepared);+ return prepared;+};diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.tsindex 7c47071e..d80e42af 100644--- a/packages/shared/src/i18n/en-US.ts+++ b/packages/shared/src/i18n/en-US.ts@@ -1017,6 +1017,30 @@ export const enUS = {imageEmbedFailed:"Image exported, but none of the {{total}} note images could be included.",},+ imageShare: {+ title: "Share as image",+ description: "Preview the complete long image and choose what information to include.",+ previewAlt: "Note image share preview",+ generating: "Generating preview…",+ background: "Background",+ backgrounds: {+ slate: "Clean",+ mint: "Mint",+ warm: "Warm",+ },+ metadata: "Note information",+ fields: {+ notebook: "Notebook",+ tags: "Tags",+ updatedAt: "Updated time",+ },+ format: "Image format",+ pngHint: "best for text",+ jpegHint: "smaller file",+ share: "Share image",+ download: "Download image",+ action: "Share as image",+ },htmlExport: {error: "Could not export the note as HTML.",imageEmbedPartial:diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.tsindex 9104dbaf..55dc850c 100644--- a/packages/shared/src/i18n/zh-CN.ts+++ b/packages/shared/src/i18n/zh-CN.ts@@ -1015,6 +1015,30 @@ export const zhCN = {imageEmbedPartial: "图片已导出,但笔记中的 {{total}} 张图片有 {{failed}} 张未能包含。",imageEmbedFailed: "图片已导出,但笔记中的 {{total}} 张图片均未能包含。",},+ imageShare: {+ title: "分享为图片",+ description: "预览完整长图,并选择图片中包含的笔记信息。",+ previewAlt: "笔记分享图片预览",+ generating: "正在生成预览…",+ background: "背景",+ backgrounds: {+ slate: "简洁",+ mint: "薄荷",+ warm: "暖色",+ },+ metadata: "笔记信息",+ fields: {+ notebook: "笔记本",+ tags: "标签",+ updatedAt: "更新时间",+ },+ format: "图片格式",+ pngHint: "文字更清晰",+ jpegHint: "文件更小",+ share: "分享图片",+ download: "下载图片",+ action: "分享为图片",+ },htmlExport: {error: "导出 HTML 失败。",imageEmbedPartial:diff --git a/tests/e2e/note-image-export.spec.ts b/tests/e2e/note-image-export.spec.tsindex 923d127c..49ed11d8 100644--- a/tests/e2e/note-image-export.spec.ts+++ b/tests/e2e/note-image-export.spec.ts@@ -24,7 +24,8 @@ const inspectDownload = async (download: Download) => {const image = sharp(path!);const metadata = await image.metadata();const statistics = await image.stats();- return { metadata, statistics };+ const { data: pixels, info } = await sharp(path!).raw().toBuffer({ resolveWithObject: true });+ return { metadata, statistics, topLeft: Array.from(pixels.slice(0, info.channels)) };};test("exports a long note as one non-blank PNG and JPEG", async ({ page, request }) => {@@ -64,6 +65,27 @@ test("exports a long note as one non-blank PNG and JPEG", async ({ page, requestexpect(metadata.height).toBeGreaterThan(4_800);expect(statistics.channels.some((channel) => channel.stdev > 5)).toBe(true);}++ await page.getByRole("button", { name: /笔记更多操作|More note actions/ }).click();+ await page.getByRole("menuitem", { name: /分享为图片|Share as image/ }).click();+ const dialog = page.getByRole("dialog", { name: /分享为图片|Share as image/ });+ await expect(dialog).toBeVisible();+ await expect(dialog.getByRole("img", { name: /笔记分享图片预览|Note image share preview/ })).toBeVisible({ timeout: 20_000 });+ await dialog.getByRole("button", { name: /薄荷|Mint/ }).click();+ await dialog.getByRole("checkbox", { name: /笔记本|Notebook/ }).click();+ await dialog.getByRole("combobox").click();+ await page.getByRole("option", { name: /JPEG/ }).click();+ await expect(dialog.getByText(/正在生成预览|Generating preview/)).toBeHidden({ timeout: 20_000 });++ const shareDownloadPromise = page.waitForEvent("download");+ await dialog.getByRole("button", { name: /下载图片|Download image/ }).click();+ const shareDownload = await shareDownloadPromise;+ expect(shareDownload.suggestedFilename()).toMatch(/\.jpg$/i);+ const sharedImage = await inspectDownload(shareDownload);+ expect(sharedImage.metadata.format).toBe("jpeg");+ expect(sharedImage.metadata.height).toBeGreaterThan(4_800);+ expect(sharedImage.statistics.channels.some((channel) => channel.stdev > 5)).toBe(true);+ expect(sharedImage.topLeft.slice(0, 3).every((value, index) => Math.abs(value - [236, 253, 245][index]) < 20)).toBe(true);} finally {await request.delete(`/api/v1/memos/${memoId}`);await request.delete(`/api/v1/memos/${memoId}?permanent=1`);